예제 #1
0
 def flipped_faces(self, value):
     self._flipped_faces = value
     if value:
         self.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullClockwise))
     else:
         self.setAttrib(
             CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
예제 #2
0
파일: entity.py 프로젝트: gargaki13/ursina
    def flip_faces(self):
        if not hasattr(self, '_vertex_order'):
            self._vertex_order = True

        self._vertex_order = not self._vertex_order
        if self._vertex_order:
            self.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullClockwise))
        else:
            self.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
예제 #3
0
 def update_instance(self, camera_pos, orientation):
     radius = self.parent.get_apparent_radius() + self.height
     inside = self.parent.distance_to_obs < radius
     if self.inside != inside:
         if inside:
             self.instance.setAttrib(
                 CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
         else:
             self.instance.setAttrib(
                 CullFaceAttrib.make(CullFaceAttrib.MCullClockwise))
         self.inside = inside
     return ShapeObject.update_instance(self, camera_pos, orientation)
def test_cullfaceattrib_compare():
    clockwise1 = CullFaceAttrib.make()
    clockwise2 = CullFaceAttrib.make()
    reverse1 = CullFaceAttrib.make_reverse()
    reverse2 = CullFaceAttrib.make_reverse()

    assert clockwise1.compare_to(clockwise2) == 0
    assert clockwise2.compare_to(clockwise1) == 0

    assert reverse1.compare_to(reverse2) == 0
    assert reverse2.compare_to(reverse1) == 0

    assert reverse1.compare_to(clockwise1) != 0
    assert clockwise1.compare_to(reverse1) != 0
    assert reverse1.compare_to(clockwise1) == -clockwise1.compare_to(reverse1)
예제 #5
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()
예제 #6
0
    def create(self):
        winprops = WindowProperties.size(self.size, self.size)
        props = FrameBufferProperties()
        props.setRgbColor(0)
        props.setAlphaBits(0)
        props.setDepthBits(1)
        self.buffer = base.graphicsEngine.makeOutput(
            base.pipe, "shadowsBuffer", -2, props, winprops,
            GraphicsPipe.BFRefuseWindow, base.win.getGsg(), base.win)

        if not self.buffer:
            print("Video driver cannot create an offscreen buffer.")
            return
        self.depthmap = Texture()
        self.buffer.addRenderTexture(self.depthmap,
                                     GraphicsOutput.RTMBindOrCopy,
                                     GraphicsOutput.RTPDepthStencil)

        self.depthmap.setMinfilter(Texture.FTShadow)
        self.depthmap.setMagfilter(Texture.FTShadow)
        self.depthmap.setBorderColor(LColor(1, 1, 1, 1))
        self.depthmap.setWrapU(Texture.WMBorderColor)
        self.depthmap.setWrapV(Texture.WMBorderColor)

        self.cam = base.makeCamera(self.buffer, lens=OrthographicLens())
        self.cam.reparent_to(render)
        self.node = self.cam.node()
        lci = NodePath(PandaNode("Light Camera Initializer"))
        lci.set_attrib(ColorWriteAttrib.make(ColorWriteAttrib.M_none), 1000)
        lci.set_attrib(
            CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise), 1000)
        self.node.setInitialState(lci.getState())
        self.node.setScene(render)
        if settings.debug_shadow_frustum:
            self.node.showFrustum()
예제 #7
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
예제 #8
0
파일: model.py 프로젝트: svfgit/solex
    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
예제 #9
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))
예제 #10
0
    def __init__(self,
                 parent,
                 file_name,
                 file_type,
                 num_frames,
                 int_padding=1,
                 scale=(1, 1, 1),
                 fps=60,
                 pos=(0, 0, 0),
                 auto_gc=True):
        self.textures = self.loadTextureMovie(num_frames, file_name, file_type,
                                              int_padding)
        self.plane = base.loader.loadModel('assets/models/plane')
        self.plane.setPos(pos[0], pos[1], pos[2])  #set its position
        self.plane.setScale(scale[0], scale[1], scale[2])
        self.plane.reparentTo(parent)  #reparent to render
        self.plane.setTransparency(1)
        self.fps = fps
        self.animation_task = None
        self.plane.node().setEffect(BillboardEffect.makePointEye())
        self.currentLoop = 0
        self.lastFrame = 0
        self.trash = False
        self.auto_gc = auto_gc

        if base.displayFlipped:
            self.plane.setAttrib(
                CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))

        #dlight = DirectionalLight('my dlight')
        #dlnp = render.attachNewNode(dlight)
        #self.plane.setLight(dlnp)
        #dlnp.lookAt(self.plane)
        base.sprites.append(self)
예제 #11
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))
예제 #12
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)
예제 #13
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())
예제 #14
0
파일: demo.py 프로젝트: loonaticx/sketches
 def toggleFrontfaceCulling(self):
     if not self.frontfaceCullingEnabled:
         render.setAttrib(
             CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
         self.frontfaceCullingEnabled = True
     else:
         render.clearAttrib(CullFaceAttrib)
         self.frontfaceCullingEnabled = False
예제 #15
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())
예제 #16
0
def DoubleSidedNoZ():
    global _DoubleSidedNoZ
    if not _DoubleSidedNoZ:
        _DoubleSidedNoZ = RenderState.make(
            CullFaceAttrib.make(CullFaceAttrib.MCullNone),
            DepthTestAttrib.make(DepthTestAttrib.MOff),
            DepthWriteAttrib.make(DepthWriteAttrib.MOff),
            CullBinAttrib.make("fixed", LEGlobals.WidgetSort))
    return _DoubleSidedNoZ
예제 #17
0
 def update_instance(self, camera_pos, orientation):
     radius = self.parent.get_apparent_radius() + self.height
     inside = self.parent.distance_to_obs < radius
     if self.inside != inside:
         if inside:
             self.instance.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
             if not settings.use_inverse_z:
                 self.instance.setAttrib(DepthOffsetAttrib.make(0))
             if self.appearance.transparency:
                 self.instance.set_depth_write(True)
         else:
             self.instance.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullClockwise))
             if not settings.use_inverse_z:
                 self.instance.setAttrib(DepthOffsetAttrib.make(1))
             if self.appearance.transparency:
                 self.instance.set_depth_write(False)
         self.inside = inside
     return FlatSurface.update_instance(self, camera_pos, orientation)
예제 #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")

        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)
예제 #19
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
예제 #20
0
def DashedLineNoZ():
    global _DashedLineNoZ
    if not _DashedLineNoZ:
        shattr = getStippleShader()
        _DashedLineNoZ = RenderState.make(
            shattr,
            DepthTestAttrib.make(DepthTestAttrib.MOff),
            DepthWriteAttrib.make(DepthWriteAttrib.MOff),
            CullFaceAttrib.make(CullFaceAttrib.MCullNone),
        )
        _DashedLineNoZ = _DashedLineNoZ.setAttrib(CullBinAttrib.make("fixed", LEGlobals.BoxSort))
    return _DashedLineNoZ
예제 #21
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)
                '''
예제 #22
0
 def customize(nodePath):
     volume = nodePath.find("light_volume")
     volume.setTransparency(True)
     volume.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullNone))
     volume.setDepthWrite(False)
     volume.setAttrib(
         ColorBlendAttrib.make(ColorBlendAttrib.M_add,
                               ColorBlendAttrib.OIncomingAlpha,
                               ColorBlendAttrib.O_one))
     volume.setShader(
         Shader.load(Shader.SL_GLSL,
                     vertex=Filename("shaders/streetlight.vert"),
                     fragment=Filename("shaders/streetlight.frag")))
예제 #23
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)
             
             '''
예제 #24
0
    def create_instance(self):
        self.shape.set_radius(self.radius)
        ShapeObject.create_instance(self)
        self.instance.setTransparency(TransparencyAttrib.MAlpha)
        blendAttrib = ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                            ColorBlendAttrib.OOne,
                                            self.alpha_mode)
        self.instance.setAttrib(blendAttrib)
        self.instance.setAttrib(
            CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
        self.instance.set_depth_write(False)

        def create_scattering_shader(self, atmosphere, calc_in_fragment):
            return None
예제 #25
0
    def attach_hidden_area_mesh(self, eye, anchor, camera_mask):
        """
        Create and attach the two meshes that will hide the areas not visible from the HMD.
        """

        left_eye_mask = self.vr_system.getHiddenAreaMesh(
            eye, type_=openvr.k_eHiddenAreaMesh_Standard)
        left_mesh = self.create_hidden_area_mesh(left_eye_mask)
        np = anchor.attach_new_node(left_mesh)
        # The winding order is not specified, it is recommended to disable backface culling
        np.set_attrib(CullFaceAttrib.make(CullFaceAttrib.M_cull_none))
        np.set_shader(self.get_ham_shader(), 10000)
        # Make sure that the mesh is rendered first to allow early-z optimization
        np.set_bin("background", 0)
        # Hide this mesh from the opposite camera
        np.hide(BitMask32.bit(camera_mask))
예제 #26
0
def load_model(name, path=application.asset_folder):
    if name in imported_meshes:
        # print('load cached model', name)
        try:
            return copy(imported_meshes[name])
        except:
            pass

    for filetype in ('.bam', '.ursinamesh', '.obj', '.blend'):
        # warning: glob is case-insensitive on windows, so m.path will be all lowercase
        for filename in path.glob(f'**/{name}{filetype}'):
            if filetype in '.bam':
                print('loading bam')
                return loader.loadModel(filename)

            if filetype == '.ursinamesh':
                try:
                    with open(filename) as f:
                        m = eval(f.read())
                        m.path = filename
                        m.name = name
                        imported_meshes[name] = m
                        return m
                except:
                    print('invalid ursinamesh file:', filename)


            if filetype == '.obj':
                print('found obj', filename)
                m = loader.loadModel(filename)
                m.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
                # m = obj_to_ursinamesh(path=path, name=name, save_to_file=False)
                # m = eval(m)
                # m.path = filename
                # m.name = name
                imported_meshes[name] = m
                return m

            elif filetype == '.blend':
                print('found blend file:', filename)
                if compress_models(path=path, name=name):
                    # obj_to_ursinamesh(name=name)
                    return load_model(name, path)

            # else:

    return None
예제 #27
0
    def _createVoxelizeState(self):
        """ Creates the tag state and loades the voxelizer shader """
        self.voxelizeShader = BetterShader.load("Shader/GI/Voxelize.vertex",
                                                "Shader/GI/Voxelize.fragment"
                                                # "Shader/GI/Voxelize.geometry"
                                                )

        initialState = NodePath("VoxelizerState")
        initialState.setShader(self.voxelizeShader, 50)
        initialState.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullNone))
        initialState.setDepthWrite(False)
        initialState.setDepthTest(False)
        initialState.setAttrib(DepthTestAttrib.make(DepthTestAttrib.MNone))

        initialState.setShaderInput("dv_dest_tex", self.voxelGenTex)

        self.voxelizeCamera.setTagState("Default", initialState.getState())
예제 #28
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]
예제 #29
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
예제 #30
0
    def __init__(self, base, name, pos=None, color=None, show_model=False):
        PointLight.__init__(self, name)
        self.base = base
        self.node = self.base.render.attachNewNode(self)
        self.set_pos(pos)
        self.base.render.setLight(self.node)
        self.set_color(color if color is not None else (1, 1, 1, 1))
        self.set_max_distance(0.3)
        self.set_attenuation((1, 0, 0.2))

        self.show_model = show_model

        if show_model:
            self.model = self.base.loader.load_model("data/models/sphere.bam")
            self.model.setAttrib(
                CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
            self.model.set_scale(0.05)
            self.model.set_color(color if color is not None else (1, 1, 1, 1))
            self.model.setLightOff()
            self.model.set_bin("fixed", 10)
            self.model.reparentTo(self.node)
예제 #31
0
    def __init__(self, base, name, pos=None, color=None, show_model=True):
        PointLight.__init__(self, name)
        self.period = 1
        self.signal = 0.1
        self.base = base
        self.show_model = show_model

        self.base.taskMgr.add(self.flash, "Flash")
        self.node = self.base.render.attachNewNode(self)
        self.node.hide()
        self.setAttenuation((1, 0, 0.2))

        self.set_pos(pos)
        if show_model:
            print('showing model')
            self.model = self.base.loader.load_model("data/models/sphere.bam")
            self.model.setAttrib(
                CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
            self.model.set_scale(1)
            self.model.setLightOff()
            self.model.reparentTo(self.node)

        self.set_global_color(color)
예제 #32
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
예제 #33
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)
예제 #34
0
def pleaseMakeTransparent(nodePath):
    nodePath.setTransparency(True)
    nodePath.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullNone))
    nodePath.setDepthWrite(False)
    nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))
예제 #35
0
 def create_instance(self):
     self.shape.set_radius(self.radius)
     ShapeObject.create_instance(self)
     TransparencyBlend.apply(self.blend, self.instance)
     self.instance.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
     self.instance.set_depth_write(False)
예제 #36
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
예제 #37
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)
예제 #38
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
예제 #39
0
    Off = 0
    Drawing = 1
    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
예제 #40
0
    def apply(self, nodePath):
        if self.mode == M_cull_all:
            raise Exception('All polygons are culled in this mode...')

        attrib = CullFaceAttrib.make(self.mode)
        nodePath.setAttrib(attrib)
예제 #41
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)
예제 #42
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()