Exemple #1
0
 def __init__(self):
     ShowBase.__init__(self)
     cm = CardMaker("cm")
     cm.setFrame(Point3(-1, -1, -1), Point3(1, -1, -1), Point3(1, 1, -1),
                 Point3(-1, 1, -1))
     model = self.hidden.attachNewNode(cm.generate())
     model.setScale(0.1)
     #self.disableMouse()
     base.setFrameRateMeter(True)
     self.n = 100
     self.data = gen(self.n)
     self.zvezde = self.render.attachNewNode("zvezde")
     model.reparentTo(self.zvezde)
     model.setTexture(self.loader.loadTexture("explosion1.png"))
     self.zvezde.setPosHpr(0, 70, 0, 0, 90, 0)
     self.zvezde.setInstanceCount(self.n)
     myShader = Shader.load(Shader.SLGLSL, "vertex.glsl", "fragment.glsl")
     self.zvezde.setShader(myShader)  #Shader.load('instance.cg'))
     self.render.setShaderAuto()
     self.offsets = PTA_LVecBase4f.emptyArray(self.n)
     self.accept("r", self.reset)
     self.zvezde.setShaderInput('shader_data', self.offsets)
     self.zvezde.setShaderInput('shader_data[0]', self.offsets)
     #self.taskMgr.setupTaskChain('threaded chain', numThreads = 0, frameBudget = -1,frameSync = 1)
     self.taskMgr.add(self.update,
                      "update")  #,taskChain = 'threaded chain')
Exemple #2
0
    def __init__(self, parent, star, **kwargs):
        super(StarView, self).__init__(parent, star, **kwargs)
        if not StarView.ready: StarView.setup(self.base.loader)
        self.seed = random.random()

        self.node = NodePath('star')

        plight = PointLight("starlight")
        self.light = self.node.attachNewNode(plight)
        self.light.setColor(self.obj.color)

        self.model = self.light.attachNewNode(SphereNode(subdivides=4))
        self.model.setShader(Shader.load("shader/star.cg"))
        self.cloudtime = 0.0
        #self.seed = hash("fish")
        self.param_set = ParamSet(self.seed)

        min_scale = Vec4(0.5, 0.5, 0.5, 0.5)
        max_scale = Vec4(1, 1, 1, 1)
        max_radius = StellarClass.highest_radius
        min_radius = StellarClass.lowest_radius
        radius_factor = log(self.obj.radius*(1/min_radius), 100) / log(max_radius*(1/min_radius), 100)
        self.param_set.vectors['scale'] = min_scale + (max_scale-min_scale)*radius_factor

        self.compute_seed_param()

        for stage, tex in StarView.texture_set:
            self.model.setTexture(stage, tex)

        self.speed = 0.00000001
        self.setup_shader_inputs()

        self.node.setScale(1/self.node.getBounds().getRadius())
        self.node.reparentTo(self.parent.node)
Exemple #3
0
    def setupGlowFilter(self):
        #create the shader that will determime what parts of the scene will glow
        glowShader=Shader.load(self.pandapath + "/data/glowShader.sha")
        
        # create the glow buffer. This buffer renders like a normal scene,
        # except that only the glowing materials should show up nonblack.
        glowBuffer=base.win.makeTextureBuffer("Glow scene", 512, 512)
        glowBuffer.setSort(-3)
        glowBuffer.setClearColor(Vec4(0,0,0,1))

        # We have to attach a camera to the glow buffer. The glow camera
        # must have the same frustum as the main camera. As long as the aspect
        # ratios match, the rest will take care of itself.
        self.glowCamera=base.makeCamera(glowBuffer, lens=base.cam.node().getLens())

        # Tell the glow camera to use the glow shader
        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setShader(glowShader)
        self.glowCamera.node().setInitialState(tempnode.getState())

        # set up the pipeline: from glow scene to blur x to blur y to main window.
        blurXBuffer=self.makeFilterBuffer(glowBuffer,  "Blur X", -2, self.pandapath+"/data/XBlurShader.sha")
        blurYBuffer=self.makeFilterBuffer(blurXBuffer, "Blur Y", -1, self.pandapath+"/data/YBlurShader.sha")
        self.finalcard = blurYBuffer.getTextureCard()
        self.finalcard.reparentTo(render2d)
        self.finalcard.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))
        
        render.setShaderInput('glow', Vec4(0,0,0,0),0)
        
        render.analyze()
Exemple #4
0
def make_filter_buffer (srcbuffer, name, sort, prog):
    blur_buffer = base.win.makeTextureBuffer (name, 512, 512)
    blur_buffer.setSort (sort)
    blur_buffer.setClearColor (Vec4 (1, 0, 0, 1))
    blur_camera = base.makeCamera2d (blur_buffer)
    blur_scene = NodePath ("filter_scene")
    blur_camera.node ().setScene (blur_scene)
    shader = Shader.load (prog)
    card = srcbuffer.getTextureCard ()
    card.reparentTo (blur_scene)
    card.setShader (shader)
    return blur_buffer
Exemple #5
0
 def makeFilterBuffer(self, srcbuffer, name, sort, prog):
     blurBuffer=base.win.makeTextureBuffer(name, 512, 512)
     blurBuffer.setSort(sort)
     blurBuffer.setClearColor(Vec4(1,0,0,1))
     blurCamera=base.makeCamera2d(blurBuffer)
     blurScene=NodePath("new Scene")
     blurCamera.node().setScene(blurScene)
     shader = Shader.load(prog)
     card = srcbuffer.getTextureCard()
     card.reparentTo(blurScene)
     card.setShader(shader)
     return blurBuffer
Exemple #6
0
	def render(self):
		LOG.debug("[SkyBox] Rendering")
		
		# If we are an orphan use render
		if self.parent is None: self.parent = render
		
		#LOG.debug("[SkyBox] model=%s"%self.modelFile)
		self.node  = loader.loadModel(self.modelFile)
		
		#print("tf1 = %s, tf2 = %s"%(self.texture1File,self.texture2File))
		
		if self.texture1File != '' and self.texture2File == '':
			#LOG.debug("[SkyBox] single texture = %s"%self.texture1File)
			t = loader.loadTexture(self.texture1File)
			self.node.setTexture(t)
			
		elif self.texture1File != '' and self.texture2File != '':
			#LOG.debug("[SkyBox] texture staging 1 = %s, 2 = %s"%(self.texture1File,self.texture2File))
			t1 = loader.loadTexture(self.texture1File)
			t1.setWrapU(Texture.WMClamp)
			t1.setWrapV(Texture.WMClamp)
			ts1 = TextureStage('Space')
			ts1.setSort(self.texture1Sort)
			
			t2 = loader.loadTexture(self.texture2File)
			t2.setWrapU(Texture.WMClamp)
			t2.setWrapV(Texture.WMClamp)
			ts2 = TextureStage('SpaceClouds')
			ts2.setSort(self.texture2Sort)
			self.node.setTexture(ts1, t1)
			self.node.setTexture(ts2, t2)
		if self.shaderFile:
			LOG.debug("[SkyBox] shader = %s"%self.shaderFile)
			#skyShader = Shader.load("./data/shaders/%s"%self.shaderFile)
			skyShader = Shader.load("%s"%self.shaderFile)
			self.node.setShader(skyShader)
		
		# Should this be scaled here or done to the model?
		# It doesn't look like scaling the objects looks any different.
		self.node.setScale(280)
		
		# make sure it's drawn first (this can be done with shaders?)
		self.node.setBin('background', 0)
		
		# dont set depth attribute when rendering the sky (this can be done with shaders?)
		self.node.setAttrib(DepthWriteAttrib.make(DepthWriteAttrib.MOff))
		
		# We don't want shadows on the skybox
		self.node.setLightOff()
		
		# Render
		self.node.reparentTo(self.parent)
		taskMgr.add(self.moveSkyTask, "Move the sky box with the cam")
Exemple #7
0
    def render(self):
        LOG.debug("[SkyBox] Rendering")

        # If we are an orphan use render
        if self.parent is None: self.parent = render

        #LOG.debug("[SkyBox] model=%s"%self.modelFile)
        self.node = loader.loadModel(self.modelFile)

        #print("tf1 = %s, tf2 = %s"%(self.texture1File,self.texture2File))

        if self.texture1File != '' and self.texture2File == '':
            #LOG.debug("[SkyBox] single texture = %s"%self.texture1File)
            t = loader.loadTexture(self.texture1File)
            self.node.setTexture(t)

        elif self.texture1File != '' and self.texture2File != '':
            #LOG.debug("[SkyBox] texture staging 1 = %s, 2 = %s"%(self.texture1File,self.texture2File))
            t1 = loader.loadTexture(self.texture1File)
            t1.setWrapU(Texture.WMClamp)
            t1.setWrapV(Texture.WMClamp)
            ts1 = TextureStage('Space')
            ts1.setSort(self.texture1Sort)

            t2 = loader.loadTexture(self.texture2File)
            t2.setWrapU(Texture.WMClamp)
            t2.setWrapV(Texture.WMClamp)
            ts2 = TextureStage('SpaceClouds')
            ts2.setSort(self.texture2Sort)
            self.node.setTexture(ts1, t1)
            self.node.setTexture(ts2, t2)
        if self.shaderFile:
            LOG.debug("[SkyBox] shader = %s" % self.shaderFile)
            #skyShader = Shader.load("./data/shaders/%s"%self.shaderFile)
            skyShader = Shader.load("%s" % self.shaderFile)
            self.node.setShader(skyShader)

        # Should this be scaled here or done to the model?
        # It doesn't look like scaling the objects looks any different.
        self.node.setScale(280)

        # make sure it's drawn first (this can be done with shaders?)
        self.node.setBin('background', 0)

        # dont set depth attribute when rendering the sky (this can be done with shaders?)
        self.node.setAttrib(DepthWriteAttrib.make(DepthWriteAttrib.MOff))

        # We don't want shadows on the skybox
        self.node.setLightOff()

        # Render
        self.node.reparentTo(self.parent)
        taskMgr.add(self.moveSkyTask, "Move the sky box with the cam")
Exemple #8
0
    def __init__(self, parent, planet, **kwargs):
        super(PlanetView, self).__init__(parent, planet, **kwargs)
        if not PlanetView.ready: PlanetView.setup(self.base.loader)
        self.node = NodePath(SphereNode(subdivides=4))
        self.node.setShader(Shader.load("shader/planet.cg"))
        self.cloudtime = 0.0
        self.seed = hash("fish")
        self.param_set = ParamSet(self.seed)

        self.compute_seed_param()
        for stage, tex in PlanetView.texture_sets['terrestrial_big']:
            self.node.setTexture(stage, tex)

        self.setup_shader_inputs()
        self.node.setScale(1 / self.node.getBounds().getRadius())
        self.node.reparentTo(self.parent.node)
Exemple #9
0
    def __init__(self, parent, planet, **kwargs):
        super(PlanetView, self).__init__(parent, planet, **kwargs)
        if not PlanetView.ready: PlanetView.setup(self.base.loader)
        self.node = NodePath(SphereNode(subdivides=4))
        self.node.setShader(Shader.load("shader/planet.cg"))
        self.cloudtime = 0.0
        self.seed = hash("fish")
        self.param_set = ParamSet(self.seed)

        self.compute_seed_param()
        for stage, tex in PlanetView.texture_sets['terrestrial_big']:
            self.node.setTexture(stage, tex)

        self.setup_shader_inputs()
        self.node.setScale(1/self.node.getBounds().getRadius())
        self.node.reparentTo(self.parent.node)
Exemple #10
0
    def make_glow (self, data_dir = './src/core/sha'):
        """
        TODO: data_dir = current module directory?
        """
    
        glow_shader = Shader.load (data_dir + "/glow_shader.sha")
        
        # create the glow buffer. This buffer renders like a normal
        # scene, except that only the glowing materials should show up
        # nonblack.
        glow_buffer = base.win.makeTextureBuffer ("glow_scene", 512, 512)
        glow_buffer.setSort (-3)
        glow_buffer.setClearColor (Vec4 (0, 0, 0, 1))

        # We have to attach a camera to the glow buffer. The glow
        # camera must have the same frustum as the main camera. As
        # long as the aspect ratios match, the rest will take care of
        # itself.
        glow_camera = base.makeCamera (glow_buffer,
                                       lens = base.cam.node ().getLens ())

        # Tell the glow camera to use the glow shader
        temp_node = NodePath (PandaNode("temp_node"))
        temp_node.setShader (glow_shader)
        glow_camera.node ().setInitialState (temp_node.getState ())

        # set up the pipeline: from glow scene to blur x to blur y to
        # main window.
        blur_xbuffer = make_filter_buffer (glow_buffer, "blur_x", -2,
                                           data_dir + "/x_blur_shader.sha")
        blur_ybuffer = make_filter_buffer (blur_xbuffer, "blur_y", -1,
                                           data_dir + "/y_blur_shader.sha")

        final_card = blur_ybuffer.getTextureCard ()
        final_card.setAttrib (ColorBlendAttrib.make (ColorBlendAttrib.MAdd))

        self.glow_camera  = glow_camera
        self.glow_buffer  = glow_buffer
        self.blur_xbuffer = blur_xbuffer
        self.blur_ybuffer = blur_ybuffer
        self.final_card   = final_card
Exemple #11
0
    def make_glow(self, data_dir='./src/core/sha'):
        """
        TODO: data_dir = current module directory?
        """

        glow_shader = Shader.load(data_dir + "/glow_shader.sha")

        # create the glow buffer. This buffer renders like a normal
        # scene, except that only the glowing materials should show up
        # nonblack.
        glow_buffer = base.win.makeTextureBuffer("glow_scene", 512, 512)
        glow_buffer.setSort(-3)
        glow_buffer.setClearColor(Vec4(0, 0, 0, 1))

        # We have to attach a camera to the glow buffer. The glow
        # camera must have the same frustum as the main camera. As
        # long as the aspect ratios match, the rest will take care of
        # itself.
        glow_camera = base.makeCamera(glow_buffer,
                                      lens=base.cam.node().getLens())

        # Tell the glow camera to use the glow shader
        temp_node = NodePath(PandaNode("temp_node"))
        temp_node.setShader(glow_shader)
        glow_camera.node().setInitialState(temp_node.getState())

        # set up the pipeline: from glow scene to blur x to blur y to
        # main window.
        blur_xbuffer = make_filter_buffer(glow_buffer, "blur_x", -2,
                                          data_dir + "/x_blur_shader.sha")
        blur_ybuffer = make_filter_buffer(blur_xbuffer, "blur_y", -1,
                                          data_dir + "/y_blur_shader.sha")

        final_card = blur_ybuffer.getTextureCard()
        final_card.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))

        self.glow_camera = glow_camera
        self.glow_buffer = glow_buffer
        self.blur_xbuffer = blur_xbuffer
        self.blur_ybuffer = blur_ybuffer
        self.final_card = final_card
Exemple #12
0
    def __init__(self, parent, star, **kwargs):
        super(StarView, self).__init__(parent, star, **kwargs)
        if not StarView.ready: StarView.setup(self.base.loader)
        self.seed = random.random()

        self.node = NodePath('star')

        plight = PointLight("starlight")
        self.light = self.node.attachNewNode(plight)
        self.light.setColor(self.obj.color)

        self.model = self.light.attachNewNode(SphereNode(subdivides=4))
        self.model.setShader(Shader.load("shader/star.cg"))
        self.cloudtime = 0.0
        #self.seed = hash("fish")
        self.param_set = ParamSet(self.seed)

        min_scale = Vec4(0.5, 0.5, 0.5, 0.5)
        max_scale = Vec4(1, 1, 1, 1)
        max_radius = StellarClass.highest_radius
        min_radius = StellarClass.lowest_radius
        radius_factor = log(self.obj.radius * (1 / min_radius), 100) / log(
            max_radius * (1 / min_radius), 100)
        self.param_set.vectors['scale'] = min_scale + (
            max_scale - min_scale) * radius_factor

        self.compute_seed_param()

        for stage, tex in StarView.texture_set:
            self.model.setTexture(stage, tex)

        self.speed = 0.00000001
        self.setup_shader_inputs()

        self.node.setScale(1 / self.node.getBounds().getRadius())
        self.node.reparentTo(self.parent.node)
Exemple #13
0
    def __init__(self, manager, xml):
        self.updateTask = None

        self.sun = base.cam.attachNewNode('sun')
        loader.loadModel(
            manager.get('paths').getConfig().find('misc').get('path') +
            '/sphere').reparentTo(self.sun)
        self.sun.setScale(0.1)
        self.sun.setTwoSided(True)
        self.sun.setColorScale(10.0, 10.0, 10.0, 1.0, 10001)
        self.sun.setLightOff(1)
        self.sun.setShaderOff(1)
        self.sun.setFogOff(1)
        self.sun.setCompass()
        self.sun.setBin('background', 10)
        self.sun.setDepthWrite(False)
        self.sun.setDepthTest(False)
        # Workaround an annoyance in Panda. No idea why it's needed.
        self.sun.node().setBounds(OmniBoundingVolume())
        isa = xml.find('isa')
        inst = xml.find('instance')
        if isa != None or inst != None:
            if inst != None:
                orig = Vec3(float(inst.get('x',
                                           '0')), float(inst.get('y', '0')),
                            float(inst.get('z', '0')))
            else:
                level = manager.get(isa.get('source'))
                orig = Vec3(level.getByIsA(isa.get('name'))[0].getPos(render))
            orig.normalize()
            self.sun.setPos(orig)

        godrays = xml.find('godrays')
        if godrays != None:
            self.vlbuffer = base.win.makeTextureBuffer('volumetric-lighting',
                                                       base.win.getXSize() / 2,
                                                       base.win.getYSize() / 2)
            self.vlbuffer.setClearColor(Vec4(0, 0, 0, 1))
            cam = base.makeCamera(self.vlbuffer)
            cam.node().setLens(base.camLens)
            cam.reparentTo(base.cam)
            initstatenode = NodePath('InitialState')
            initstatenode.setColorScale(0, 0, 0, 1, 10000)
            initstatenode.setShaderOff(10000)
            initstatenode.setLightOff(10000)
            initstatenode.setMaterialOff(10000)
            initstatenode.setTransparency(TransparencyAttrib.MBinary, 10000)
            cam.node().setCameraMask(BitMask32.bit(2))
            cam.node().setInitialState(initstatenode.getState())
            self.vltexture = self.vlbuffer.getTexture()
            self.vltexture.setWrapU(Texture.WMClamp)
            self.vltexture.setWrapV(Texture.WMClamp)
            card = CardMaker('VolumetricLightingCard')
            card.setFrameFullscreenQuad()
            self.finalQuad = render2d.attachNewNode(card.generate())
            self.finalQuad.setAttrib(
                ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                      ColorBlendAttrib.OIncomingColor,
                                      ColorBlendAttrib.OFbufferColor))

            self.finalQuad.setShader(
                Shader.load(
                    posixpath.join(
                        manager.get('paths').getConfig().find('shaders').get(
                            'path'), 'filter-vlight.cg')))
            self.finalQuad.setShaderInput('src', self.vltexture)
            self.finalQuad.setShaderInput(
                'vlparams', 32, 0.9 / 32.0, 0.97, 0.5
            )  # Note - first 32 is now hardcoded into shader for cards that don't support variable sized loops.
            self.finalQuad.setShaderInput('casterpos', 0.5, 0.5, 0, 0)
            # Last parameter to vlcolor is the exposure
            vlcolor = Vec4(float(godrays.get('r', '1')),
                           float(godrays.get('g', '1')),
                           float(godrays.get('b', '1')), 0.04)

            self.finalQuad.setShaderInput('vlcolor', vlcolor)
        else:
            self.finalQuad = None
    def __init__(self, filters):
        self.filters = filters
        self.updateTask = None
        self.finalQuad = None

        self.sun = base.cam.attachNewNode('sun')
        loader.loadModel("models/sphere").reparentTo(self.sun)
        self.sun.setScale(0.08)
        self.sun.setTwoSided(True)
        self.sun.setColorScale(1.0, 1.0, 1.0, 1.0, 10001)
        self.sun.setLightOff(1)
        self.sun.setShaderOff(1)
        self.sun.setFogOff(1)
        self.sun.setCompass()
        self.sun.setBin('background', 2)
        self.sun.setDepthWrite(False)
        self.sun.setDepthTest(False)
        # Workaround an annoyance in Panda. No idea why it's needed.
        self.sun.node().setBounds(OmniBoundingVolume())     

        direct = Vec4(2.0, 1.9, 1.8, 1) #bright for hdr
        #direct = Vec4(0.7, 0.65, 0.6, 1)
        self.dlight = DirectionalLight('dlight')
        self.dlight.setColor(direct)
        dlnp = self.sun.attachNewNode(self.dlight)
        render.setLight(dlnp)
        render.setShaderInput('dlight0', dlnp)

        self.setTime(700.0)

        pandaVolumetricLighting = False


        if pandaVolumetricLighting:
            self.filters.setVolumetricLighting( dlnp )
        else:
            self.vlbuffer = base.win.makeTextureBuffer('volumetric-lighting', base.win.getXSize() / 2, base.win.getYSize() / 2)
            self.vlbuffer.setClearColor(Vec4(0, 0, 0, 1))
            cam = base.makeCamera(self.vlbuffer)
            cam.node().setLens(base.camLens)
            cam.reparentTo(base.cam)
            initstatenode = NodePath('InitialState')
            initstatenode.setColorScale(0, 0, 0, 1, 10000)
            initstatenode.setShaderOff(10000)
            initstatenode.setFogOff(1)
            initstatenode.setLightOff(10000)
            initstatenode.setMaterialOff(10000)
            initstatenode.setTransparency(TransparencyAttrib.MBinary, 10000)
            cam.node().setCameraMask(BitMask32.bit(2))
            cam.node().setInitialState(initstatenode.getState())
            self.vltexture = self.vlbuffer.getTexture()
            self.vltexture.setWrapU(Texture.WMClamp)
            self.vltexture.setWrapV(Texture.WMClamp)
            card = CardMaker('VolumetricLightingCard')
            card.setFrameFullscreenQuad()
            self.finalQuad = render2d.attachNewNode(card.generate())
            self.finalQuad.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingColor, ColorBlendAttrib.OFbufferColor))
            self.finalQuad.setShader(Shader.load("shaders/filter-vlight.cg"))
            self.finalQuad.setShaderInput('src', self.vltexture)
            self.finalQuad.setShaderInput('vlparams', 32, 0.95 / 32.0, 0.985, 0.5) # Note - first 32 is now hardcoded into shader for cards that don't support variable sized loops.
            self.finalQuad.setShaderInput('casterpos', 0.5, 0.5, 0, 0)
            # Last parameter to vlcolor is the exposure
            vlcolor = Vec4(1, 0.99, 0.80, 0.03)
            self.finalQuad.setShaderInput('vlcolor', vlcolor)

        self.start()
Exemple #15
0
    def _loadInternal(self,
                      resType,
                      filename,
                      locationName=None,
                      preloading=False):
        '''
        Manages the actual loading of a resource given the resource filename and the resource location
        that contains it.

        @param resType: A constant that identifies the type of the resource.
        @param filename: The filename of the resource.
        @param locationName: The name of the resource location containing the resource. This is optional.
        @return: A pano.resources.Resource instance if preloading is True, or the actual resource instance
        if preloading is False or finally None if the resource couldn't be found.
        '''

        self.requests += 1

        if locationName is not None:
            location = self.locationsByName.get(locationName)
        else:
            location = self.locateResource(resType, filename)
        if location is None:
            self.log.error('Failed to locate resource %s' % filename)
            return None

        # get the full path to query the cache, sticky and preload stores
        fullPath = location.getResourceFullPath(filename)
        if fullPath is None:
            self.log.error('Failed to get full path to resource %s' % filename)
            return None

        # resource locations can be sticky
        if location.sticky:
            resource = self._getStickyResource(fullPath, resType)
            if resource is not None:
                if self.log.isEnabledFor(logging.DEBUG):
                    self.log.debug('Returning sticky resource %s' % fullPath)

                self.stickyLoads += 1
                if not preloading:
                    resource.requested = True
                return resource.data if not preloading else resource

        # if the location has a preload flag, then search first in the preload store
        if location.preload:
            resource = self._fetchPreloaded(fullPath, location.name)
            if resource is not None:
                self.preloadHits += 1
                if not preloading:
                    resource.requested = True
                return resource.data if not preloading else resource
            else:
                self.preloadMisses += 1

        # then search in our cache
#        resource = self._cacheLookup(fullPath, location.name)
#        if resource is not None:
#            if self.log.isEnabledFor(logging.DEBUG):
#                self.log.debug('Returning cached instance of resource %s' % fullPath)
#            if not preloading:
#                resource.requested = True
#            return resource.data if not preloading else resource

# finally load it from the resource location
        if ResourcesTypes.isParsedResource(resType):
            # Convention: construct resource name from the basename of the filename and by dropping the extension.
            resName = os.path.basename(filename)
            extIndex = resName.rfind('.')
            if extIndex >= 0:
                resName = resName[:extIndex]

            resData = self._loadParsedResource(resType, resName, fullPath,
                                               location)

        else:
            if ResourcesTypes.isPandaResource(resType):
                # for Panda resources we use the BaseLoader
                resName = filename
                try:
                    if resType == PanoConstants.RES_TYPE_MODELS:
                        resData = loader.loadModel(fullPath)

                    elif resType == PanoConstants.RES_TYPE_TEXTURES or resType == PanoConstants.RES_TYPE_VIDEOS:
                        resData = loader.loadTexture(fullPath)

                    elif resType == PanoConstants.RES_TYPE_IMAGES:
                        img = PNMImage()
                        img.read(fullPath)
                        resData = img

                    elif resType == PanoConstants.RES_TYPE_MUSIC:
                        resData = loader.loadMusic(fullPath)

                    elif resType == PanoConstants.RES_TYPE_SFX:
                        resData = loader.loadSfx(fullPath)

                    elif resType == PanoConstants.RES_TYPE_SHADERS:
                        resData = Shader.load(fullPath)

                except Exception:
                    self.log.exception(
                        'Panda loader failed to load resource %s' % fullPath)
                    return None

            elif ResourcesTypes.isStreamResource(resType):
                # we consider character based and binary based streams
                # by handling stream resources in a special way we can perhaps provide more efficient
                # handling of streams, i.e. memory mapped files, compressed streams, decryption, etc.
                resName = filename
                if resType == PanoConstants.RES_TYPE_SCRIPTS or resType == PanoConstants.RES_TYPE_TEXTS:
                    resData = self._loadCharacterStream(fullPath, location)
                else:
                    resData = self._loadBinaryStream(fullPath, location)

            elif ResourcesTypes.isOpaqueResource(resType):
                # opaque resources perform their own loading, we only load the file's contents without caring
                # about how it looks and pass it to the read() method.
                resName = os.path.basename(filename)
                resData = ResourcesTypes.constructOpaqueResource(
                    resType, resName, filename)
                opaque = self._loadBinaryStream(fullPath, location)
                fp = StringIO.StringIO(opaque)
                resData.read(fp)

            if resData is None:
                self.log.error('Failed to load resource %s' % fullPath)
                return None

        resource = Resource(resName, resData, resType, fullPath, location.name)
        resource.sticky = location.sticky
        resource.preload = location.preload
        if not preloading:
            resource.requested = True

        # consider caching the resource
        if not resource.sticky and not resource.preload:
            self._cacheResource(fullPath, resource, location.name)

        elif resource.sticky:
            self._addStickyResource(fullPath, resource, location.name)

        # when we are preloading, return the Resource instance instead
        return resource.data if not preloading else resource
Exemple #16
0
    def __init__(self, manager, xml):
        self.updateTask = None

        self.sun = base.cam.attachNewNode("sun")
        loader.loadModel(manager.get("paths").getConfig().find("misc").get("path") + "/sphere").reparentTo(self.sun)
        self.sun.setScale(0.1)
        self.sun.setTwoSided(True)
        self.sun.setColorScale(10.0, 10.0, 10.0, 1.0, 10001)
        self.sun.setLightOff(1)
        self.sun.setShaderOff(1)
        self.sun.setFogOff(1)
        self.sun.setCompass()
        self.sun.setBin("background", 10)
        self.sun.setDepthWrite(False)
        self.sun.setDepthTest(False)
        # Workaround an annoyance in Panda. No idea why it's needed.
        self.sun.node().setBounds(OmniBoundingVolume())
        isa = xml.find("isa")
        inst = xml.find("instance")
        if isa != None or inst != None:
            if inst != None:
                orig = Vec3(float(inst.get("x", "0")), float(inst.get("y", "0")), float(inst.get("z", "0")))
            else:
                level = manager.get(isa.get("source"))
                orig = Vec3(level.getByIsA(isa.get("name"))[0].getPos(render))
            orig.normalize()
            self.sun.setPos(orig)

        godrays = xml.find("godrays")
        if godrays != None:
            self.vlbuffer = base.win.makeTextureBuffer(
                "volumetric-lighting", base.win.getXSize() / 2, base.win.getYSize() / 2
            )
            self.vlbuffer.setClearColor(Vec4(0, 0, 0, 1))
            cam = base.makeCamera(self.vlbuffer)
            cam.node().setLens(base.camLens)
            cam.reparentTo(base.cam)
            initstatenode = NodePath("InitialState")
            initstatenode.setColorScale(0, 0, 0, 1, 10000)
            initstatenode.setShaderOff(10000)
            initstatenode.setLightOff(10000)
            initstatenode.setMaterialOff(10000)
            initstatenode.setTransparency(TransparencyAttrib.MBinary, 10000)
            cam.node().setCameraMask(BitMask32.bit(2))
            cam.node().setInitialState(initstatenode.getState())
            self.vltexture = self.vlbuffer.getTexture()
            self.vltexture.setWrapU(Texture.WMClamp)
            self.vltexture.setWrapV(Texture.WMClamp)
            card = CardMaker("VolumetricLightingCard")
            card.setFrameFullscreenQuad()
            self.finalQuad = render2d.attachNewNode(card.generate())
            self.finalQuad.setAttrib(
                ColorBlendAttrib.make(
                    ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingColor, ColorBlendAttrib.OFbufferColor
                )
            )
            self.finalQuad.setShader(
                Shader.load(
                    posixpath.join(manager.get("paths").getConfig().find("shaders").get("path"), "filter-vlight.cg")
                )
            )
            self.finalQuad.setShaderInput("src", self.vltexture)
            self.finalQuad.setShaderInput(
                "vlparams", 32, 0.9 / 32.0, 0.97, 0.5
            )  # Note - first 32 is now hardcoded into shader for cards that don't support variable sized loops.
            self.finalQuad.setShaderInput("casterpos", 0.5, 0.5, 0, 0)
            # Last parameter to vlcolor is the exposure
            vlcolor = Vec4(
                float(godrays.get("r", "1")), float(godrays.get("g", "1")), float(godrays.get("b", "1")), 0.04
            )
            self.finalQuad.setShaderInput("vlcolor", vlcolor)
        else:
            self.finalQuad = None
Exemple #17
0
 def loadShader(self, name):
     fn = os.path.join(os.path.abspath(os.path.dirname(__file__)), name)
     fn = Filename.fromOsSpecific(fn)
     fn.makeTrueCase()
     return Shader.load(fn)
Exemple #18
0
 def loadShader(self, name):
     fn = os.path.join(os.path.abspath(os.path.dirname(__file__)), name)
     fn = Filename.fromOsSpecific(fn)
     fn.makeTrueCase()
     return Shader.load(fn)
Exemple #19
0
    def __init__(self, _base):
        
        self._base = _base
        
        self._base.cam.node().setActive(0)
        
        # window properties
        self.winprops = WindowProperties.size(base.win.getXSize(),base.win.getYSize())
        self.props = FrameBufferProperties()
        self.props.setDepthBits(1)
        self.props.setColorBits(1) 
        self.props.setAlphaBits(1) 
        
        # buffers creation
        self.geom_buffer = self.make_FBO("geom buffer",3)
        self.light_buffer = self.make_FBO("light buffer",0)
        self.transparency_buffer = self.make_FBO("transparency buffer",0)
        
        # cameras creation
        self.geom_cam = self._base.makeCamera(self.geom_buffer)
        self.light_cam = self._base.makeCamera(self.light_buffer)
        self.transparency_cam = self._base.makeCamera(self.transparency_buffer)
        
        # cameras setup
        self.geom_cam.node().getDisplayRegion(0).setClearColorActive(1) 
        self.geom_cam.node().getDisplayRegion(0).setClearColor(Vec4(1,0,0,1)) 
        self.geom_cam.node().getDisplayRegion(0).setClearDepthActive(1) 
        
        self.light_cam.node().getDisplayRegion(0).setClearColorActive(1) 
        self.geom_cam.node().getDisplayRegion(0).setClearColor(Vec4(0,1,0,1)) 
        self.light_cam.node().getDisplayRegion(0).setClearDepthActive(1) 
        
        self.transparency_cam.node().getDisplayRegion(0).setClearColorActive(1) 
        self.transparency_cam.node().getDisplayRegion(0).setClearDepthActive(1) 
        
        self.geom_cam.node().getLens().setNear(0.1)
        self.light_cam.node().getLens().setNear(0.1)
        self.transparency_cam.node().getLens().setNear(0.1)
        
        self.geom_cam.node().getLens().setFov(90)
        self.light_cam.node().getLens().setFov(90)
        self._base.cam.node().getLens().setFov(90)
        self.transparency_cam.node().getLens().setFov(90)
                
        # cameras masks
        self.geom_mask = BitMask32(1)
        self.light_mask = BitMask32(2)    
        self.transparency_mask = BitMask32(4) 
        
        self.light_cam.node().setCameraMask(self.light_mask)
        self.geom_cam.node().setCameraMask(self.geom_mask)
        self.transparency_cam.node().setCameraMask(self.transparency_mask)
        
        RENDER_NODES['LIGHTS'].hide(self.geom_mask)
        RENDER_NODES['GEOMS'].hide(self.light_mask)
        RENDER_NODES['TRANSPS'].hide(self.geom_mask)
        
        # link cameras
        self.geom_cam.node().setScene(RENDER_NODES['GEOMS'])
        self.light_cam.node().setScene(RENDER_NODES['LIGHTS'])
        self.transparency_cam.node().setScene(RENDER_NODES['TRANSPS'])
        
        # buffers rendering order
        self.light_buffer.setSort(0)
        self.geom_buffer.setSort(-50)
        self.transparency_buffer.setSort(50)
        self._base.win.setSort(-100)   

        # shadows cube creation
        self.shadow_cube = RENDER_NODES['GEOMS'].attachNewNode("cubemap")
        self.shadow_cube.setPos(0, 0, 0)
        buffer_cube_shadow = self._base.win.makeCubeMap("cube 1", 512, self.shadow_cube, camera_mask = self.geom_mask, to_ram = False, fbp = self.props)
        self.shadow_cube_texture = buffer_cube_shadow.getTexture()

        cameras = []
        for camera in self.shadow_cube.getChildren():
            cameras.append(camera)
            camera.node().getLens().setFov(90)
            camera.node().getLens().setNearFar(0.1 ,10.0)
            camera.node().setCameraMask(self.geom_mask)
            cameraInit = NodePath(PandaNode("cube camera initiator"))
            cameraInit.setShader(Shader.load('shaders/point_lights_cube.sha'))
            cameraInit.setShaderInput("light2", self.shadow_cube)
            cameraInit.setShaderInput("lightCamera", camera)
            cameraInit.setShaderInput("lensFar", Vec4(camera.node().getLens().getFar()))
            cameraInit.setShaderInput("transparency", Vec4(1))
            camera.node().setInitialState(cameraInit.getState())
            
        # reflections cube creation                    
        self.reflection_cube = RENDER_NODES['GEOMS'].attachNewNode("cubemap pivot")
        self.buffer_reflection_cube = self._base.win.makeCubeMap("cube 2", 512, self.reflection_cube, camera_mask = self.geom_mask, to_ram = False, fbp = self.props)
        self.reflection_cube_texture = self.buffer_reflection_cube.getTexture()

        for camera in self.reflection_cube.getChildren():
            camera.node().getLens().setNearFar(0.1 ,500.0)

        # shader rendering normal maps
        normal_shader = ShaderAttrib.make()
        normal_shader = normal_shader.setShader(Shader.load(CG_NORMALMAP))

        # shader rendering light
        light_shader = ShaderAttrib.make()
        light_shader = light_shader.setShader(Shader.load(CG_LIGHT))
        
        # link states with cameras
        self.geom_cam.node().setTagStateKey(SHADER_TAGS['g-buffer'])
        self.geom_cam.node().setTagState("True", RenderState.make(normal_shader))
        self.light_cam.node().setTagStateKey(SHADER_TAGS['compute light'])
        self.light_cam.node().setTagState("True", RenderState.make(light_shader))
        
        # render textures creation
        self.albedo_map = Texture()
        self.normal_map = Texture()
        self.depth_map = Texture()  
        self.specular_map = Texture()
        self.misc_map = Texture()
        self.light_map = Texture()
        self.transparency_map = Texture() 
        self.transparency_depth_map = Texture()
             
        # render textures   
        self.transparency_buffer.addRenderTexture(self.transparency_map, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor)
        self.transparency_buffer.addRenderTexture(self.transparency_depth_map, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth)
        
        self.geom_buffer.addRenderTexture(self.normal_map, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor)
        self.geom_buffer.addRenderTexture(self.depth_map, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth)
        self.geom_buffer.addRenderTexture(self.albedo_map, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0)      
        self.geom_buffer.addRenderTexture(self.specular_map, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba1)
        self.geom_buffer.addRenderTexture(self.misc_map, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba2)
        
        self.light_buffer.addRenderTexture(self.light_map, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor)  
 
        taskMgr.add(self.update,'update reflections cubemap')