Ejemplo n.º 1
0
    def create(self):
        # Create the voxel grid used to store the voxels
        self._voxel_grid = Image.create_3d(
            "Voxels", self._voxel_res, self._voxel_res, self._voxel_res, Texture.T_float, Texture.F_r11_g11_b10
        )
        self._voxel_grid.set_clear_color(Vec4(0))

        # Create the camera for voxelization
        self._voxel_cam = Camera("VoxelizeCam")
        self._voxel_cam.set_camera_mask(self._pipeline.tag_mgr.get_voxelize_mask())
        self._voxel_cam_lens = OrthographicLens()
        self._voxel_cam_lens.set_film_size(-self._voxel_ws, self._voxel_ws)
        self._voxel_cam_lens.set_near_far(0.0, 2.0 * self._voxel_ws)
        self._voxel_cam.set_lens(self._voxel_cam_lens)
        self._voxel_cam_np = Globals.base.render.attach_new_node(self._voxel_cam)
        self._pipeline.tag_mgr.register_voxelize_camera(self._voxel_cam)

        # Create the voxelization target
        self._voxel_target = self._create_target("VoxelizeScene")
        self._voxel_target.set_source(source_cam=self._voxel_cam_np, source_win=Globals.base.win)
        self._voxel_target.set_size(self._voxel_res, self._voxel_res)
        self._voxel_target.set_create_overlay_quad(False)
        self._voxel_target.prepare_scene_render()

        # Create the initial state used for rendering voxels
        initial_state = NodePath("VXInitialState")
        initial_state.set_attrib(CullFaceAttrib.make(CullFaceAttrib.M_cull_none), 100000)
        initial_state.set_attrib(DepthTestAttrib.make(DepthTestAttrib.M_none), 100000)
        initial_state.set_attrib(ColorWriteAttrib.make(ColorWriteAttrib.C_off), 100000)
        self._voxel_cam.set_initial_state(initial_state.get_state())

        Globals.base.render.set_shader_input("voxelGridPosition", self._pta_grid_pos)
        Globals.base.render.set_shader_input("voxelGridRes", self._pta_grid_res)
        Globals.base.render.set_shader_input("voxelGridSize", self._pta_grid_size)
        Globals.base.render.set_shader_input("VoxelGridDest", self._voxel_grid.texture)
Ejemplo n.º 2
0
def recurseScene(curnode, scene_members, data_cache, M, texture_cache, col_inst=None):
    M = numpy.dot(M, curnode.matrix)
    for node in curnode.children:
        if isinstance(node, collada.scene.Node):
            recurseScene(node, scene_members, data_cache, M, texture_cache, col_inst=col_inst)
        elif isinstance(node, collada.scene.GeometryNode) or isinstance(node, collada.scene.ControllerNode):
            if isinstance(node, collada.scene.GeometryNode):
                geom = node.geometry
            else:
                geom = node.controller.geometry
            
            materialnodesbysymbol = {}
            for mat in node.materials:
                materialnodesbysymbol[mat.symbol] = mat

            for prim in geom.primitives:
                if len(prim) > 0:
                    mat = materialnodesbysymbol.get(prim.material)
                    matstate = None
                    if mat is not None:
                        matstate = data_cache['material2state'].get(mat.target)
                        if matstate is None:
                            matstate = getStateFromMaterial(mat.target, texture_cache, col_inst)
                            if geom.double_sided:
                                matstate = matstate.addAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullNone))
                            data_cache['material2state'][mat.target] = matstate
                    
                    mat4 = Mat4(*M.T.flatten().tolist())
                    
                    primgeom = data_cache['prim2geom'].get(prim)
                    if primgeom is None:
                        primgeom = getGeomFromPrim(prim, matstate)
                        data_cache['prim2geom'][prim] = primgeom
                    
                    scene_members.append((primgeom, matstate, mat4))
Ejemplo n.º 3
0
    def __build_Model(self, planet, model_type, rec):
        model_np = NodePath("model_{}".format(rec))
        
        # Basic terrain model.
        ter_model, pts = self.__get_Sphere_Model(model_type, rec, planet.radius, "terrain")
        ter_model.NP.reparentTo(model_np)

        # Map planet topography.
        if "height_map" in planet.__dict__ and model_type in ("mid", "high"):
            self.__map_Topography(planet, ter_model, pts)
        
        # Map planet colours for low type models only.
        if model_type == "low" and "colour_map" in planet.__dict__:
            self.__map_Colours(planet, ter_model, rec, pts)
        
        # Atmosphere.
        if "atmos_ceiling" in planet.__dict__:
            a_radius = planet.radius + planet.atmos_ceiling
            am_type = model_type if model_type != "high" else "mid"
            atmos_model, a_pts = self.__get_Sphere_Model(am_type, min(rec,7), a_radius, "atmos")
            atmos_model.NP.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
            atmos_model.NP.setAttrib(TransparencyAttrib.make(TransparencyAttrib.MAlpha))
            atmos_model.NP.reparentTo(model_np)
            
        model_np.attachNewNode("planet_label")
        return model_np
Ejemplo n.º 4
0
	def __init__(self, base, scene, name, model, pos=Vec3(0,0,0), scale=1.0):
		self.root = scene.attachNewNode(name)
		
		self.model = base.loader.loadModel(model)
		self.model.reparentTo(self.root)

		self.model.setDepthOffset(1)
		self.model.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullClockwise))
		
		self.root.setPos(pos)
		self.root.setScale(scale)
		
		self.lights = []
		self.doors  = []
		self.keys   = []
		
		self.setupDoors(base, scene)
		self.setupKeys(base, scene)
		self.setupLightSources(base, scene)
		self.setupEnemies(base, scene)
		self.setupGoal(base, scene)
		self.setupTrees(base, scene)
		
		for np in self.model.findAllMatches('**/=Hide'):
			np.hide()
Ejemplo n.º 5
0
 def registerTagState(self, name, state):
     """ Registers a new tag state """
     state.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullNone))
     state.setDepthWrite(False)
     state.setDepthTest(False)
     state.setAttrib(DepthTestAttrib.make(DepthTestAttrib.MNone))
     state.setShaderInput("voxelizeCam", self.voxelizeCameraNode)
     self.voxelizeCamera.setTagState(name, state.getState())
Ejemplo n.º 6
0
    def onSceneLoaded(self, scene):
        """ Callback which gets called after the scene got loaded """

        self.debug("Successfully loaded scene")

        self.loadingScreen.setStatus("Loading skybox")

        self.scene = scene
        self.scene.prepareScene(self.win.getGsg())

        # Load surround scene
        if self.sceneSourceSurround is not None:
            self.debug("Loading Surround-Scene '" + self.sceneSourceSurround + "'")
            self.sceneSurround = self.loader.loadModel(self.sceneSourceSurround)
            self.sceneSurround.reparentTo(self.scene)

        seed(1)

        # Performance testing
        if True:
            highPolyObj = self.scene.find("**/HighPolyObj")

            if highPolyObj is not None and not highPolyObj.isEmpty():
                highPolyObj.detachNode()
                self.loadingScreen.setStatus("Preparing Performance Test")

                for x in xrange(-10, 10):
                    for y in xrange(-10, 10):
                        copiedObj = copy.deepcopy(highPolyObj)
                        # copiedObj.setColorScale(random(), random(), random(), 1)
                        if random() < 0.2:
                            copiedObj.setColorScale(0.4, 1.2, 2.0, 1.0)

                        copiedObj.reparentTo(self.scene)
                        copiedObj.setPos(x*1.5 + random(), y*1.5 + random(), random()*5.0 + 0.4)

        # Find transparent objects and mark them as transparent
        self.transpObjRoot = render.attachNewNode("transparentObjects")
        matches = self.scene.findAllMatches("**/T__*")
        if matches:
            for match in matches:
                # match.reparentTo(self.transpObjRoot)
                self.transparentObjects.append(match)
                self.renderPipeline.prepareTransparentObject(match)
                # match.listTags()
                match.setAttrib(CullFaceAttrib.make(CullFaceAttrib.M_none))
                # match.setColorScale(1,0,1, 1)
                # match.hide(self.renderPipeline.getShadowPassBitmask())
        # Wheter to use a ground plane
        self.usePlane = False
        self.sceneWireframe = False

        # Flatten scene?
        self.loadingScreen.setStatus("Optimizing Scene")

        # self.scene.clearModelNodes()
        loader.asyncFlattenStrong(self.scene, inPlace=False, callback=self.onScenePrepared)
Ejemplo n.º 7
0
    def build(self, wld_container, f, start_index, n_polys, tex_idx,debug=False):

        
        # f.dump()
        self.sprite_list_index = f.fragment1-1        # the fragment1 ref is used as sprite list index
        sprite = wld_container.getSprite(tex_idx, self.sprite_list_index)
            
        polyList = f.polyList
        poly_idx = start_index
        for poly in range(0, n_polys):
            p = polyList[poly_idx]
            poly_idx += 1
            self.primitives.addVertices(p[0], p[1], p[2])

        self.node = GeomNode(self.name)
        self.node.addGeom(self.geom)
        
        # make a node path for our GEOM, these will be attached under our parent mesh's root
        self.nodePath = NodePath(self.node)
            
        # self.nodePath.setRenderModeWireframe()
        # self.nodePath.setRenderModeFilled()
        # self.nodePath.showBounds()
        
        self.nodePath.setPos(f.centerX, f.centerY,f.centerZ)    # translate to correct position
        self.nodePath.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
        # self.nodePath.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullClockwise))

        # Texture setup
        if sprite != None:
            # sprite.dump()
            if sprite.numtex > 0:   
                t = sprite.textures[0]
                self.nodePath.setTexture(t)
                if debug:
                    print("    polygroup build had texture count: " + str(sprite.numtex) + " AnimDelay: " + str(sprite.anim_delay))
                patchInvertDDSV(self.nodePath,t,debug)
                if sprite.anim_delay > 0:
                    geom_num = self.node.getNumGeoms()-1
                    if debug:
                        print("Adding geom render state for " + self.name)
                    from panda3d.core import ColorBlendAttrib
                    
                    # seems animated "masked" textrue need this in order to function
                    # dont want to have it on the main zone geoms though cause it breaks
                    # semi trasparent surfaces (water etc). Probably should move away from making those
                    # transparent through color blending and simply patch up their alpha channels as needed?
                    if sprite.masked == 1:
                        self.node.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd,ColorBlendAttrib.OAlphaScale,ColorBlendAttrib.OOne))
                    
                    sprite.addAnimGeomRenderState( (self.node,geom_num,self.node.getGeomState(geom_num),self.name) )
        else:
            print 'Error: texture (idx=%i) not found. PolyGroup will be rendered untextured' % (tex_idx)

        return 1
Ejemplo n.º 8
0
    def mirrorFlip(self, obj):
        tempObj = copy.copy(obj)
        # if tempObj is not None: #if none, throws up errors
        try:
            sc = tempObj.getScale()
            tempObj.setScale(-1 * sc[0], 1 * sc[1], 1 * sc[2])#change the scale of x axis to -1 of the prev scale
            tempObj.setAttrib(CullFaceAttrib.makeReverse()) #reverse backface culling to make sure things are visible
        except AttributeError:
            pass        # if tempObj is not None: #if none, throws up errors

        return tempObj
Ejemplo n.º 9
0
 def loadPlaceables(self, wld_file_obj):
     # We need to a.) find all distinct models referenced here and 
     # b.) store the reference data so that we can actually spawn the placeables later on
     for f in wld_file_obj.fragments.values():
         if f.type == 0x15:
             # f.dump()
             self.placeables_fragments.append(f)     # store the f15 ref
             name = f.refName
             if not self.models.has_key(name):
                 m = Model(self, name)
                 self.models[name] = m
     
     # load all referenced models
     for model in self.models.values():
         model.load()
         
     # spawn placeables
     for f in self.placeables_fragments:
         model_name = f.refName
         # print 'spawning placeable:', model_name+str(f.id)
         model = self.models[model_name]
         if model.loaded > 0:
             p_node = PandaNode(model_name+str(f.id))
         
             # for now we attach a new parent node for every placeable directly under the zone root
             np = self.zone.rootNode.attachNewNode(p_node)
             np.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullClockwise))
         
             # setting up texture alpha transparency for all models this way currently
             # seems to work well with our "masked" textures at least
             np.setTransparency(TransparencyAttrib.MAlpha)
         
             np.setPos(f.xpos, f.ypos, f.zpos )
             np.setHpr(f.xrot / 512.0 * 360.0, f.yrot / 512.0 * 360.0, f.zrot / 512.0 * 360.0 )
         
             # NOTE on placeables scale: from what I've seen so far for placeables this seems to always
             # be x=0.0 y=1.0 z=1.0
             # No idea if this is a bug or intentional. For now we assume a unified scale for x/y being
             # stored in yscale and one for z in zscale
             # print 'scalex:%f scaley:%i scalez:%f' % (f.xscale, f.yscale, f.zscale )
             np.setScale(f.yscale, f.yscale, f.zscale )
         
             # attach an instance of all the model's meshes under the placeable's NodePath
             # NOTE that we do not yet properly support animated models, they are displayed
             # all right, scale seems to be ok but trees for example are sunk into the ground etc
             # probably caused by the incomplete implementation not yet using the translation values 
             # in the 0x10 fragments or something
             
             model.meshes[0].root.instanceTo(np)
             
             '''
Ejemplo n.º 10
0
    def setShaders(self):
        """ Creates the tag state and loades the voxelizer shader """
        voxelizeShader = Shader.load(Shader.SLGLSL, 
            "Shader/GI/Voxelize.vertex",
            "Shader/GI/Voxelize.fragment")

        # Create tag state
        initialState = NodePath("VoxelizerState")
        initialState.setShader(voxelizeShader, 500)
        initialState.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullNone))
        initialState.setDepthWrite(False)
        initialState.setDepthTest(False)
        initialState.setAttrib(DepthTestAttrib.make(DepthTestAttrib.MNone))
        initialState.setShaderInput("giVoxelGenerationTex", self.voxelGenTex)

        # Apply tag state
        self.voxelizeCamera.setTagState("Default", initialState.getState())

        return [voxelizeShader]
Ejemplo n.º 11
0
 def __build_Atmos_Sphere(self):
     sphere_path = "{}/sphere_simp_6.bam".format(_path.MODELS)
     atmos_model_np = loader.loadModel(sphere_path).getChild(0)
     atmos_model_np.setName("atmos")
     atmos_model = Model(atmos_model_np)
     
     pts = atmos_model.read("vertex")
     pts = list(map(lambda pt: pt*_env.ATMOS_RADIUS, pts))
     atmos_model.modify("vertex", pts)
     atmos_model.NP.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
     atmos_model.NP.setAttrib(TransparencyAttrib.make(TransparencyAttrib.MAlpha))
     
     atmos_vert_path = "{}/env_atmos_VERT.glsl".format(_path.SHADERS)
     atmos_frag_path = "{}/env_atmos_FRAG.glsl".format(_path.SHADERS)
     atmos_shader = Shader.load(Shader.SL_GLSL, atmos_vert_path, atmos_frag_path)
     atmos_model.NP.setShader(atmos_shader)
     atmos_model.NP.setShaderInput("atmos_colour", LVector4f(0,0,0,0))
     atmos_model.NP.setBin("fixed", 10)
     atmos_model.NP.reparentTo(self.NP)
     return atmos_model.NP
Ejemplo n.º 12
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.setBackgroundColor((0, 0, 0, 0))

        # Preliminary capabilities check.

        if not self.win.getGsg().getSupportsBasicShaders():
            self.t = addTitle("Firefly Demo: Video driver reports that Cg "
                              "shaders are not supported.")
            return
        if not self.win.getGsg().getSupportsDepthTexture():
            self.t = addTitle("Firefly Demo: Video driver reports that depth "
                              "textures are not supported.")
            return

        # This algorithm uses two offscreen buffers, one of which has
        # an auxiliary bitplane, and the offscreen buffers share a single
        # depth buffer.  This is a heck of a complicated buffer setup.

        self.modelbuffer = self.makeFBO("model buffer", 1)
        self.lightbuffer = self.makeFBO("light buffer", 0)

        # Creation of a high-powered buffer can fail, if the graphics card
        # doesn't support the necessary OpenGL extensions.

        if self.modelbuffer is None or self.lightbuffer is None:
            self.t = addTitle("Toon Shader: Video driver does not support "
                              "multiple render targets")
            return

        # Create four render textures: depth, normal, albedo, and final.
        # attach them to the various bitplanes of the offscreen buffers.

        self.texDepth = Texture()
        self.texDepth.setFormat(Texture.FDepthStencil)
        self.texAlbedo = Texture()
        self.texNormal = Texture()
        self.texFinal = Texture()

        self.modelbuffer.addRenderTexture(self.texDepth,
            GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepthStencil)
        self.modelbuffer.addRenderTexture(self.texAlbedo,
            GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor)
        self.modelbuffer.addRenderTexture(self.texNormal,
            GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0)

        self.lightbuffer.addRenderTexture(self.texFinal,
            GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor)

        # Set the near and far clipping planes.

        self.cam.node().getLens().setNear(50.0)
        self.cam.node().getLens().setFar(500.0)
        lens = self.cam.node().getLens()

        # This algorithm uses three cameras: one to render the models into the
        # model buffer, one to render the lights into the light buffer, and
        # one to render "plain" stuff (non-deferred shaded) stuff into the
        # light buffer.  Each camera has a bitmask to identify it.

        self.modelMask = 1
        self.lightMask = 2
        self.plainMask = 4

        self.modelcam = self.makeCamera(self.modelbuffer,
            lens=lens, scene=render, mask=self.modelMask)
        self.lightcam = self.makeCamera(self.lightbuffer,
            lens=lens, scene=render, mask=self.lightMask)
        self.plaincam = self.makeCamera(self.lightbuffer,
            lens=lens, scene=render, mask=self.plainMask)

        # Panda's main camera is not used.

        self.cam.node().setActive(0)

        # Take explicit control over the order in which the three
        # buffers are rendered.

        self.modelbuffer.setSort(1)
        self.lightbuffer.setSort(2)
        self.win.setSort(3)

        # Within the light buffer, control the order of the two cams.

        self.lightcam.node().getDisplayRegion(0).setSort(1)
        self.plaincam.node().getDisplayRegion(0).setSort(2)

        # By default, panda usually clears the screen before every
        # camera and before every window.  Tell it not to do that.
        # Then, tell it specifically when to clear and what to clear.

        self.modelcam.node().getDisplayRegion(0).disableClears()
        self.lightcam.node().getDisplayRegion(0).disableClears()
        self.plaincam.node().getDisplayRegion(0).disableClears()
        self.cam.node().getDisplayRegion(0).disableClears()
        self.cam2d.node().getDisplayRegion(0).disableClears()
        self.modelbuffer.disableClears()
        self.win.disableClears()

        self.modelbuffer.setClearColorActive(1)
        self.modelbuffer.setClearDepthActive(1)
        self.lightbuffer.setClearColorActive(1)
        self.lightbuffer.setClearColor((0, 0, 0, 1))

        # Miscellaneous stuff.

        self.disableMouse()
        self.camera.setPos(-9.112, -211.077, 46.951)
        self.camera.setHpr(0, -7.5, 2.4)
        random.seed()

        # Calculate the projection parameters for the final shader.
        # The math here is too complex to explain in an inline comment,
        # I've put in a full explanation into the HTML intro.

        proj = self.cam.node().getLens().getProjectionMat()
        proj_x = 0.5 * proj.getCell(3, 2) / proj.getCell(0, 0)
        proj_y = 0.5 * proj.getCell(3, 2)
        proj_z = 0.5 * proj.getCell(3, 2) / proj.getCell(2, 1)
        proj_w = -0.5 - 0.5 * proj.getCell(1, 2)

        # Configure the render state of the model camera.

        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setAttrib(
            AlphaTestAttrib.make(RenderAttrib.MGreaterEqual, 0.5))
        tempnode.setShader(loader.loadShader("model.sha"))
        tempnode.setAttrib(DepthTestAttrib.make(RenderAttrib.MLessEqual))
        self.modelcam.node().setInitialState(tempnode.getState())

        # Configure the render state of the light camera.

        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setShader(loader.loadShader("light.sha"))
        tempnode.setShaderInput("texnormal", self.texNormal)
        tempnode.setShaderInput("texalbedo", self.texAlbedo)
        tempnode.setShaderInput("texdepth", self.texDepth)
        tempnode.setShaderInput("proj", (proj_x, proj_y, proj_z, proj_w))
        tempnode.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
            ColorBlendAttrib.OOne, ColorBlendAttrib.OOne))
        tempnode.setAttrib(
            CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
        # The next line causes problems on Linux.
        # tempnode.setAttrib(DepthTestAttrib.make(RenderAttrib.MGreaterEqual))
        tempnode.setAttrib(DepthWriteAttrib.make(DepthWriteAttrib.MOff))
        self.lightcam.node().setInitialState(tempnode.getState())

        # Configure the render state of the plain camera.

        rs = RenderState.makeEmpty()
        self.plaincam.node().setInitialState(rs)

        # Clear any render attribs on the root node. This is necessary
        # because by default, panda assigns some attribs to the root
        # node.  These default attribs will override the
        # carefully-configured render attribs that we just attached
        # to the cameras.  The simplest solution is to just clear
        # them all out.

        render.setState(RenderState.makeEmpty())

        # My artist created a model in which some of the polygons
        # don't have textures.  This confuses the shader I wrote.
        # This little hack guarantees that everything has a texture.

        white = loader.loadTexture("models/white.jpg")
        render.setTexture(white, 0)

        # Create two subroots, to help speed cull traversal.

        self.lightroot = NodePath(PandaNode("lightroot"))
        self.lightroot.reparentTo(render)
        self.modelroot = NodePath(PandaNode("modelroot"))
        self.modelroot.reparentTo(render)
        self.lightroot.hide(BitMask32(self.modelMask))
        self.modelroot.hide(BitMask32(self.lightMask))
        self.modelroot.hide(BitMask32(self.plainMask))

        # Load the model of a forest.  Make it visible to the model camera.
        # This is a big model, so we load it asynchronously while showing a
        # load text.  We do this by passing in a callback function.
        self.loading = addTitle("Loading models...")

        self.forest = NodePath(PandaNode("Forest Root"))
        self.forest.reparentTo(render)
        self.forest.hide(BitMask32(self.lightMask | self.plainMask))
        loader.loadModel([
            "models/background",
            "models/foliage01",
            "models/foliage02",
            "models/foliage03",
            "models/foliage04",
            "models/foliage05",
            "models/foliage06",
            "models/foliage07",
            "models/foliage08",
            "models/foliage09"],
            callback=self.finishLoading)

        # Cause the final results to be rendered into the main window on a
        # card.

        self.card = self.lightbuffer.getTextureCard()
        self.card.setTexture(self.texFinal)
        self.card.reparentTo(render2d)

        # Panda contains a built-in viewer that lets you view the results of
        # your render-to-texture operations.  This code configures the viewer.

        self.bufferViewer.setPosition("llcorner")
        self.bufferViewer.setCardSize(0, 0.40)
        self.bufferViewer.setLayout("vline")
        self.toggleCards()
        self.toggleCards()

        # Firefly parameters

        self.fireflies = []
        self.sequences = []
        self.scaleseqs = []
        self.glowspheres = []
        self.fireflysize = 1.0
        self.spheremodel = loader.loadModel("misc/sphere")

        # Create the firefly model, a fuzzy dot
        dotSize = 1.0
        cm = CardMaker("firefly")
        cm.setFrame(-dotSize, dotSize, -dotSize, dotSize)
        self.firefly = NodePath(cm.generate())
        self.firefly.setTexture(loader.loadTexture("models/firefly.png"))
        self.firefly.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.M_add,
            ColorBlendAttrib.O_incoming_alpha, ColorBlendAttrib.O_one))

        # these allow you to change parameters in realtime

        self.accept("escape", sys.exit, [0])
        self.accept("arrow_up",   self.incFireflyCount, [1.1111111])
        self.accept("arrow_down", self.decFireflyCount, [0.9000000])
        self.accept("arrow_right", self.setFireflySize, [1.1111111])
        self.accept("arrow_left",  self.setFireflySize, [0.9000000])
        self.accept("v", self.toggleCards)
        self.accept("V", self.toggleCards)
Ejemplo n.º 13
0
def drawBody(nodePath, vdata, pos, vecList, radius=1, keepDrawing=True, numVertices=8):

    circleGeom = Geom(vdata)

    vertWriter = GeomVertexWriter(vdata, "vertex")
    colorWriter = GeomVertexWriter(vdata, "color")
    normalWriter = GeomVertexWriter(vdata, "normal")
    drawReWriter = GeomVertexRewriter(vdata, "drawFlag")
    texReWriter = GeomVertexRewriter(vdata, "texcoord")

    startRow = vdata.getNumRows()
    vertWriter.setRow(startRow)
    colorWriter.setRow(startRow)
    normalWriter.setRow(startRow)

    sCoord = 0

    if (startRow != 0):
        texReWriter.setRow(startRow - numVertices)
        sCoord = texReWriter.getData2f().getX() + 1

        drawReWriter.setRow(startRow - numVertices)
        if(drawReWriter.getData1f() == False):
            sCoord -= 1

    drawReWriter.setRow(startRow)
    texReWriter.setRow(startRow)

    angleSlice = 2 * math.pi / numVertices
    currAngle = 0

    #axisAdj=LMatrix4.rotateMat(45, axis)*LMatrix4.scaleMat(radius)*LMatrix4.translateMat(pos)

    perp1 = vecList[1]
    perp2 = vecList[2]

    # vertex information is written here
    for i in range(numVertices):
        adjCircle = pos + \
            (perp1 * math.cos(currAngle) + perp2 * math.sin(currAngle)) * \
            radius
        normal = perp1 * math.cos(currAngle) + perp2 * math.sin(currAngle)
        normalWriter.addData3f(normal)
        vertWriter.addData3f(adjCircle)
        texReWriter.addData2f(sCoord, (i + 0.001) / (numVertices - 1))
        colorWriter.addData4f(0.5, 0.5, 0.5, 1)
        drawReWriter.addData1f(keepDrawing)
        currAngle += angleSlice

    drawReader = GeomVertexReader(vdata, "drawFlag")
    drawReader.setRow(startRow - numVertices)

    # we cant draw quads directly so we use Tristrips
    if (startRow != 0) & (drawReader.getData1f() != False):
        lines = GeomTristrips(Geom.UHStatic)
        half = int(numVertices * 0.5)
        for i in range(numVertices):
            lines.addVertex(i + startRow)
            if i < half:
                lines.addVertex(i + startRow - half)
            else:
                lines.addVertex(i + startRow - half - numVertices)

        lines.addVertex(startRow)
        lines.addVertex(startRow - half)
        lines.closePrimitive()
        lines.decompose()
        circleGeom.addPrimitive(lines)

        circleGeomNode = GeomNode("Debug")
        circleGeomNode.addGeom(circleGeom)

        # I accidentally made the front-face face inwards. Make reverse makes the tree render properly and
        # should cause any surprises to any poor programmer that tries to use
        # this code
        circleGeomNode.setAttrib(CullFaceAttrib.makeReverse(), 1)
        global numPrimitives
        numPrimitives += numVertices * 2

        nodePath.attachNewNode(circleGeomNode)
Ejemplo n.º 14
0
 def generateWater(self, style):
     print "Generate Water:", self.waterXMin, self.waterXMax, self.waterYMin,  self.waterYMax
     '''Generates water
     style 0: blue card
     style 1: reflective card
     style 2: reflective card with shaders
     '''
     self.waterHeight = 22.0
     if self.water:
         self.water.removeNode()
     if style is 0:
         cm = CardMaker("water")
         #cm.setFrame(-1, 1, -1, 1)
         cm.setFrame(self.waterXMin, self.waterXMax, self.waterYMin,  self.waterYMax)
         cm.setColor(0, 0, 1, 0.9)
         self.water = render.attachNewNode(cm.generate())
         if self.waterYMax > self.waterXMax:
             size = self.waterYMax
         else:
             size = self.waterXMax
         self.water.lookAt(0, 0, -1)
         self.water.setZ(self.waterHeight)
         messenger.send('makePickable', [self.water])
     elif style is 1:
         # From Prosoft's super awesome terrain demo
         cm = CardMaker("water")
         #cm.setFrame(-1, 1, -1, 1)
         cm.setFrame(self.waterXMin, self.waterXMax, self.waterYMin,  self.waterYMax)
         self.water = render.attachNewNode(cm.generate())
         if self.waterYMax > self.waterXMax:
             size = self.waterYMax
         else:
             size = self.waterXMax
         #self.water.setScale(size)
         self.water.lookAt(0, 0, -1)
         self.water.setZ(self.waterHeight)
         self.water.setShaderOff(1)
         self.water.setLightOff(1)
         self.water.setAlphaScale(0.5)
         self.water.setTransparency(TransparencyAttrib.MAlpha)
         wbuffer = base.win.makeTextureBuffer("water", 512, 512)
         wbuffer.setClearColorActive(True)
         wbuffer.setClearColor(base.win.getClearColor())
         self.wcamera = base.makeCamera(wbuffer)
         self.wcamera.reparentTo(render)
         self.wcamera.node().setLens(base.camLens)
         self.wcamera.node().setCameraMask(BitMask32.bit(1))
         self.water.hide(BitMask32.bit(1))
         wtexture = wbuffer.getTexture()
         wtexture.setWrapU(Texture.WMClamp)
         wtexture.setWrapV(Texture.WMClamp)
         wtexture.setMinfilter(Texture.FTLinearMipmapLinear)
         self.wplane = Plane(Vec3(0, 0, 1), Point3(0, 0, self.water.getZ()))
         wplanenp = render.attachNewNode(PlaneNode("water", self.wplane))
         tmpnp = NodePath("StateInitializer")
         tmpnp.setClipPlane(wplanenp)
         tmpnp.setAttrib(CullFaceAttrib.makeReverse())
         self.wcamera.node().setInitialState(tmpnp.getState())
         self.water.projectTexture(TextureStage("reflection"), wtexture, self.wcamera)
         messenger.send('makePickable', [self.water])
     elif style is 2:
         # From Clcheung just as super awesome demomaster
         self.water_level = Vec4(0.0, 0.0, self.waterHeight, 1.0)
         self.water = water.WaterNode(self.waterXMin, self.waterYMin, self.waterXMax, self.waterYMax, self.water_level.getZ())
         self.water.setStandardControl()
         self.water.changeParams(None)
         wl=self.water_level
         wl.setZ(wl.getZ()-0.05)
         #root.setShaderInput('waterlevel', self.water_level)
         render.setShaderInput('time', 0)
         messenger.send('makePickable', [self.water.waterNP])
Ejemplo n.º 15
0
def drawBody(nodePath,
             vdata,
             pos,
             vecList,
             radius=1,
             keepDrawing=True,
             numVertices=8):

    circleGeom = Geom(vdata)

    vertWriter = GeomVertexWriter(vdata, "vertex")
    colorWriter = GeomVertexWriter(vdata, "color")
    normalWriter = GeomVertexWriter(vdata, "normal")
    drawReWriter = GeomVertexRewriter(vdata, "drawFlag")
    texReWriter = GeomVertexRewriter(vdata, "texcoord")

    startRow = vdata.getNumRows()
    vertWriter.setRow(startRow)
    colorWriter.setRow(startRow)
    normalWriter.setRow(startRow)

    sCoord = 0

    if (startRow != 0):
        texReWriter.setRow(startRow - numVertices)
        sCoord = texReWriter.getData2f().getX() + 1

        drawReWriter.setRow(startRow - numVertices)
        if (drawReWriter.getData1f() == False):
            sCoord -= 1

    drawReWriter.setRow(startRow)
    texReWriter.setRow(startRow)

    angleSlice = 2 * math.pi / numVertices
    currAngle = 0

    #axisAdj=Mat4.rotateMat(45, axis)*Mat4.scaleMat(radius)*Mat4.translateMat(pos)

    perp1 = vecList[1]
    perp2 = vecList[2]

    #vertex information is written here
    for i in range(numVertices):
        adjCircle = pos + (perp1 * math.cos(currAngle) +
                           perp2 * math.sin(currAngle)) * radius
        normal = perp1 * math.cos(currAngle) + perp2 * math.sin(currAngle)
        normalWriter.addData3f(normal)
        vertWriter.addData3f(adjCircle)
        texReWriter.addData2f(sCoord, (i + 0.001) / (numVertices - 1))
        colorWriter.addData4f(0.5, 0.5, 0.5, 1)
        drawReWriter.addData1f(keepDrawing)
        currAngle += angleSlice

    drawReader = GeomVertexReader(vdata, "drawFlag")
    drawReader.setRow(startRow - numVertices)

    #we cant draw quads directly so we use Tristrips
    if (startRow != 0) & (drawReader.getData1f() != False):
        lines = GeomTristrips(Geom.UHStatic)
        half = int(numVertices * 0.5)
        for i in range(numVertices):
            lines.addVertex(i + startRow)
            if i < half:
                lines.addVertex(i + startRow - half)
            else:
                lines.addVertex(i + startRow - half - numVertices)

        lines.addVertex(startRow)
        lines.addVertex(startRow - half)
        lines.closePrimitive()
        lines.decompose()
        circleGeom.addPrimitive(lines)

        circleGeomNode = GeomNode("Debug")
        circleGeomNode.addGeom(circleGeom)

        #I accidentally made the front-face face inwards. Make reverse makes the tree render properly and
        #should cause any surprises to any poor programmer that tries to use this code
        circleGeomNode.setAttrib(CullFaceAttrib.makeReverse(), 1)
        global numPrimitives
        numPrimitives += numVertices * 2

        nodePath.attachNewNode(circleGeomNode)
Ejemplo n.º 16
0
    def onSceneLoaded(self, scene):
        """ Callback which gets called after the scene got loaded """

        self.debug("Successfully loaded scene")

        self.loadingScreen.setStatus("Loading skybox", 70)

        self.scene = scene
        self.scene.prepareScene(self.win.getGsg())
        # render.hide(self.renderPipeline.getVoxelizePassBitmask())
        # self.scene.hide(self.renderPipeline.getVoxelizePassBitmask())

        # Load surround scene
        if self.sceneSourceSurround is not None:
            self.debug("Loading Surround-Scene '" + self.sceneSourceSurround +
                       "'")
            self.sceneSurround = self.loader.loadModel(
                self.sceneSourceSurround)
            self.sceneSurround.reparentTo(self.scene)
            # self.sceneSurround.setScale(0.7)
            # self.sceneSurround.setH(180)
            # self.sceneSurround.setPos(0, -4.7, 0.73)

        seed(1)

        # Performance testing
        if False:
            highPolyObj = self.scene.find("**/HighPolyObj")

            if highPolyObj is not None and not highPolyObj.isEmpty():
                # highPolyObj.detachNode()
                self.loadingScreen.setStatus("Preparing Performance Test", 75)

                for x in xrange(0, 20):
                    for y in xrange(0, 1):
                        # if True:
                        # y = 5
                        copiedObj = copy.deepcopy(highPolyObj)
                        copiedObj.setColorScale(random(), random(), random(),
                                                1)
                        # if random() < 0.2:
                        # copiedObj.setColorScale(0.4, 1.2, 2.0, 1.0)

                        copiedObj.reparentTo(self.scene)
                        copiedObj.setPos(x * 1.5 + random(),
                                         y * 1.5 + random(),
                                         random() * 5.0 + 0.4)

        # Find transparent objects and mark them as transparent
        if self.renderPipeline.settings.useTransparency:
            self.transpObjRoot = render.attachNewNode("transparentObjects")
            matches = self.scene.findAllMatches("**/T__*")
            if matches:
                for match in matches:
                    # match.hide()
                    # continue
                    self.transparentObjects.append(match)
                    self.renderPipeline.setEffect(
                        match, "Effects/Default/Default.effect",
                        {"transparent": True})
                    match.setAttrib(CullFaceAttrib.make(CullFaceAttrib.M_none))

        for i in ["53", "54", "55", "56", "57"]:
            matches = self.scene.findAllMatches("**/" + i)
            for match in matches:
                match.remove()

        # Wheter to use a ground plane

        self.sceneWireframe = False

        # Flatten scene?
        self.loadingScreen.setStatus("Optimizing Scene", 90)

        # self.scene.clearModelNodes()
        loader.asyncFlattenStrong(self.scene,
                                  inPlace=False,
                                  callback=self.onScenePrepared)
    def __init__(self, name, size=10000, resolution=1024):
        """Arguments:
        size -- Edge length of the water square.
        resolution -- Texture size of the rendered reflection buffer.
        """
        # Uncomment to see the output of the refclection buffer.
        base.bufferViewer.toggleEnable()

        AssetBase.__init__(self)
        self.name = name

        self.cm = CardMaker("water surface")
        self.cm.setFrame(-0.5 * size, 0.5 * size, -0.5 * size, 0.5 * size)
        self.cm.setHasUvs(True)
        self.node = NodePath(self.cm.generate())

        self.node.setP(self.node, -90)
        self.node.flattenLight()
        self.node.hide(BitMask32.bit(1))
        # self.node.setTwoSided(True)
        self.node.setShaderOff()

        # size of one texture tile in meters
        self.tex_size = 100.0

        diffuse = TexturePool.loadTexture("textures/water.diffuse.png")
        diffuse.setWrapU(Texture.WMRepeat)
        diffuse.setWrapV(Texture.WMRepeat)
        diffuse.setMinfilter(Texture.FTLinearMipmapLinear)
        diffuse.setMagfilter(Texture.FTLinearMipmapLinear)
        self.diffuse_stage = TextureStage("diffuse")
        self.diffuse_stage.setSort(2)
        self.node.setTexture(self.diffuse_stage, diffuse)
        self.node.setTexScale(self.diffuse_stage, size / self.tex_size, size / self.tex_size)

        # Reflection camera renders to 'buffer' which is projected onto the
        # water surface.
        buffer = base.win.makeTextureBuffer("water reflection", resolution, resolution)
        buffer.setClearColor(Vec4(0, 0, 0, 1))

        self.refl_cam = base.makeCamera(buffer)
        self.refl_cam.reparentTo(self.node)
        self.refl_cam.node().setCameraMask(BitMask32.bit(1))
        self.refl_cam.node().getLens().setFov(base.camLens.getFov())
        self.refl_cam.node().getLens().setNearFar(1, 100000)

        plane = PlaneNode("water culling plane", Plane(Vec3(0, 0, 1), Point3(0, 0, 0)))
        cfa = CullFaceAttrib.makeReverse()
        cpa = ClipPlaneAttrib.make(PlaneNode.CEVisible, plane)
        rs = RenderState.make(cfa, cpa)
        self.refl_cam.node().setInitialState(rs)

        reflection = buffer.getTexture()
        reflection.setMinfilter(Texture.FTLinear)
        reflection.setMagfilter(Texture.FTLinear)
        self.refl_stage = TextureStage("reflection")
        self.refl_stage.setSort(1)
        self.node.projectTexture(self.refl_stage, reflection, base.cam)
        self.node.setTexture(self.refl_stage, reflection)

        # Blend between diffuse and reflection.
        self.diffuse_stage.setColor(VBase4(1, 1, 1, 0.2))  # opacity of 20%
        self.diffuse_stage.setCombineRgb(
            TextureStage.CMInterpolate,
            TextureStage.CSTexture,
            TextureStage.COSrcColor,
            TextureStage.CSPrevious,
            TextureStage.COSrcColor,
            TextureStage.CSConstant,
            TextureStage.COSrcAlpha,
        )

        self.addTask(self.update, name="water update", sort=1, taskChain="world")
Ejemplo n.º 18
0
    def onSceneLoaded(self, scene):
        """ Callback which gets called after the scene got loaded """

        self.debug("Successfully loaded scene")

        self.loadingScreen.setStatus("Loading skybox", 70)

        self.scene = scene
        # self.scene.hide(self.renderPipeline.getMainPassBitmask())
        self.scene.prepareScene(self.win.getGsg())

        # Load surround scene
        if self.sceneSourceSurround is not None:
            self.debug("Loading Surround-Scene '" + self.sceneSourceSurround + "'")
            self.sceneSurround = self.loader.loadModel(self.sceneSourceSurround)
            self.sceneSurround.reparentTo(self.scene)
            # self.sceneSurround.setScale(0.7)
            # self.sceneSurround.setH(180)
            # self.sceneSurround.setPos(0, -4.7, 0.73)

        seed(1)

        # Performance testing
        if False:
            highPolyObj = self.scene.find("**/HighPolyObj")

            if highPolyObj is not None and not highPolyObj.isEmpty():
                # highPolyObj.detachNode()
                self.loadingScreen.setStatus("Preparing Performance Test", 75)

                for x in xrange(0, 20):
                    # for y in xrange(0, 1):
                    if True:
                        y = 5
                        copiedObj = copy.deepcopy(highPolyObj)
                        copiedObj.setColorScale(random(), random(), random(), 1)
                        # if random() < 0.2:
                            # copiedObj.setColorScale(0.4, 1.2, 2.0, 1.0)

                        copiedObj.reparentTo(self.scene)
                        copiedObj.setPos(x*1.5 + random(), y*1.5 + random(), random()*5.0 + 0.4)

        # Find transparent objects and mark them as transparent
        if self.renderPipeline.settings.useTransparency:
            self.transpObjRoot = render.attachNewNode("transparentObjects")
            matches = self.scene.findAllMatches("**/T__*")
            if matches:
                for match in matches:
                    # match.hide()
                    # continue
                    self.transparentObjects.append(match)
                    self.renderPipeline.setEffect(match, "Effects/Default/Default.effect", {
                        "transparent": True
                        })
                    match.setAttrib(CullFaceAttrib.make(CullFaceAttrib.M_none))

        for i in ["53", "54", "55", "56", "57"]:
            matches = self.scene.findAllMatches("**/" + i)
            for match in matches:
                match.remove()

        # Wheter to use a ground plane
        self.usePlane = True
        self.sceneWireframe = False

        # Flatten scene?
        self.loadingScreen.setStatus("Optimizing Scene", 90)

        # self.scene.clearModelNodes()
        # loader.asyncFlattenStrong(self.scene, inPlace=False, callback=self.onScenePrepared)
        self.onScenePrepared()
Ejemplo n.º 19
0
    Drawn = 2
    MovingPoint1 = 3
    MovingPoint2 = 4
    MovingPoint3 = 5


class ClipSide(IntEnum):
    Both = 0
    Front = 1
    Back = 2


PlaneVis3DState = RenderState.make(
    ColorAttrib.makeFlat(Vec4(0, 1, 1, 0.5)),
    TransparencyAttrib.make(TransparencyAttrib.MAlpha),
    CullFaceAttrib.make(CullFaceAttrib.MCullNone))

PlaneVis2DState = RenderState.make(
    ColorAttrib.makeFlat(Vec4(0, 1, 1, 1)),
    CullBinAttrib.make("fixed", LEGlobals.BoxSort),
    CullFaceAttrib.make(CullFaceAttrib.MCullNone))


# Draws the clip plane lines and move handles in each 2D viewport
class ClipToolViewport2D:
    def __init__(self, tool, vp):
        self.tool = tool
        self.vp = vp

        self.hPoint1 = self.makeHandle()
        self.hPoint2 = self.makeHandle()
Ejemplo n.º 20
0
def getStateFromMaterial(prim_material, texture_cache, col_inst=None):
    state = RenderState.makeEmpty()
    
    mat = Material()
    texattr = TextureAttrib.makeAllOff()
    
    hasDiffuse = False
    if prim_material and prim_material.effect:
        
        diffuse = getattr(prim_material.effect, 'diffuse', None)
        transparent = getattr(prim_material.effect, 'transparent', None)
        if isinstance(diffuse, collada.material.Map) and isinstance(transparent, collada.material.Map):
            if diffuse.sampler.surface.image == transparent.sampler.surface.image:
                #some exporters put the same map in the diffuse channel
                # and the transparent channel when they don't really mean to
                transparent = None
        
        if isinstance(diffuse, collada.material.Map) or isinstance(transparent, collada.material.Map):
            diffuseMap = None
            transparentMap = None
            diffuseInitColor = None
            if isinstance(diffuse, collada.material.Map):
                diffuseMap = diffuse
            else:
                diffuseInitColor = v4fromtuple(diffuse)
            if isinstance(transparent, collada.material.Map):
                transparentMap = transparent
            if diffuseMap == transparentMap:
                transparentMap = None
                
            diffuseTexture = getTexture(color=diffuseMap, alpha=transparentMap, texture_cache=texture_cache, diffuseinit=diffuseInitColor)
            texattr = addTextureStage('tsDiff', TextureStage.MModulate, texattr, diffuseTexture)
            hasDiffuse = True

        if type(diffuse) is tuple:
            mat.setDiffuse(v4fromtuple(diffuse))
        
        # hack to look for sketchup version < 8 where transparency was exported flipped
        # also ColladaMaya v2.03b had this same issue
        flip_alpha = False
        if col_inst and col_inst.assetInfo:
            for contributor in col_inst.assetInfo.contributors:
                tool_name = contributor.authoring_tool
                if tool_name is None:
                    continue
                split = tool_name.split()
                if len(split) == 3 and \
                      split[0].strip().lower() == 'google' and \
                      split[1].strip().lower() == 'sketchup':
                    version = split[2].strip().split('.')
                    try:
                        major_version = int(version[0])
                        if major_version < 8:
                            flip_alpha = True
                    except (ValueError, TypeError):
                        continue
                    
                try:
                    collada_maya_idx = split.index('ColladaMaya')
                    if split[collada_maya_idx + 1] == 'v2.03b':
                        flip_alpha = True
                except (ValueError, IndexError):
                    continue
        
        if type(transparent) is tuple:
            trR, trG, trB = transparent[0], transparent[1], transparent[2]
            trA = transparent[3] if len(transparent) > 3 else 1.0
        else:
            trR, trG, trB = 1.0, 1.0, 1.0
            trA = 1.0
        
        transparency = getattr(prim_material.effect, 'transparency', 1.0)
        if transparency is None:
            transparency = 1.0
        a_one = prim_material.effect.opaque_mode == collada.material.OPAQUE_MODE.A_ONE
        if a_one:
            alphaR = alphaG = alphaB = alphaA = transparency * trA
        else:
            alphaR = transparency * trR
            alphaG = transparency * trG
            alphaB = transparency * trB
            alphaA = luminance([trR, trG, trB])
            flip_alpha = not flip_alpha
        
        if flip_alpha:
            alphaR = 1.0 - alphaR
            alphaG = 1.0 - alphaG
            alphaB = 1.0 - alphaB
            alphaA = 1.0 - alphaA
        
        if alphaA < 1.0:
            state = state.addAttrib(ColorScaleAttrib.make(VBase4(alphaR, alphaG, alphaB, alphaA)))
        
        emission = getattr(prim_material.effect, 'emission', None)
        if isinstance(emission, collada.material.Map):
            emissionTexture = getTexture(alpha=emission, texture_cache=texture_cache)
            texattr = addTextureStage('tsEmiss', TextureStage.MGlow, texattr, emissionTexture)
        elif type(emission) is tuple:
            mat.setEmission(v4fromtuple(emission))
        
        ambient = getattr(prim_material.effect, 'ambient', None)
        if type(ambient) is tuple:
            mat.setAmbient(v4fromtuple(ambient))
        
        specular = getattr(prim_material.effect, 'specular', None)
        if isinstance(specular, collada.material.Map):
            specularTexture = getTexture(color=specular, texture_cache=texture_cache)
            texattr = addTextureStage('tsSpec', TextureStage.MGloss, texattr, specularTexture)
            mat.setSpecular(VBase4(0.1, 0.1, 0.1, 1.0))
        elif type(specular) is tuple:
            mat.setSpecular(v4fromtuple(specular))

        shininess = getattr(prim_material.effect, 'shininess', None)
        #this sets a sane value for blinn shading
        if shininess <= 1.0:
            if shininess < 0.01:
                shininess = 1.0
            shininess = shininess * 128.0
        mat.setShininess(shininess)

        bumpmap = getattr(prim_material.effect, 'bumpmap', None)
        if isinstance(bumpmap, collada.material.Map):
            bumpTexture = getTexture(color=bumpmap, texture_cache=texture_cache)
            texattr = addTextureStage('tsBump', TextureStage.MNormal, texattr, bumpTexture)

        if prim_material.effect.double_sided:
            state = state.addAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullNone))

    if hasDiffuse:
        state = state.addAttrib(DepthOffsetAttrib.make(1))
    
    state = state.addAttrib(MaterialAttrib.make(mat))
    state = state.addAttrib(texattr)
    
    return state
Ejemplo n.º 21
0
    def __init__(self, name, reso, height, planeVec, reflection = False, needDepth = False):
        fbp = FrameBufferProperties()
        fbp.clear()
        fbp.set_depth_bits( 8 )
        fbp.set_force_hardware( True )
        fbp.set_rgba_bits( 8, 8, 8, 8 )
        fbp.set_stencil_bits( 0 )
        fbp.set_float_color( False )
        fbp.set_float_depth( False )
        fbp.set_stereo( False )
        fbp.set_accum_bits( 0 )
        fbp.set_aux_float( 0 )
        fbp.set_aux_rgba( 0 )
        fbp.set_aux_hrgba( 0 )
        fbp.set_coverage_samples( 0 )
        fbp.set_multisamples( 0 )
        
        buffer = base.win.makeTextureBuffer(name, reso, reso, None, False, fbp)
        buffer.setSort(-10000)
        buffer.disableClears()
        buffer.setClearDepthActive(True)

        self.buffer = buffer
        
        self.camera = base.makeCamera(buffer)
        self.camera.node().setLens(base.camLens)
        self.camera.node().setCameraMask(CIGlobals.ReflectionCameraBitmask)

        self.texture = buffer.getTexture()
        self.texture.setWrapU(Texture.WMClamp)
        self.texture.setWrapV(Texture.WMClamp)
        self.texture.setMinfilter(Texture.FTLinearMipmapLinear)

        if needDepth:
            depthTex = Texture(name + "_depth")
            depthTex.setWrapU(Texture.WMClamp)
            depthTex.setWrapV(Texture.WMClamp)
            depthTex.setMinfilter(Texture.FTLinearMipmapLinear)

            buffer.addRenderTexture(depthTex, GraphicsOutput.RTMBindOrCopy,
                                    GraphicsOutput.RTPDepth)

            self.depthTex = depthTex

        self.plane = Plane(planeVec, Point3(0, 0, height))
        self.planeNode = PlaneNode(name + "_plane", self.plane)
        self.planeNP = render.attachNewNode(self.planeNode)
        tmpnp = NodePath("StateInitializer")
        tmpnp.setClipPlane(self.planeNP)
        if reflection:
            tmpnp.setAttrib(CullFaceAttrib.makeReverse())
        else:
            tmpnp.setAttrib(CullFaceAttrib.makeDefault())
        # As an optimization, disable any kind of shaders (mainly the ShaderGenerator) on the
        # reflected/refracted scene.
        #tmpnp.setShaderOff(10)
        tmpnp.setLightOff(10)
        tmpnp.setAntialias(0, 10)
        self.camera.node().setInitialState(tmpnp.getState())

        self.disable()
Ejemplo n.º 22
0
    def create(self):
        # Create the voxel grid used to generate the voxels
        self.voxel_temp_grid = Image.create_3d(
            "VoxelsTemp", self.voxel_resolution, self.voxel_resolution,
            self.voxel_resolution, "RGBA8")
        self.voxel_temp_grid.set_clear_color(Vec4(0))
        self.voxel_temp_nrm_grid = Image.create_3d(
            "VoxelsTemp", self.voxel_resolution, self.voxel_resolution,
            self.voxel_resolution, "R11G11B10")
        self.voxel_temp_nrm_grid.set_clear_color(Vec4(0))

        # Create the voxel grid which is a copy of the temporary grid, but stable
        self.voxel_grid = Image.create_3d(
            "Voxels", self.voxel_resolution, self.voxel_resolution, self.voxel_resolution, "RGBA8")
        self.voxel_grid.set_clear_color(Vec4(0))
        self.voxel_grid.set_minfilter(SamplerState.FT_linear_mipmap_linear)

        # Create the camera for voxelization
        self.voxel_cam = Camera("VoxelizeCam")
        self.voxel_cam.set_camera_mask(self._pipeline.tag_mgr.get_voxelize_mask())
        self.voxel_cam_lens = OrthographicLens()
        self.voxel_cam_lens.set_film_size(
            -2.0 * self.voxel_world_size, 2.0 * self.voxel_world_size)
        self.voxel_cam_lens.set_near_far(0.0, 2.0 * self.voxel_world_size)
        self.voxel_cam.set_lens(self.voxel_cam_lens)
        self.voxel_cam_np = Globals.base.render.attach_new_node(self.voxel_cam)
        self._pipeline.tag_mgr.register_camera("voxelize", self.voxel_cam)

        # Create the voxelization target
        self.voxel_target = self.create_target("VoxelizeScene")
        self.voxel_target.size = self.voxel_resolution
        self.voxel_target.prepare_render(self.voxel_cam_np)

        # Create the target which copies the voxel grid
        self.copy_target = self.create_target("CopyVoxels")
        self.copy_target.size = self.voxel_resolution
        self.copy_target.prepare_buffer()

        # TODO! Does not work with the new render target yet - maybe add option
        # to post process region for instances?
        self.copy_target.instance_count = self.voxel_resolution
        self.copy_target.set_shader_input("SourceTex", self.voxel_temp_grid)
        self.copy_target.set_shader_input("DestTex", self.voxel_grid)

        # Create the target which generates the mipmaps
        self.mip_targets = []
        mip_size, mip = self.voxel_resolution, 0
        while mip_size > 1:
            mip_size, mip = mip_size // 2, mip + 1
            mip_target = self.create_target("GenMipmaps:" + str(mip))
            mip_target.size = mip_size
            mip_target.prepare_buffer()
            mip_target.instance_count = mip_size
            mip_target.set_shader_input("SourceTex", self.voxel_grid)
            mip_target.set_shader_input("sourceMip", mip - 1)
            mip_target.set_shader_input("DestTex", self.voxel_grid, False, True, -1, mip, 0)
            self.mip_targets.append(mip_target)

        # Create the initial state used for rendering voxels
        initial_state = NodePath("VXGIInitialState")
        initial_state.set_attrib(CullFaceAttrib.make(CullFaceAttrib.M_cull_none), 100000)
        initial_state.set_attrib(DepthTestAttrib.make(DepthTestAttrib.M_none), 100000)
        initial_state.set_attrib(ColorWriteAttrib.make(ColorWriteAttrib.C_off), 100000)
        self.voxel_cam.set_initial_state(initial_state.get_state())

        Globals.base.render.set_shader_input("voxelGridPosition", self.pta_next_grid_pos)
        Globals.base.render.set_shader_input("VoxelGridDest", self.voxel_temp_grid)
Ejemplo n.º 23
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.setBackgroundColor((0, 0, 0, 0))

        # Preliminary capabilities check.

        if not self.win.getGsg().getSupportsBasicShaders():
            self.t = addTitle("Firefly Demo: Video driver reports that Cg "
                              "shaders are not supported.")
            return
        if not self.win.getGsg().getSupportsDepthTexture():
            self.t = addTitle("Firefly Demo: Video driver reports that depth "
                              "textures are not supported.")
            return

        # This algorithm uses two offscreen buffers, one of which has
        # an auxiliary bitplane, and the offscreen buffers share a single
        # depth buffer.  This is a heck of a complicated buffer setup.

        self.modelbuffer = self.makeFBO("model buffer", 1)
        self.lightbuffer = self.makeFBO("light buffer", 0)

        # Creation of a high-powered buffer can fail, if the graphics card
        # doesn't support the necessary OpenGL extensions.

        if self.modelbuffer is None or self.lightbuffer is None:
            self.t = addTitle("Toon Shader: Video driver does not support "
                              "multiple render targets")
            return

        # Create four render textures: depth, normal, albedo, and final.
        # attach them to the various bitplanes of the offscreen buffers.

        self.texDepth = Texture()
        self.texDepth.setFormat(Texture.FDepthStencil)
        self.texAlbedo = Texture()
        self.texNormal = Texture()
        self.texFinal = Texture()

        self.modelbuffer.addRenderTexture(self.texDepth,
            GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepthStencil)
        self.modelbuffer.addRenderTexture(self.texAlbedo,
            GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor)
        self.modelbuffer.addRenderTexture(self.texNormal,
            GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0)

        self.lightbuffer.addRenderTexture(self.texFinal,
            GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor)

        # Set the near and far clipping planes.

        self.cam.node().getLens().setNear(50.0)
        self.cam.node().getLens().setFar(500.0)
        lens = self.cam.node().getLens()

        # This algorithm uses three cameras: one to render the models into the
        # model buffer, one to render the lights into the light buffer, and
        # one to render "plain" stuff (non-deferred shaded) stuff into the
        # light buffer.  Each camera has a bitmask to identify it.

        self.modelMask = 1
        self.lightMask = 2
        self.plainMask = 4

        self.modelcam = self.makeCamera(self.modelbuffer,
            lens=lens, scene=render, mask=self.modelMask)
        self.lightcam = self.makeCamera(self.lightbuffer,
            lens=lens, scene=render, mask=self.lightMask)
        self.plaincam = self.makeCamera(self.lightbuffer,
            lens=lens, scene=render, mask=self.plainMask)

        # Panda's main camera is not used.

        self.cam.node().setActive(0)

        # Take explicit control over the order in which the three
        # buffers are rendered.

        self.modelbuffer.setSort(1)
        self.lightbuffer.setSort(2)
        self.win.setSort(3)

        # Within the light buffer, control the order of the two cams.

        self.lightcam.node().getDisplayRegion(0).setSort(1)
        self.plaincam.node().getDisplayRegion(0).setSort(2)

        # By default, panda usually clears the screen before every
        # camera and before every window.  Tell it not to do that.
        # Then, tell it specifically when to clear and what to clear.

        self.modelcam.node().getDisplayRegion(0).disableClears()
        self.lightcam.node().getDisplayRegion(0).disableClears()
        self.plaincam.node().getDisplayRegion(0).disableClears()
        self.cam.node().getDisplayRegion(0).disableClears()
        self.cam2d.node().getDisplayRegion(0).disableClears()
        self.modelbuffer.disableClears()
        self.win.disableClears()

        self.modelbuffer.setClearColorActive(1)
        self.modelbuffer.setClearDepthActive(1)
        self.lightbuffer.setClearColorActive(1)
        self.lightbuffer.setClearColor((0, 0, 0, 1))

        # Miscellaneous stuff.

        self.disableMouse()
        self.camera.setPos(-9.112, -211.077, 46.951)
        self.camera.setHpr(0, -7.5, 2.4)
        random.seed()

        # Calculate the projection parameters for the final shader.
        # The math here is too complex to explain in an inline comment,
        # I've put in a full explanation into the HTML intro.

        proj = self.cam.node().getLens().getProjectionMat()
        proj_x = 0.5 * proj.getCell(3, 2) / proj.getCell(0, 0)
        proj_y = 0.5 * proj.getCell(3, 2)
        proj_z = 0.5 * proj.getCell(3, 2) / proj.getCell(2, 1)
        proj_w = -0.5 - 0.5 * proj.getCell(1, 2)

        # Configure the render state of the model camera.

        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setAttrib(
            AlphaTestAttrib.make(RenderAttrib.MGreaterEqual, 0.5))
        tempnode.setShader(loader.loadShader("model.sha"))
        tempnode.setAttrib(DepthTestAttrib.make(RenderAttrib.MLessEqual))
        self.modelcam.node().setInitialState(tempnode.getState())

        # Configure the render state of the light camera.

        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setShader(loader.loadShader("light.sha"))
        tempnode.setShaderInput("texnormal", self.texNormal)
        tempnode.setShaderInput("texalbedo", self.texAlbedo)
        tempnode.setShaderInput("texdepth", self.texDepth)
        tempnode.setShaderInput("proj", (proj_x, proj_y, proj_z, proj_w))
        tempnode.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
            ColorBlendAttrib.OOne, ColorBlendAttrib.OOne))
        tempnode.setAttrib(
            CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
        # The next line causes problems on Linux.
        # tempnode.setAttrib(DepthTestAttrib.make(RenderAttrib.MGreaterEqual))
        tempnode.setAttrib(DepthWriteAttrib.make(DepthWriteAttrib.MOff))
        self.lightcam.node().setInitialState(tempnode.getState())

        # Configure the render state of the plain camera.

        rs = RenderState.makeEmpty()
        self.plaincam.node().setInitialState(rs)

        # Clear any render attribs on the root node. This is necessary
        # because by default, panda assigns some attribs to the root
        # node.  These default attribs will override the
        # carefully-configured render attribs that we just attached
        # to the cameras.  The simplest solution is to just clear
        # them all out.

        render.setState(RenderState.makeEmpty())

        # My artist created a model in which some of the polygons
        # don't have textures.  This confuses the shader I wrote.
        # This little hack guarantees that everything has a texture.

        white = loader.loadTexture("models/white.jpg")
        render.setTexture(white, 0)

        # Create two subroots, to help speed cull traversal.

        self.lightroot = NodePath(PandaNode("lightroot"))
        self.lightroot.reparentTo(render)
        self.modelroot = NodePath(PandaNode("modelroot"))
        self.modelroot.reparentTo(render)
        self.lightroot.hide(BitMask32(self.modelMask))
        self.modelroot.hide(BitMask32(self.lightMask))
        self.modelroot.hide(BitMask32(self.plainMask))

        # Load the model of a forest.  Make it visible to the model camera.
        # This is a big model, so we load it asynchronously while showing a
        # load text.  We do this by passing in a callback function.
        self.loading = addTitle("Loading models...")

        self.forest = NodePath(PandaNode("Forest Root"))
        self.forest.reparentTo(render)
        self.forest.hide(BitMask32(self.lightMask | self.plainMask))
        loader.loadModel([
            "models/background",
            "models/foliage01",
            "models/foliage02",
            "models/foliage03",
            "models/foliage04",
            "models/foliage05",
            "models/foliage06",
            "models/foliage07",
            "models/foliage08",
            "models/foliage09"],
            callback=self.finishLoading)

        # Cause the final results to be rendered into the main window on a
        # card.

        self.card = self.lightbuffer.getTextureCard()
        self.card.setTexture(self.texFinal)
        self.card.reparentTo(render2d)

        # Panda contains a built-in viewer that lets you view the results of
        # your render-to-texture operations.  This code configures the viewer.

        self.bufferViewer.setPosition("llcorner")
        self.bufferViewer.setCardSize(0, 0.40)
        self.bufferViewer.setLayout("vline")
        self.toggleCards()
        self.toggleCards()

        # Firefly parameters

        self.fireflies = []
        self.sequences = []
        self.scaleseqs = []
        self.glowspheres = []
        self.fireflysize = 1.0
        self.spheremodel = loader.loadModel("misc/sphere")

        # Create the firefly model, a fuzzy dot
        dotSize = 1.0
        cm = CardMaker("firefly")
        cm.setFrame(-dotSize, dotSize, -dotSize, dotSize)
        self.firefly = NodePath(cm.generate())
        self.firefly.setTexture(loader.loadTexture("models/firefly.png"))
        self.firefly.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.M_add,
            ColorBlendAttrib.O_incoming_alpha, ColorBlendAttrib.O_one))

        # these allow you to change parameters in realtime

        self.accept("escape", sys.exit, [0])
        self.accept("arrow_up",   self.incFireflyCount, [1.1111111])
        self.accept("arrow_down", self.decFireflyCount, [0.9000000])
        self.accept("arrow_right", self.setFireflySize, [1.1111111])
        self.accept("arrow_left",  self.setFireflySize, [0.9000000])
        self.accept("v", self.toggleCards)
        self.accept("V", self.toggleCards)