def update_scene(self, scene_graph, materials_only): """Update a scene using scene_graph description Arguments: scene_graph {SceneGraph} -- scene description materials_only {bool} -- update only shape materials """ for k, v in scene_graph.nodes.items(): node = self.render.attachNewNode(f'node_{k:02d}') self.nodes[k] = node for shape in v.shapes: # load model if shape.type == ShapeType.Mesh: model = self.loader.load_model(shape.mesh.filename) else: mesh = Mesh.from_trimesh(primitive_mesh(shape)) model = node.attach_new_node(mesh) if shape.material is not None: # set material material = Material() material.setAmbient(Vec4(*shape.material.diffuse_color)) material.setDiffuse(Vec4(*shape.material.diffuse_color)) material.setSpecular(Vec3(*shape.material.specular_color)) material.setShininess(5.0) model.setMaterial(material, 1) # set relative position model.reparentTo(node) model.setPos(*shape.pose.origin) model.setQuat(Quat(*shape.pose.quat)) model.setScale(*shape.pose.scale)
def __set_material(self, nodePath): mat = Material() mat.setAmbient((.35, .35, .35, .5)) mat.setDiffuse((.35, .35, .35, .5)) mat.setSpecular((.35, .35, .35, .5)) mat.setShininess(12.5) nodePath.set_material(mat, 1)
def set_material(self, root_path, name, color=None, texture_path=''): """Override material of a node. Arguments: root_path {str} -- path to the group's root node name {str} -- node name within a group color {Vec4} -- color RGBA Keyword Arguments: texture {str | np.ndarray} -- path to the texture file on disk (default: {None}) """ node = self._groups[root_path].find(name) if color is not None: node.set_color(Vec4(*color)) material = Material() material.set_ambient(Vec4(*color)) material.set_diffuse(Vec4(*color)) material.set_specular(Vec3(1, 1, 1)) material.set_roughness(0.4) node.set_material(material, 1) if color[3] < 1: node.set_transparency(TransparencyAttrib.M_alpha) if texture_path: texture = self.loader.load_texture(texture_path) node.set_texture(texture)
class GasGiant(ProceduralGasGiant): def init(self, scale=1, debug=False): self.node_path = shapeGeneratorAdvanced.GasIcoSphere(1, 5) # create sane material defaults self.material = Material() self.material.set_diffuse(VBase4(0.13)) self.material.set_ambient(VBase4(0.0)) self.material.set_emission(VBase4(0.0)) self.material.set_shininess(0.0) self.material.set_specular(VBase4(0.01)) self.node_path.set_material(self.material) def load_shaders(self): shaders = Shader.load(Shader.SL_GLSL, 'gas_giant_vertex.glsl', 'gas_giant_fragment.glsl', '', "Shader/DefaultShaders/Opaque/tesscontrol.glsl", "Shader/DefaultShaders/Opaque/tesseval.glsl") shaders = Shader.load(Shader.SL_GLSL, 'gas_giant_vertex.glsl', 'gas_giant_fragment.glsl') #convertToPatches(self.node_path) self.node_path.set_shader(shaders, 51) def load_texture_special(self): diffuse = base.loader.loadTexture('saturn_color.png') self.node_path.set_texture(diffuse)
def __init__(self): ShowBase.__init__(self) self.camera.setPos(0, 0, 3) self.fm = FlyMove(self) self.scene = self.loader.loadModel('models/environment') self.disable_mouse() self.scene.reparentTo(self.render) self.scene.setScale(0.25, 0.25, 0.25) self.scene.setPos(-8, 42, 0) pandaMat = Material() pandaMat.setEmission((1, 0.4, 0, 1)) colour = (0.5, 0.8, 0.8) expfog = Fog("Scene-wide exponential Fog object") expfog.setColor(*colour) expfog.setExpDensity(0.005) self.render.setFog(expfog) self.pandaActor = Actor('models/panda-model', {'walk': 'models/panda-walk4'}) self.pandaActor.set_material(pandaMat) self.pandaActor.setScale(0.005, 0.005, 0.005) self.pandaActor.loop('walk') line = NodePath('pandaline') for i in range(50): placeholder = line.attachNewNode('line-panda') placeholder.setPos(i * 2, 0, 0) self.pandaActor.instanceTo(placeholder) line.reparentTo(self.render) pandaPosIntervalInterval1 = self.pandaActor.posInterval( 13, Point3(0, -10, 0), startPos=Point3(0, 10, 0)) pandaPosIntervalInterval2 = self.pandaActor.posInterval( 13, Point3(0, 10, 0), startPos=Point3(0, -10, 0)) pandaHprIntervalInterval1 = self.pandaActor.hprInterval( 2, Point3(180, 0, 0), startHpr=Point3(0, 0, 0)) pandaHprIntervalInterval2 = self.pandaActor.hprInterval( 2, Point3(0, 0, 0), startHpr=Point3(180, 0, 0)) self.pandaPace = Sequence(pandaPosIntervalInterval1, pandaHprIntervalInterval1, pandaPosIntervalInterval2, pandaHprIntervalInterval2) self.pandaPace.loop() light = DirectionalLight('pl') light.set_color_temperature(2000) np = self.render.attachNewNode(light) np.set_pos(0, 0, 5) light.set_shadow_caster(True, 512, 512) self.render.setLight(np) # np.place() alight = AmbientLight('alight') alight.setColor(VBase4(0.3, 0.1, 0.1, 1)) alnp = self.render.attachNewNode(alight) self.render.setLight(alnp)
def load_3D_Model(self, position, hpr, color, metalic=False, scale=0.005, id=None, name=None, filename=None, parent=None, shininess=None, specular=None, texture=None): if parent is None: parent = render if name: filename = 'egg/%s_%s' % (self.device_id, name) model = loader.loadModel('%s/%s' % (self.layout_dir, filename)) if (id): container = parent.attachNewNode(id) model.reparentTo(container) else: model.reparentTo(parent) if texture: tex_node = loader.loadTexture(texture) model.setTexture(tex_node, 1) else: model.setColor(color) model.setPosHpr(position[0], position[1], position[2], hpr[0], hpr[1], hpr[2]) model.setScale(float(scale)) if metalic: m = Material() m.setShininess(shininess) m.setSpecular(specular) model.setMaterial(m) if id: self.nodes_by_id[id] = model return model
def _make_floor(self): model = GeomNode('floor') model.add_geom(geometry.make_plane(size=(10, 10))) node = self.render.attach_new_node(model) node.set_color(Vec4(0.3, 0.3, 0.3, 1)) material = Material() material.set_ambient(Vec4(0, 0, 0, 1)) material.set_diffuse(Vec4(0.3, 0.3, 0.3, 1)) material.set_specular(Vec3(1, 1, 1)) material.set_roughness(0.8) node.set_material(material, 1) return node
def makeGround(self, parent): ground = self.base.loader.loadModel("cube") ground.setScale(20, 5, .2) ground.setPos(0, 0, -.2) ground.setColor(VBase4(.33,.42,.55,1))#*colorsys.hsv_to_rgb(.6, .4, .55)) ground.reparentTo(parent) m = Material("gnd") m.setDiffuse(VBase4(1,1,1,1)) #ground.setMaterial(m) return ground
def makeGround(self, parent): ground = self.base.loader.loadModel("cube") ground.setScale(20, 5, .2) ground.setPos(0, 0, -.2) ground.setColor(VBase4(.33, .42, .55, 1)) #*colorsys.hsv_to_rgb(.6, .4, .55)) ground.reparentTo(parent) m = Material("gnd") m.setDiffuse(VBase4(1, 1, 1, 1)) #ground.setMaterial(m) return ground
def defaultMaterial(): material = Material() material.setShininess(0.0) material.setAmbient((0.2, 0, 0, 1)) rand = random.uniform(0, 1) material.setDiffuse((rand, rand, rand, 1)) return material
def bake(self): self.material = Material() if self.emissionColor != None: self.material.setEmission(self.emissionColor) if self.diffuseColor != None: self.material.setDiffuse(self.diffuseColor) if self.ambientColor != None: self.material.setAmbient(self.ambientColor) if self.specularColor != None: self.material.setSpecular(self.specularColor) if self.shininess != None: self.material.setShininess(self.shininess) self.check_specular_mask() self.calc_indexes()
def make_star(name='star', scale=1, color=Vec3(1), texture_size=64, debug=False): card_maker = CardMaker(name) card_maker.set_frame(-1, 1, -1, 1) node_path = NodePath(name) node = card_maker.generate() final_node_path = node_path.attach_new_node(node) final_node_path.set_billboard_point_eye() from panda3d.core import Filename shaders = Shader.load(Shader.SL_GLSL, Filename('Shader/Star/vertex.glsl'), Filename('Shader/Star/fragment.glsl'), Filename(''), Filename(''), Filename('')) if not shaders: print("WARNING. STAR SHADER FAILED TO LOAD", type(shaders)) else: final_node_path.set_shader_input('cameraSpherePos', 1, 1, 1) final_node_path.set_shader_input('sphereRadius', 1.0) final_node_path.set_shader_input('myCamera', base.camera) final_node_path.set_shader(shaders) final_node_path.set_shader_input('blackbody', color) material = Material() material.set_emission(VBase4(color, 1.0)) final_node_path.set_material(material) xn = PerlinNoise3(0.5, 0.5, 0.5) #yn = PerlinNoise3(0.5, 0.5, 0.5) texture = Texture('star') texture.setup_3d_texture() for z in range(texture_size): p = PNMImage(texture_size, texture_size) for y in range(texture_size): for x in range(texture_size): p.set_gray(x, y, abs(xn.noise(x, y, z))) texture.load(p, z, 0) diffuse = texture diffuse.setMinfilter(Texture.FTLinearMipmapLinear) diffuse.setAnisotropicDegree(4) final_node_path.set_texture(diffuse) normal = sandbox.base.loader.loadTexture('data/empty_textures/empty_normal.png') normalts = TextureStage('normalts') final_node_path.set_texture(normalts, normal) specular = sandbox.base.loader.loadTexture('data/empty_textures/empty_specular.png') spects = TextureStage('spects') final_node_path.set_texture(spects, specular) roughness = sandbox.base.loader.loadTexture('data/empty_textures/empty_roughness.png') roughts= TextureStage('roughts') final_node_path.set_texture(roughts, roughness) return final_node_path
def load_water(self): """ Loads the islands psuedo infinite water plane """ # Create a material for the PBR shaders water_material = Material() water_material.set_base_color(VBase4(0, 0.7, 0.9, 1)) water_card_maker = CardMaker('water_card') water_card_maker.set_frame(-200, 200, -150, 150) self.water_path = self.render.attach_new_node( water_card_maker.generate()) self.water_path.set_material(water_material, 1) self.water_path.set_scale(500)
def __init__texture(self): """ Methode bei der die Textur initialisert wird """ self.texture = loader.loadModel("models/planet_sphere") self.texture.reparentTo(self.orbit) self.chooseTexture() self.texture.setPos(self.position[0], self.position[1], self.position[2]) self.texture.setScale(2.5 * self.scale, 2.5 * self.scale, 2.5 * self.scale) myMaterial = Material() myMaterial.setEmission((1, 1, 1, 1)) #Make this material shiny self.texture.setMaterial( myMaterial) #Apply the material to this nodePath
def __init__( self, filePath ): """ Initializes the object. The filePath argument represents the model to load for the sky geometry. """ self.sky = loader.loadModel( filePath ) mat = Material() #mat.setAmbient( VBase4( 1, 1, 1, 1 )) mat.setEmission( VBase4( 1, 1, 1, 1 )) self.sky.setMaterial( mat ) self.sky.setDepthWrite( False ) self.sky.setDepthTest( False ) self.sky.setBin( 'background', 0 ) self.sky.setEffect(CompassEffect.make(render)) self.sky.setLightOff() self.sky.reparentTo( base.cam ) self.sky.setShaderOff()
def __init__(self, filePath): """ Initializes the object. The filePath argument represents the model to load for the sky geometry. """ self.sky = loader.loadModel(filePath) mat = Material() #mat.setAmbient( VBase4( 1, 1, 1, 1 )) mat.setEmission(VBase4(1, 1, 1, 1)) self.sky.setMaterial(mat) self.sky.setDepthWrite(False) self.sky.setDepthTest(False) self.sky.setBin('background', 0) self.sky.setEffect(CompassEffect.make(render)) self.sky.setLightOff() self.sky.reparentTo(base.cam) self.sky.setShaderOff()
def __init__(self): self.root = render.attachNewNode("Root") base.setBackgroundColor(0,0,0) # This code puts the standard title and instruction text on screen self.title = OnscreenText(text="Ball In Maze", style=1, fg=(1,1,0,1), pos=(0.7,-0.95), scale = .07) self.instructions = OnscreenText(text="Press Esc to exit", pos = (-1.3, .95), fg=(1,1,0,1), align = TextNode.ALeft, scale = .05) self.central_msg = OnscreenText(text="", pos = (0, 0), fg=(1, 1, 0, 1), scale = .1 ) self.central_msg.hide() self.accept("escape", sys.exit) # Escape quits base.disableMouse() # Disable mouse-based camera control camera.setPosHpr(0, 0, 25, 0, -90, 0) # Place the camera # Load the maze and place it in the scene self.maze = loader.loadModel("models/maze") self.maze.reparentTo(render) # Load the ball and attach it to the scene # It is on a root dummy node so that we can rotate the ball itself without # rotating the ray that will be attached to it self.ballRoot = render.attachNewNode("ballRoot") self.ball = loader.loadModel("models/ball") self.ball.reparentTo(self.ballRoot) # This section deals with lighting for the ball. Only the ball was lit # because the maze has static lighting pregenerated by the modeler ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0, 0, -1)) directionalLight.setColor(Vec4(0.375, 0.375, 0.375, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) self.ballRoot.setLight(render.attachNewNode(ambientLight)) self.ballRoot.setLight(render.attachNewNode(directionalLight)) # This section deals with adding a specular highlight to the ball to make # it look shiny m = Material() m.setSpecular(Vec4(1,1,1,1)) m.setShininess(96) self.ball.setMaterial(m, 1)
def init(self): shaders = Shader.load(Shader.SLGLSL, 'planet_surface_vert.glsl', 'planet_surface_frag.glsl') self.node_path.setShader(shaders) tex = Texture() # create sane material defaults self.material = Material() self.material.set_ambient(VBase4(0.0, 0.0, 0.0, 0.0)) self.material.set_diffuse(VBase4(0.0, 0.0, 0.0, 0.0)) self.material.set_emission(VBase4(0.0, 0.0, 0.0, 0.0)) self.material.set_shininess(0) self.material.set_specular(VBase4(0.0, 0.0, 0.0, 0.0)) for m in self.sides: m.set_material(self.material) '''m.set_shader_input('colorTexture', tex)
def init(self, scale, debug): self.sides = [] for i in range(0, 6): m = create_side(self.node_path, debug, invert=True) m.set_scale(scale) self.sides.append(m) """The side meshes are rotated here. They are moved to their correct position in the shader.""" self.sides[0].set_hpr(90, 90, 0) self.sides[1].set_hpr(-90, 90, 0) self.sides[2].set_hpr(0, 0, 0) self.sides[3].set_hpr(0, 180, 0) self.sides[4].set_hpr(0, 90, 0) self.sides[5].set_hpr(180, 90, 0) # create sane material defaults self.material = Material() self.material.set_diffuse(VBase4(0.7)) self.material.set_ambient(VBase4(0.0)) self.material.set_emission(VBase4(0.0)) self.material.set_shininess(0.0) self.material.set_specular(VBase4(0.2, 0.0, 0.2, 0.0)) for m in self.sides: m.set_material(self.material) """m.set_shader_input('colorTexture', tex)
def __init__(self, world, attach, name = '', position = Vec3(0,0,0), orientation = Vec3(0,0,0), size = (32, 32)): cm=CardMaker('') cm.setFrame(0,1,0,1) floor = render.attachNewNode(PandaNode("floor")) tex = loader.loadTexture('media/'+'ground.png') tex.setMagfilter(Texture.FTNearest) tex.setMinfilter(Texture.FTNearest) for y in range(size[0]): for x in range(size[1]): nn = floor.attachNewNode(cm.generate()) nn.setP(-90) nn.setPos((x), (y), 0) floor.setTexture(tex) floor.flattenStrong() myMaterial = Material() myMaterial.setShininess(0) #Make this material shiny myMaterial.setAmbient(VBase4(0.5,.5,.5,1)) #Make this material blue myMaterial.setDiffuse(VBase4(.5,.5,.5,1)) nn.setMaterial(myMaterial) shape = BulletPlaneShape(Vec3(0, 0, 1), 0) StaticWorldObject.__init__(self, world, attach, name, position, shape, orientation) ##Mass must be zero. self._nodePath.node().setFriction(1)
def update_scene(self, scene_graph, materials_only): """Update a scene using scene_graph description Arguments: scene_graph {SceneGraph} -- scene description materials_only {bool} -- update only shape materials """ for k, v in scene_graph.nodes.items(): node = self.render.attachNewNode(f'node_{k:02d}') self.nodes[k] = node for j, shape in enumerate(v.shapes): if shape.type == ShapeType.Mesh: filename = shape.mesh.filename elif shape.type == ShapeType.Cube: filename = 'cube.obj' else: print('Unknown shape type: {}'.format(shape.type)) continue # load model model = self.loader.load_model(filename) if shape.has_material: # set material material = Material() material.setAmbient(Vec4(*shape.material.diffuse_color)) material.setDiffuse(Vec4(*shape.material.diffuse_color)) material.setSpecular(Vec3(*shape.material.specular_color)) material.setShininess(5.0) model.setMaterial(material, 1) # set texture if shape.material.diffuse_texture > -1: tex = scene_graph.texture( shape.material.diffuse_texture) model.setTexture(tex.filename) # set relative position pose = shape.pose model.reparentTo(node) model.setPos(*shape.pose.origin) model.setQuat(Quat(*shape.pose.quat)) model.setScale(*shape.pose.scale)
def apply_instance(self, instance): if instance != self.instance: if self.instance is not None: self.instance.remove_node() self.instance = instance self.shape.set_clickable(self.clickable) self.shape.apply_owner() self.instance.reparentTo(self.context.world) if self.parent.is_emissive(): #TODO: Should be done by the owner of the shape myMaterial = Material() myMaterial.setEmission((1, 1, 1, 1)) self.instance.setMaterial(myMaterial, 1) if self.appearance is not None: #TODO: should be done somewhere else self.appearance.bake() self.instance.node().setBounds(OmniBoundingVolume()) self.instance.node().setFinal(True) self.schedule_jobs()
def init(self, scale=1, debug=False): self.node_path = shapeGeneratorAdvanced.GasIcoSphere(1, 5) # create sane material defaults self.material = Material() self.material.set_diffuse(VBase4(0.13)) self.material.set_ambient(VBase4(0.0)) self.material.set_emission(VBase4(0.0)) self.material.set_shininess(0.0) self.material.set_specular(VBase4(0.01)) self.node_path.set_material(self.material)
def make_star(name='star', scale=1, color=Vec3(1), texture_size=64, debug=False): card_maker = CardMaker(name) card_maker.set_frame(-1, 1, -1, 1) node_path = NodePath(name) node = card_maker.generate() final_node_path = node_path.attach_new_node(node) final_node_path.set_billboard_point_eye() shaders = Shader.load(Shader.SLGLSL, 'Shader/Star/vertex.glsl', 'Shader/Star/fragment.glsl') final_node_path.set_shader_input(b'cameraSpherePos', 1, 1, 1) final_node_path.set_shader_input(b'sphereRadius', 1.0) final_node_path.set_shader_input(b'myCamera', base.camera) final_node_path.set_shader(shaders) final_node_path.set_shader_input(b'blackbody', color) material = Material() material.set_emission(VBase4(color, 1.0)) final_node_path.set_material(material) xn = PerlinNoise3(0.5, 0.5, 0.5) #yn = PerlinNoise3(0.5, 0.5, 0.5) texture = Texture('star') texture.setup_3d_texture() for z in range(texture_size): p = PNMImage(texture_size, texture_size) for y in range(texture_size): for x in range(texture_size): p.set_gray(x, y, abs(xn.noise(x, y, z))) texture.load(p, z, 0) diffuse = texture diffuse.setMinfilter(Texture.FTLinearMipmapLinear) diffuse.setAnisotropicDegree(4) final_node_path.set_texture(diffuse) normal = base.loader.loadTexture('Data/Textures/EmptyNormalTexture.png') normalts = TextureStage('normalts') final_node_path.set_texture(normalts, normal) specular = base.loader.loadTexture('Data/Textures/EmptySpecularTexture.png') spects = TextureStage('spects') final_node_path.set_texture(spects, specular) roughness = base.loader.loadTexture('Data/Textures/EmptyRoughnessTexture.png') roughts= TextureStage('roughts') final_node_path.set_texture(roughts, roughness) return final_node_path
class Ring(Body): """Ring system. Parent to parent planet.""" def __init__(self, name, scale=1, debug=False, outer_radius=3.0, inner_radius=1.15): """Debug will generate colored pixels for fun time. self.init() is called for specific body type inits.""" self.name = name self.node_path = NodePath(name) base.accept('h', self.node_path.hide) base.accept('j', self.node_path.show) self.init(scale=scale, debug=debug, outer_radius=outer_radius, inner_radius=inner_radius) def init(self, scale=1, debug=False, outer_radius=3.0, inner_radius=1.15): # http://johnwhigham.blogspot.com/2011/11/planetary-rings.html # Px shader use to clip to make smooth. Must extend outer radius for this numSides = 16.0 vert_radius = outer_radius/math.cos(math.pi/numSides) print("Vert radius:", vert_radius) self.node_path = shapeGenerator.Circle(outer_radius=vert_radius, inner_radius=inner_radius) #self.node_path.set_transparency(TransparencyAttrib.MBinary, 1) # create sane material defaults self.material = Material() self.material.set_diffuse(VBase4(0.7)) self.material.set_ambient(VBase4(0.0)) self.material.set_emission(VBase4(0.0)) self.material.set_shininess(0.0) self.material.set_specular(VBase4(0.224, 0.0, 0.5, 0)) self.node_path.set_material(self.material) self.node_path.setTwoSided(True) def load_shaders(self): #shaders = Shader.load(Shader.SL_GLSL, # 'ring_vertex.glsl', # 'ring_fragment.glsl') #self.node_path.set_shader(shaders, 51) pass def load_texture_special(self): diffuse = base.loader.loadTexture('ring_color.png', 'ring_alpha.png') #Dust rings alpha might be needed diffuse.setAnisotropicDegree(2) diffuse.setMinfilter(Texture.FTLinearMipmapLinear) self.node_path.set_texture(diffuse)
def basic_point_light(self, position, color, name, attenuation=(1, 0, 0.02)): light = PointLight(name) light.setColor(color) light.setAttenuation(attenuation) # light.setShadowCaster(True) # light.getLens().setNearFar(5, 20) plight = self.centerlight_np.attachNewNode(light) plight.setPos(position) self.render.setLight(plight) light_cube = self.loader.loadModel("cuby.gltf") light_cube.reparentTo(plight) light_cube.setScale(0.25) material = Material() material.setEmission(color) light_cube.setMaterial(material)
def __init__(self,name,size,mass): GameObject.__init__(self,name) super(AnimatableObject,self).__initToBox__(name,size,mass,False) # initialize game object to a box with no Visual self.setTransparency(TransparencyAttrib.M_alpha) self.node().setAngularFactor((0,0,0)) # no rotation self.animation_root_np_ = self.attachNewNode('animations_root') self.animation_root_np_.setPos(Vec3(0,0,-0.5*size.getZ())) self.animators_ = {} self.selected_animation_name_ = '' self.animator_np_ = None # selected animator NodePath self.animator_ = None # make sprites brigntess consistent material = Material(name + 'animation-material') material.setEmission(LColor(1,1,1,1)) self.animation_root_np_.setMaterial(material) # callbacks self.frame_monitor_seq_ = Sequence() # Used to monitor animation frames and invoke callbacks self.animation_end_cb_ = None self.animation_start_cb_ = None
def load_sphere(self, position, directionalLight, ambientLight, color): # Load a sphere. pos = position self.sphere = self.loader.loadModel("ball") self.sphere.setScale(self.SPHERE_SIZE, self.SPHERE_SIZE, self.SPHERE_SIZE) self.sphere.setPos(pos) # Sets the sphere color. self.sphere.setColor(color) self.sphere.reparentTo(render) # Make the sphere a material (to behave with the light). material = Material() material.setShininess(10.0) self.sphere.setMaterial(material) # Set lighting on the sphere. self.sphere.setLight(self.sphere.attachNewNode(directionalLight)) self.sphere.setLight(self.sphere.attachNewNode(ambientLight))
def updateSphero(self, node, pos, u, L, diameter): node.set_shader_input("L", L) node.set_shader_input("diameter", diameter) node.setPos(pos) # Theta is the amount to rotate about x, the 'roll' roll = math.acos(u[2]) * 180 / math.pi # Determine amount to rotate about z ('yaw' or 'heading') length_xy = math.sqrt(u[0]*u[0] + u[1]*u[1]) if length_xy > 0.0: yaw = math.acos(u[0] / length_xy) * 180 / math.pi if u[1] < 0.0: yaw = 360 - yaw else: yaw = 0.0 # Apply transforms (heading/yaw, pitch, roll) node.setHpr(yaw, 0.0, roll) # Make a diffuse material to color our spherocylinder myMaterial = Material() myMaterial.setAmbient((0.0, 0.0, 0.0, 0.0)) myMaterial.setDiffuse(self.spheroColor) node.setMaterial(myMaterial)
def levelLoaded(self): if self.level == 'TT_maze': for model in self.models: if model.getName() == 'maze': brightenMat = Material() brightenMat.setShininess(2.0) brightenMat.setEmission((0, 0.25, 0.16, 1)) walls = model.find('**/maze_walls') walls.setSz(1.5) walls.setBSPMaterial('phase_4/maps/DGhedge.mat', 1) walls.setMaterial(brightenMat) floor = model.find('**/maze_floor') floor.setBSPMaterial('phase_4/maps/grass.mat', 1) model.setShaderAuto() elif model.getName() == 'maze_collisions': model.hide() model.setTransparency(1) model.setColorScale(1, 1, 1, 0) for node in model.findAllMatches('**'): node.setSz(1.5) elif model.getName() == 'tag_arena_bg': model.find('**/g1').removeNode()
def __init__(self, loader, parentNodePath): w = loader.loadModel("plane") w.reparentTo(parentNodePath) size = 6 w.setPos(3.5, 15, size / 2 - 3) w.setColor(1, 0, 0) w.setHpr(0, 180, 0) w.setScale(size, 1, size / 1.33) w.setTwoSided(True) self.tx = Texture("video") self.tx.setup2dTexture(self.res, self.res, Texture.TUnsignedByte, Texture.FRgb8) # this makes some important setup call self.tx.load(PNMImage(self.res, self.res)) w.setTexture(self.tx) m = Material("vid") m.setTwoside(True) m.setEmission(VBase4(1, 1, 1, 1)) w.setMaterial(m) w.setFogOff()
def loadBall(self): self.ballRoot = render.attachNewNode("ballRoot") self.ball = load_model("ball") self.ball.reparentTo(self.ballRoot) self.ball_tex = load_tex("pokeball.png") self.ball.setTexture(self.ball_tex,1) self.ball.setScale(0.8) # Find the collision sphere for the ball in egg. self.ballSphere = self.ball.find("**/ball") self.ballSphere.node().setFromCollideMask(BitMask32.bit(0)) self.ballSphere.node().setIntoCollideMask(BitMask32.allOff()) #self.ballSphere.show() # Now we create a ray to cast down at the ball. self.ballGroundRay = CollisionRay() self.ballGroundRay.setOrigin(0,0,10) self.ballGroundRay.setDirection(0,0,-1) # Collision solids go in CollisionNode self.ballGroundCol = CollisionNode('groundRay') self.ballGroundCol.addSolid(self.ballGroundRay) self.ballGroundCol.setFromCollideMask(BitMask32.bit(1)) self.ballGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol) # light ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0,0,-1)) directionalLight.setColor(Vec4(0.375,0.375,0.375,1)) directionalLight.setSpecularColor(Vec4(1,1,1,1)) self.ballRoot.setLight(render.attachNewNode(ambientLight)) self.ballRoot.setLight(render.attachNewNode(directionalLight)) # material to the ball m = Material() m.setSpecular(Vec4(1,1,1,1)) m.setShininess(96) self.ball.setMaterial(m,1)
def create_material_COLOR(self, materialname, color): if panda3d is None: raise ImportError("Cannot locate Panda3D") currblock = self.blocks[-1] assert materialname not in currblock.materials mat = Material() mat.setAmbient(VBase4(color[0], color[1], color[2], 1)) mat.setDiffuse(VBase4(color[0], color[1], color[2], 1)) currblock.materials[materialname] = mat
def draw_spheres(self): # draw spheres self.spheres = [] for ball in self.box.particles: sphere = self.loader.loadModel("models/Sphere_HighPoly") # sphere = self.loader.loadModel("models/sphere") # model_radius = abs(sphere.getTightBounds()[0][0]) size1, size2 = sphere.getTightBounds() min_ = min(list(size1) + list(size2)) max_ = max(list(size1) + list(size2)) model_radius = (max_ - min_) / 2 # scale = ball.radius * 0.30 scale = ball.radius / model_radius color = [c / 255 for c in ball.color] color.append(1) sphere.setScale(scale, scale, scale) material = Material() material.setShininess(5) material.setAmbient(Vec4(*color)) material.setSpecular(Vec4(1, 1, 1, 1)) # transparent_color = color[:3] # transparent_color.append(0.1) # material.setDiffuse(Vec4(*transparent_color)) # material.setEmission(Vec4(*color)) sphere.setMaterial(material) sphere.setColor(*color) sphere.reparentTo(self.boxnode) position = ball.position if self.box.dimensions < 3: position = self._project3d(position) sphere.setPos(*position[:3]) if self.box.dimensions > 3: sphere.setTransparency(TransparencyAttrib.M_dual, 1) # if ball == self._dummy_ball: # sphere.setTransparency(TransparencyAttrib.M_dual, 1) # color = sphere.getColor() # color[3] = 0 # sphere.setColor(color) # sphere.setAntiAlias(8,1) ball.object = sphere # sphere.setColor(0, 100, 100, 10) self.spheres.append(sphere)
def __init__(self, loader, parentNodePath): w = loader.loadModel("plane") w.reparentTo(parentNodePath) size = 6 w.setPos(3.5, 15, size / 2 - 3) w.setColor(1,0,0) w.setHpr(0, 180, 0) w.setScale(size, 1, size / 1.33) w.setTwoSided(True) self.tx = Texture("video") self.tx.setup2dTexture(self.res, self.res, Texture.TUnsignedByte, Texture.FRgb8) # this makes some important setup call self.tx.load(PNMImage(self.res, self.res)) w.setTexture(self.tx) m = Material("vid") m.setTwoside(True) m.setEmission(VBase4(1,1,1,1)) w.setMaterial(m) w.setFogOff()
def init(self): shaders = Shader.load(Shader.SLGLSL, "planet_surface_vert.glsl", "planet_surface_frag.glsl") self.node_path.setShader(shaders) tex = Texture() # create sane material defaults self.material = Material() self.material.set_ambient(VBase4(0.0, 0.0, 0.0, 0.0)) self.material.set_diffuse(VBase4(0.0, 0.0, 0.0, 0.0)) self.material.set_emission(VBase4(0.0, 0.0, 0.0, 0.0)) self.material.set_shininess(0) self.material.set_specular(VBase4(0.0, 0.0, 0.0, 0.0)) for m in self.sides: m.set_material(self.material) """m.set_shader_input('colorTexture', tex)
def init(self, scale=1, debug=False, outer_radius=3.0, inner_radius=1.15): # http://johnwhigham.blogspot.com/2011/11/planetary-rings.html # Px shader use to clip to make smooth. Must extend outer radius for this numSides = 16.0 vert_radius = outer_radius/math.cos(math.pi/numSides) print("Vert radius:", vert_radius) self.node_path = shapeGenerator.Circle(outer_radius=vert_radius, inner_radius=inner_radius) #self.node_path.set_transparency(TransparencyAttrib.MBinary, 1) # create sane material defaults self.material = Material() self.material.set_diffuse(VBase4(0.7)) self.material.set_ambient(VBase4(0.0)) self.material.set_emission(VBase4(0.0)) self.material.set_shininess(0.0) self.material.set_specular(VBase4(0.224, 0.0, 0.5, 0)) self.node_path.set_material(self.material) self.node_path.setTwoSided(True)
def __init__(self): loadPrcFile("config/Config.prc") ShowBase.__init__(self) self.camera = self.makeCamera(self.win) #self.render.setAntialias(AntialiasAttrib.MMultisample) self.setBackgroundColor(0.0,0.0,0.0) #Mouse position text self.posText = OnscreenText(\ style=1, fg=(1,1,1,1), pos=(0.8,-0.95), scale = .07) #self.toggleWireframe() self._setupKeyboardEvents() # Load and transform the panda actor. self.render.setTransparency(TransparencyAttrib.MAlpha) self.tile1 = Tile("tile1",0.0,0.0) node1 = self.render.attachNewNode(self.tile1) self.tile2 = Tile("tile2",0.064,0.032) node2 = self.render.attachNewNode(self.tile2) texture = self.loader.loadTexture('artwork/sample.png') #node.setTwoSided(True) ts = TextureStage('ts') #ts.setMode(TextureStage.MNormal) node1.setTexture(ts, texture, 1) node2.setTexture(ts, texture, 1) myMaterial = Material() myMaterial.setShininess(0.0) #Make this material shiny myMaterial.setAmbient(VBase4(0.0,0.0,0.0,1)) #Make this material blue node1.setMaterial(myMaterial) node2.setMaterial(myMaterial) self.camera.setPos(0, 0, 2) self.camera.setHpr(0, -95, 0) plight = PointLight('plight') plight.setColor(VBase4(0.8, 0.8, 0.2, 1)) plnp = self.render.attachNewNode(plight) plnp.setPos(0.128, 0.064, -0.8) plight.setAttenuation(Point3(0.23, 0.23, 0.25)) self.render.setLight(plnp) self.alight = self.render.attachNewNode(AmbientLight("Ambient")) self.alight.node().setColor(Vec4(0.1, 0.1, 0.1, 1)) self.render.setLight(self.alight) self.render.setShaderAuto()
def __init__(self): self.root = render.attachNewNode("Root") base.setBackgroundColor(0, 0, 0) # This code puts the standard title and instruction text on screen self.title = OnscreenText(text="Ball In Maze", style=1, fg=(1, 1, 0, 1), pos=(0.7, -0.95), scale=.07) self.instructions = OnscreenText(text="Press Esc to exit", pos=(-1.3, .95), fg=(1, 1, 0, 1), align=TextNode.ALeft, scale=.05) self.central_msg = OnscreenText(text="", pos=(0, 0), fg=(1, 1, 0, 1), scale=.1) self.central_msg.hide() self.accept("escape", sys.exit) # Escape quits base.disableMouse() # Disable mouse-based camera control camera.setPosHpr(0, 0, 25, 0, -90, 0) # Place the camera # Load the maze and place it in the scene self.maze = loader.loadModel("models/maze") self.maze.reparentTo(render) # Load the ball and attach it to the scene # It is on a root dummy node so that we can rotate the ball itself without # rotating the ray that will be attached to it self.ballRoot = render.attachNewNode("ballRoot") self.ball = loader.loadModel("models/ball") self.ball.reparentTo(self.ballRoot) # This section deals with lighting for the ball. Only the ball was lit # because the maze has static lighting pregenerated by the modeler ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0, 0, -1)) directionalLight.setColor(Vec4(0.375, 0.375, 0.375, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) self.ballRoot.setLight(render.attachNewNode(ambientLight)) self.ballRoot.setLight(render.attachNewNode(directionalLight)) # This section deals with adding a specular highlight to the ball to make # it look shiny m = Material() m.setSpecular(Vec4(1, 1, 1, 1)) m.setShininess(96) self.ball.setMaterial(m, 1)
def __init__(self): # This code puts the standard title and instruction text on screen self.title = OnscreenText(text="Ball in Maze", style=1, fg=(1, 1, 1, 1), pos=(0.7, -0.95), scale=.07) self.instructions = OnscreenText(text="Press Esc to exit.", pos=(-1.3, .95), fg=(1, 1, 1, 1), align=TextNode.ALeft, scale=.05) base.setBackgroundColor(0, 0, 0) self.central_msg = OnscreenText(text="", pos=(0, 0), fg=(1, 1, 0, 1), scale=.1) self.central_msg.hide() self.accept("escape", sys.exit) # Escape quits base.disableMouse() # Disable mouse-based camera control camera.setPosHpr(0, 0, 25, 0, -90, 0) # Place the camera # Load the maze and place it in the scene self.maze = loader.loadModel("models/maze") self.maze.reparentTo(render) # Most times, you want collisions to be tested against invisible geometry # rather than every polygon. This is because testing against every polygon # in the scene is usually too slow. You can have simplified or approximate # geometry for the solids and still get good results. # # Sometimes you'll want to create and position your own collision solids in # code, but it's often easier to have them built automatically. This can be # done by adding special tags into an egg file. Check maze.egg and ball.egg # and look for lines starting with <Collide>. The part is brackets tells # Panda exactly what to do. Polyset means to use the polygons in that group # as solids, while Sphere tells panda to make a collision sphere around them # Keep means to keep the polygons in the group as visable geometry (good # for the ball, not for the triggers), and descend means to make sure that # the settings are applied to any subgroups. # # Once we have the collision tags in the models, we can get to them using # NodePath's find command # Find the collision node named wall_collide self.walls = self.maze.find("**/wall_collide") # Collision objects are sorted using BitMasks. BitMasks are ordinary numbers # with extra methods for working with them as binary bits. Every collision # solid has both a from mask and an into mask. Before Panda tests two # objects, it checks to make sure that the from and into collision masks # have at least one bit in common. That way things that shouldn't interact # won't. Normal model nodes have collision masks as well. By default they # are set to bit 20. If you want to collide against actual visable polygons, # set a from collide mask to include bit 20 # # For this example, we will make everything we want the ball to collide with # include bit 0 self.walls.node().setIntoCollideMask(BitMask32.bit(0)) # CollisionNodes are usually invisible but can be shown. Uncomment the next # line to see the collision walls # self.walls.show() # We will now find the triggers for the holes and set their masks to 0 as # well. We also set their names to make them easier to identify during # collisions self.loseTriggers = [] for i in range(6): trigger = self.maze.find("**/hole_collide" + str(i)) trigger.node().setIntoCollideMask(BitMask32.bit(0)) trigger.node().setName("loseTrigger") self.loseTriggers.append(trigger) # Uncomment this line to see the triggers # trigger.show() # Ground_collide is a single polygon on the same plane as the ground in the # maze. We will use a ray to collide with it so that we will know exactly # what height to put the ball at every frame. Since this is not something # that we want the ball itself to collide with, it has a different # bitmask. self.mazeGround = self.maze.find("**/ground_collide") self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1)) # Load the ball and attach it to the scene # It is on a root dummy node so that we can rotate the ball itself without # rotating the ray that will be attached to it self.ballRoot = render.attachNewNode("ballRoot") self.ball = loader.loadModel("models/ball") self.ball.reparentTo(self.ballRoot) # Find the collison sphere for the ball which was created in the egg file # Notice that it has a from collision mask of bit 0, and an into collison # mask of no bits. This means that the ball can only cause collisions, not # be collided into self.ballSphere = self.ball.find("**/ball") self.ballSphere.node().setFromCollideMask(BitMask32.bit(0)) self.ballSphere.node().setIntoCollideMask(BitMask32.allOff()) # No we create a ray to start above the ball and cast down. This is to # Determine the height the ball should be at and the angle the floor is # tilting. We could have used the sphere around the ball itself, but it # would not be as reliable self.ballGroundRay = CollisionRay() # Create the ray self.ballGroundRay.setOrigin(0, 0, 10) # Set its origin self.ballGroundRay.setDirection(0, 0, -1) # And its direction # Collision solids go in CollisionNode self.ballGroundCol = CollisionNode( 'groundRay') # Create and name the node self.ballGroundCol.addSolid(self.ballGroundRay) # Add the ray self.ballGroundCol.setFromCollideMask( BitMask32.bit(1)) # Set its bitmasks self.ballGroundCol.setIntoCollideMask(BitMask32.allOff()) # Attach the node to the ballRoot so that the ray is relative to the ball # (it will always be 10 feet over the ball and point down) self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol) # Uncomment this line to see the ray # self.ballGroundColNp.show() # Finally, we create a CollisionTraverser. CollisionTraversers are what # do the job of calculating collisions self.cTrav = CollisionTraverser() # Collision traverservs tell collision handlers about collisions, and then # the handler decides what to do with the information. We are using a # CollisionHandlerQueue, which simply creates a list of all of the # collisions in a given pass. There are more sophisticated handlers like # one that sends events and another that tries to keep collided objects # apart, but the results are often better with a simple queue self.cHandler = CollisionHandlerQueue() # Now we add the collision nodes that can create a collision to the # traverser. The traverser will compare these to all others nodes in the # scene. There is a limit of 32 CollisionNodes per traverser # We add the collider, and the handler to use as a pair self.cTrav.addCollider(self.ballSphere, self.cHandler) self.cTrav.addCollider(self.ballGroundColNp, self.cHandler) # Collision traversers have a built in tool to help visualize collisions. # Uncomment the next line to see it. # self.cTrav.showCollisions(render) # This section deals with lighting for the ball. Only the ball was lit # because the maze has static lighting pregenerated by the modeler ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0, 0, -1)) directionalLight.setColor(Vec4(0.375, 0.375, 0.375, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) self.ballRoot.setLight(render.attachNewNode(ambientLight)) self.ballRoot.setLight(render.attachNewNode(directionalLight)) # This section deals with adding a specular highlight to the ball to make # it look shiny m = Material() m.setSpecular(Vec4(1, 1, 1, 1)) m.setShininess(96) self.ball.setMaterial(m, 1) # Finally, we call start for more initialization self.start()
def __init__(self): # Setup window size, title and so on load_prc_file_data("", """ win-size 1600 900 window-title Render Pipeline - Lights demo """) # ------ Begin of render pipeline code ------ # Insert the pipeline path to the system path, this is required to be # able to import the pipeline classes pipeline_path = "../../" # Just a special case for my development setup, so I don't accidentally # commit a wrong path. You can remove this in your own programs. if not os.path.isfile(os.path.join(pipeline_path, "setup.py")): pipeline_path = "../../RenderPipeline/" sys.path.insert(0, pipeline_path) from rpcore import RenderPipeline, SpotLight self.render_pipeline = RenderPipeline() self.render_pipeline.create(self) # This is a helper class for better camera movement - its not really # a rendering element, but it included for convenience from rpcore.util.movement_controller import MovementController # ------ End of render pipeline code, thats it! ------ # Set time of day self.render_pipeline.daytime_mgr.time = "4:50" self.half_energy = 5000 self.lamp_fov = 70 self.lamp_radius = 10 # Load the scene model = loader.loadModel("scene/Scene.bam") model.reparent_to(render) # Animate balls, this is for testing the motion blur blend_type = "noBlend" np = model.find("**/MBRotate") np.hprInterval(1.5, Vec3(360, 360, 0), Vec3(0, 0, 0), blendType=blend_type).loop() np = model.find("**/MBUpDown") np_pos = np.get_pos() - Vec3(0, 0, 2) Sequence( np.posInterval(0.15, np_pos + Vec3(0, 0, 6), np_pos, blendType=blend_type), np.posInterval(0.15, np_pos, np_pos + Vec3(0, 0, 6), blendType=blend_type)).loop() np = model.find("**/MBFrontBack") np_pos = np.get_pos() - Vec3(0, 0, 2) Sequence( np.posInterval(0.15, np_pos + Vec3(0, 6, 0), np_pos, blendType=blend_type), np.posInterval(0.15, np_pos, np_pos + Vec3(0, 6, 0), blendType=blend_type)).loop() np = model.find("**/MBScale") Sequence( np.scaleInterval(0.2, Vec3(1.5), Vec3(1), blendType=blend_type), np.scaleInterval(0.2, Vec3(1), Vec3(1.5), blendType=blend_type)).loop() # Generate temperature lamps # This shows how to procedurally create lamps. In this case, we # base the lights positions on empties created in blender. self._lights = [] light_key = lambda light: int(light.get_name().split("LampLum")[-1]) lumlamps = sorted(model.find_all_matches("**/LampLum*"), key=light_key) for lumlamp in lumlamps: lum = float(lumlamp.get_name()[len("LampLum"):]) light = SpotLight() light.direction = (0, -1.5, -1) light.fov = self.lamp_fov light.set_color_from_temperature(lum * 1000.0) light.energy = self.half_energy light.pos = lumlamp.get_pos(self.render) light.radius = self.lamp_radius light.casts_shadows = False light.shadow_map_resolution = 256 self.render_pipeline.add_light(light) # Put Pandas on the edges if lumlamp in lumlamps[0:2] + lumlamps[-2:]: panda = loader.loadModel("panda") panda.reparent_to(render) panda_mat = Material("default") panda_mat.emission = 0 panda.set_material(panda_mat) panda.set_pos(light.pos) panda.set_z(0.65) panda.set_h(180 + randint(-60, 60)) panda.set_scale(0.2) panda.set_y(panda.get_y() - 3.0) self._lights.append(light) self.render_pipeline.prepare_scene(model) # Init movement controller self.controller = MovementController(self) self.controller.set_initial_position(Vec3(23.9, 42.5, 13.4), Vec3(23.8, 33.4, 10.8)) self.controller.setup() self.day_time = 0.3 self.time_direction = 0 # Keys to modify the time, disabled in the demo self.accept("k", self.reset) self.accept("p", self.set_time_direction, [1,]) self.accept("p-up", self.set_time_direction, [0,]) self.accept("i", self.set_time_direction, [-1,]) self.accept("i-up", self.set_time_direction, [0,]) self.addTask(self.update, "update")
class Surface(Body): """Planet is a parent nodepath that the 6 side mesh nodepaths will parent to. Planet can be moved, scale, and rotated with no problems""" def init(self, scale, debug): self.sides = [] for i in range(0, 6): m = create_side(self.node_path, debug, invert=True) m.set_scale(scale) self.sides.append(m) """The side meshes are rotated here. They are moved to their correct position in the shader.""" self.sides[0].set_hpr(90, 90, 0) self.sides[1].set_hpr(-90, 90, 0) self.sides[2].set_hpr(0, 0, 0) self.sides[3].set_hpr(0, 180, 0) self.sides[4].set_hpr(0, 90, 0) self.sides[5].set_hpr(180, 90, 0) # create sane material defaults self.material = Material() self.material.set_diffuse(VBase4(0.7)) self.material.set_ambient(VBase4(0.0)) self.material.set_emission(VBase4(0.0)) self.material.set_shininess(0.0) self.material.set_specular(VBase4(0.2, 0.0, 0.2, 0.0)) for m in self.sides: m.set_material(self.material) """m.set_shader_input('colorTexture', tex) m.set_shader_input('nightTesture', tex) m.set_shader_input('glossTexture', tex)""" def set_textures(self, texture_paths={}): """MultiTextures the surface. t_path is a string in the same format as loader.loadCubeMap('texture_#.png') for a multifile cubemap. The orientation is a little different than what is described in the panda manual. North pole is z-up.""" for i in range(0, 6): diffuse = base.loader.loadTexture(texture_paths["diffuse"].replace("#", str(i))) diffuse.setMinfilter(Texture.FTLinearMipmapLinear) diffuse.setAnisotropicDegree(4) self.sides[i].set_texture(diffuse) def set_ambient(self, r, g, b, a): self.material.set_ambient(VBase4(float(r), float(g), float(b), float(a))) def set_diffuse(self, r, g, b, a): self.material.set_diffuse(VBase4(float(r), float(g), float(b), float(a))) def set_specular(self, r, g, b, a): self.material.set_specular(VBase4(float(r), float(g), float(b), float(a))) def set_shininess(self, n): self.material.set_shininess(n)
class Appearance(AppearanceBase): JOB_TEXTURE_LOAD = 0x0001 def __init__(self, emissionColor=None, diffuseColor=None, ambientColor=None, specularColor=None, shininess=1.0, colorScale=None, transparency=False, transparency_level=0.0, transparency_blend=TransparencyBlend.TB_Alpha, texture=None, normalMap=None, specularMap=None, bumpMap=None, bump_height=10.0, emission_texture=None, tint=None, srgb=None): AppearanceBase.__init__(self) self.emissionColor = emissionColor self.diffuseColor = diffuseColor self.ambientColor = ambientColor self.specularColor = specularColor self.shininess = shininess self.colorScale = colorScale if srgb is None: srgb = settings.srgb self.srgb = srgb if texture is not None: self.set_texture(texture, tint, transparency, transparency_level, transparency_blend) if emission_texture is not None: self.set_emission_texture(emission_texture, tint) self.set_normal_map(normalMap) self.set_specular_map(specularMap) self.set_bump_map(bumpMap, bump_height) self.normal_map_tangent_space = True self.nb_textures_coord = 0 self.tex_transform = True self.has_material = True def set_roughness(self, roughness): self.roughness = roughness def set_nightscale(self, nightscale): self.nightscale = nightscale def set_backlit(self, backlit): self.backlit = backlit def check_specular_mask(self): if self.texture is not None and self.specularColor is not None: self.texture.check_specular_mask = True def check_transparency(self): if self.texture is not None: self.texture.check_transparency = True def bake(self): self.material = Material() if self.emissionColor != None: self.material.setEmission(self.emissionColor) if self.diffuseColor != None: self.material.setDiffuse(self.diffuseColor) if self.ambientColor != None: self.material.setAmbient(self.ambientColor) if self.specularColor != None: self.material.setSpecular(self.specularColor) if self.shininess != None: self.material.setShininess(self.shininess) self.check_specular_mask() self.calc_indexes() def set_texture(self, texture, tint=None, transparency=False, transparency_level=0.0, transparency_blend=TransparencyBlend.TB_Alpha, offset=0, context=defaultDirContext): if texture is not None and not isinstance(texture, TextureBase): if transparency: texture = TransparentTexture(AutoTextureSource( texture, None, context), tint, level=transparency_level, blend=transparency_blend, srgb=self.srgb) else: texture = SurfaceTexture(AutoTextureSource( texture, None, context), tint, srgb=self.srgb) self.texture = texture self.transparency = transparency self.transparency_level = transparency_level self.transparency_blend = transparency_blend self.tint = tint texture.set_offset(offset) def set_emission_texture(self, emission_texture, tint=None, context=defaultDirContext): if emission_texture is not None and not isinstance( emission_texture, TextureBase): emission_texture = EmissionTexture(AutoTextureSource( emission_texture, None, context), tint, srgb=self.srgb) self.emission_texture = emission_texture def set_normal_map(self, normal_map, context=defaultDirContext): if normal_map is not None and not isinstance(normal_map, TextureBase): normal_map = NormalMapTexture( AutoTextureSource(normal_map, None, context)) self.normal_map = normal_map def set_specular_map(self, specular_map, context=defaultDirContext): if specular_map is not None and not isinstance(specular_map, TextureBase): specular_map = SpecularMapTexture( AutoTextureSource(specular_map, None, context)) self.specular_map = specular_map def set_bump_map(self, bump_map, bump_height, context=defaultDirContext): if bump_map is not None and not isinstance(bump_map, TextureBase): bump_map = BumpMapTexture( AutoTextureSource(bump_map, None, context)) self.bump_map = bump_map self.bump_height = bump_height def set_occlusion_map(self, occlusion_map, context=defaultDirContext): if occlusion_map is not None and not isinstance( occlusion_map, TextureBase): occlusion_map = OcclusionMapTexture( AutoTextureSource(occlusion_map, None, context)) self.occlusion_map = occlusion_map def calc_indexes(self): self.nb_textures = 0 self.nb_textures_coord = 0 if self.texture is not None: self.texture_index = self.nb_textures self.nb_textures += 1 if self.normal_map is not None: self.normal_map_index = self.nb_textures self.nb_textures += 1 if self.bump_map is not None: self.bump_map_index = self.nb_textures self.nb_textures += 1 if self.specularColor is not None and self.specular_map is not None: self.specular_map_index = self.nb_textures self.nb_textures += 1 if self.emission_texture is not None: self.emission_texture_index = self.nb_textures self.nb_textures += 1 if self.occlusion_map is not None: self.occlusion_map_index = self.nb_textures self.nb_textures += 1 if self.nb_textures > 0: self.nb_textures_coord = 1 def get_recommended_shape(self): if self.texture is not None and self.texture.source is not None: return self.texture.source.get_recommended_shape() else: return None def texture_loaded_cb(self, texture, patch, owner): shape = owner.shape if self.texture is not None and self.texture.check_specular_mask: self.has_specular_mask = self.texture.has_specular_mask self.texture.check_specular_mask = False if shape.patchable: #print("CB", patch.str_id(), '-', patch.jobs_pending) owner.jobs_done_cb(patch) else: #print("CB", shape, '-', shape.jobs_pending) owner.jobs_done_cb(None) def load_textures(self, shape, owner): if self.texture: self.texture.load(shape, self.texture_loaded_cb, (shape, owner)) if self.normal_map: self.normal_map.load(shape, self.texture_loaded_cb, (shape, owner)) if self.bump_map: self.bump_map.load(shape, self.texture_loaded_cb, (shape, owner)) if self.specular_map: self.specular_map.load(shape, self.texture_loaded_cb, (shape, owner)) if self.emission_texture: self.emission_texture.load(shape, self.texture_loaded_cb, (shape, owner)) if self.occlusion_map: self.occlusion_map.load(shape, self.texture_loaded_cb, (shape, owner)) def apply_textures(self, patch): patch.instance.clearTexture() if self.texture: self.has_specular_mask = self.texture.has_specular_mask self.texture.apply(patch) if self.normal_map: self.normal_map.apply(patch) if self.bump_map: self.bump_map.apply(patch) if self.specularColor is not None and self.specular_map is not None: self.specular_map.apply(patch) if self.emission_texture: self.emission_texture.apply(patch) if self.occlusion_map: self.occlusion_map.apply(patch) def apply_patch(self, patch, owner): if (patch.jobs & Appearance.JOB_TEXTURE_LOAD) == 0: #print("APPLY", patch.str_id()) if self.nb_textures > 0: patch.jobs |= Appearance.JOB_TEXTURE_LOAD patch.jobs_pending += self.nb_textures self.load_textures(patch, owner) def apply(self, shape, owner): #Override any material present on the shape (use ModelAppearance to keep it) shape.instance.setMaterial(self.material, 1) if self.colorScale is not None: shape.instance.set_color_scale(self.colorScale) if shape.patchable: return if (shape.jobs & Appearance.JOB_TEXTURE_LOAD) == 0: #print("APPLY", shape, self.nb_textures) if self.nb_textures > 0: shape.jobs |= Appearance.JOB_TEXTURE_LOAD shape.jobs_pending += self.nb_textures self.load_textures(shape, owner)
def __init__(self): self.title = OnscreenText(text = "KAI KANG: BALL IN MAZE", style = 1, fg=(1,1,1,1), pos=(0.7,-0.95),scale= .07) self.instructions = OnscreenText(text="Mouse pointer tilts the board", pos = (-1.3, .95), fg=(1,1,1,1), align = TextNode.ALeft, scale=.05) self.accept("escape", sys.exit) # ESC to quit self.accept("arrow_up",self.moveBall,["up"]) self.accept("arrow_down",self.moveBall,["down"]) self.accept("arrow_left",self.moveBall,["left"]) self.accept("arrow_right",self.moveBall,["right"]) base.disableMouse() # Disable mouse-based camera control # place the camera camera.setPosHpr(0,-12,25,0,-65,0) self.jerk = (0,0,0) # load the maze model and reparent it to the topmost node #self.MAZE = load_model("groupegg.egg") self.MAZE = load_model("ground3.egg") self.MAZE.flattenLight() self.MAZE.reparentTo(render) self.MAZE.setPos(0,0,0) self.MAZE.setHpr(90,0,0) #self.MAZE.place() #self.pikachu = load_model("Groudon.egg") #self.pikachu = load_model("P2_Pikachu.egg") #self.pikachu.reparentTo(render) #self.pikachu.setScale(0.1) #self.pikachu.setTexture(self.pika_tex,1) #self.pikachu.setPos(endPos) # check the egg file <Collide> #self.walls = self.maze.find("**/wall_collide") self.WALLS = self.MAZE.find("**/Wall.003") ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # collision with wall #self.walls.node().setIntoCollideMask(BitMask32.bit(0)) self.WALLS.node().setIntoCollideMask(BitMask32.bit(0)) #self.WALLS.show() # holes. the triggers that cause you to lose the game self.loseTriggers = [] # collision with the ground. different bit mask #self.mazeGround = self.maze.find("**/ground_collide") #self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1)) self.MAZEGROUND = self.MAZE.find("**/Cube.003") self.MAZEGROUND.node().setIntoCollideMask(BitMask32.bit(1)) # load the ball and attach it to the scene. # it is on a dummy node so that we can rotate the ball # without rotating the ray that will be attached to it self.ballRoot = render.attachNewNode("ballRoot") self.ball = load_model("ball") self.ball.reparentTo(self.ballRoot) self.ball_tex = load_tex("pokeball.png") self.ball.setTexture(self.ball_tex,1) # Find the collision sphere for the ball in egg. self.ballSphere = self.ball.find("**/ball") self.ballSphere.node().setFromCollideMask(BitMask32.bit(0)) self.ballSphere.node().setIntoCollideMask(BitMask32.allOff()) #self.ballSphere.show() # Now we create a ray to cast down at the ball. self.ballGroundRay = CollisionRay() self.ballGroundRay.setOrigin(0,0,10) self.ballGroundRay.setDirection(0,0,-1) # Collision solids go in CollisionNode self.ballGroundCol = CollisionNode('groundRay') self.ballGroundCol.addSolid(self.ballGroundRay) self.ballGroundCol.setFromCollideMask(BitMask32.bit(1)) self.ballGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol) # CollisionTraversers calculate collisions self.cTrav = CollisionTraverser() #self.cTrav.showCollisions(render) # self.cTrav.showCollisions(render) # A list collision handler queue self.cHandler = CollisionHandlerQueue() # add collision nodes to the traverse. # maximum nodes per traverser: 32 self.cTrav.addCollider(self.ballSphere,self.cHandler) self.cTrav.addCollider(self.ballGroundColNp,self.cHandler) # collision traversers have a built-in tool to visualize collisons # self.cTrav.showCollisions(render) # Lighting for the ball ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0,0,-1)) directionalLight.setColor(Vec4(0.375,0.375,0.375,1)) directionalLight.setSpecularColor(Vec4(1,1,1,1)) self.ballRoot.setLight(render.attachNewNode(ambientLight)) self.ballRoot.setLight(render.attachNewNode(directionalLight)) #self.ballGroundColNp.show() # adding a specular highlight to the ball to make it shiny m = Material() m.setSpecular(Vec4(1,1,1,1)) m.setShininess(96) self.ball.setMaterial(m,1) self.start()
def __init__(self): ShowBase.__init__(self) base.set_background_color(0.1, 0.1, 0.8, 1) base.set_frame_rate_meter(True) base.cam.set_pos_hpr(0, 0, 25, 0, -90, 0) base.disable_mouse() # Input self.accept('escape', self.exitGame) self.accept('f1', base.toggle_wireframe) self.accept('f2', base.toggle_texture) self.accept('f3', self.toggle_debug) self.accept('f5', self.do_screenshot) # Setup scene 1: World self.debugNP = render.attach_new_node(BulletDebugNode('Debug')) self.debugNP.node().show_wireframe(True) self.debugNP.node().show_constraints(True) self.debugNP.node().show_bounding_boxes(True) self.debugNP.node().show_normals(True) self.debugNP.show() self.world = BulletWorld() self.world.set_gravity(LVector3(0, 0, -9.81)) self.world.set_debug_node(self.debugNP.node()) # Setup scene 2: Ball #visNP = loader.load_model('models/ball.egg') visNP = loader.load_model('samples/ball-in-maze/models/ball.egg.pz') visNP.clear_model_nodes() bodyNPs = BulletHelper.from_collision_solids(visNP, True) self.ballNP = bodyNPs[0] self.ballNP.reparent_to(render) self.ballNP.node().set_mass(1.0) self.ballNP.set_pos(4, -4, 1) self.ballNP.node().set_deactivation_enabled(False) visNP.reparent_to(self.ballNP) # Setup scene 3: Maze visNP = loader.load_model('models/maze.egg') #visNP = loader.load_model('samples/ball-in-maze/models/maze.egg.pz') visNP.clear_model_nodes() visNP.reparent_to(render) self.holes = [] self.maze = [] self.mazeNP = visNP bodyNPs = BulletHelper.from_collision_solids(visNP, True); for bodyNP in bodyNPs: bodyNP.reparent_to(render) if isinstance(bodyNP.node(), BulletRigidBodyNode): bodyNP.node().set_mass(0.0) bodyNP.node().set_kinematic(True) self.maze.append(bodyNP) elif isinstance(bodyNP.node(), BulletGhostNode): self.holes.append(bodyNP) # Lighting and material for the ball ambientLight = AmbientLight('ambientLight') ambientLight.set_color(LVector4(0.55, 0.55, 0.55, 1)) directionalLight = DirectionalLight('directionalLight') directionalLight.set_direction(LVector3(0, 0, -1)) directionalLight.set_color(LVector4(0.375, 0.375, 0.375, 1)) directionalLight.set_specular_color(LVector4(1, 1, 1, 1)) self.ballNP.set_light(render.attach_new_node(ambientLight)) self.ballNP.set_light(render.attach_new_node(directionalLight)) m = Material() m.set_specular(LVector4(1,1,1,1)) m.set_shininess(96) self.ballNP.set_material(m, 1) # Startup self.start_game()
class BitmapSurface(Body): """Planet is a parent nodepath that the 6 side mesh nodepaths will parent to. Planet can be moved, scale, and rotated with no problems. This uses 6 normalized planes for cubemapping.""" def init(self, scale=1, debug=False): self.sides = [] for i in range(0, 6): m = create_side(self.node_path, debug, invert=True) m.set_scale(scale) self.sides.append(m) '''The side meshes are rotated here. They are moved to their correct position in the shader.''' self.sides[0].set_hpr(90, 90, 0) self.sides[1].set_hpr(-90, 90, 0) self.sides[2].set_hpr(0, 0, 0) self.sides[3].set_hpr(0, 180, 0) self.sides[4].set_hpr(0, 90, 0) self.sides[5].set_hpr(180, 90, 0) # create sane material defaults self.material = Material() self.material.set_diffuse(VBase4(1.0, 1.0, 1.0, 1.0)) self.material.set_ambient(VBase4(1.0, 1.0, 1.0, 1.0)) self.material.set_emission(VBase4(0.0, 0.0, 0.0, 1.0)) self.material.set_shininess(1) self.material.set_specular(VBase4(0.5, 0.0, 0.0, 1.0)) #tex = Texture() for m in self.sides: m.set_material(self.material) '''m.set_shader_input('colorTexture', tex) m.set_shader_input('nightTesture', tex) m.set_shader_input('glossTexture', tex)''' def load_shaders(self): shaders = Shader.load(Shader.SL_GLSL, 'Shader/Planet/surface_vertex.glsl', 'Shader/Planet/surface_fragment.glsl', '', "Shader/DefaultShaders/Opaque/tesscontrol.glsl", "Shader/DefaultShaders/Opaque/tesseval.glsl") convertToPatches(self.node_path) for m in self.sides: m.set_shader(shaders, 51) def set_texture(self, texture_path): """Textures the surface. texture_path is a string in the same format as loader.loadCubeMap('texture_#.png') for a multifile cubemap. The orientation is a little different than what is described in the panda manual. North pole is z-up.""" for i in range(0, 6): self.sides[i].setShaderInput('colorTexture', loader.loadTexture( texture_path.replace('#', str(i)))) def set_textures(self, texture_paths={}): """MultiTextures the surface. t_path is a string in the same format as loader.loadCubeMap('texture_#.png') for a multifile cubemap. The orientation is a little different than what is described in the panda manual. North pole is z-up.""" for i in range(0, 6): diffuse = sandbox.base.loader.loadTexture(texture_paths['diffuse'].replace('#', str(i))) diffuse.setMinfilter(Texture.FTLinearMipmapLinear) diffuse.setAnisotropicDegree(4) self.sides[i].set_texture(diffuse) continue normal = base.loader.loadTexture('Data/Textures/EmptyNormalTexture.png') normalts = TextureStage('normalts') self.sides[i].set_texture(normalts, normal) if 'specular' in texture_paths: specular = sandbox.base.loader.loadTexture(texture_paths['specular'].replace('#', str(i))) else: specular = sandbox.base.loader.loadTexture('Data/Textures/EmptySpecularTexture.png') spects = TextureStage('spects') self.sides[i].set_texture(spects, specular) roughness = sandbox.base.loader.loadTexture('Data/Textures/EmptyRoughnessTexture.png') roughts= TextureStage('roughts') self.sides[i].set_texture(roughts, roughness) '''if 'night' in texture_paths: self.sides[i].set_shader_input('nightTexture', sandbox.base.loader.loadTexture( texture_paths['night'].replace('#', str(i))))''' '''self.sides[i].set_shader_input('colorTexture', texture) if night_path: self.sides[i].set_shader_input('nightTesture', loader.loadTexture( night_path.replace('#', str(i)))) if gloss_path: self.sides[i].set_shader_input('glossTexture', loader.loadTexture( gloss_path.replace('#', str(i))))''' self.load_shaders() def set_ambient(self, r, g, b, a): self.material.set_ambient( VBase4(float(r), float(g), float(b), float(a))) def set_diffuse(self, r, g, b, a): self.material.set_diffuse( VBase4(float(r), float(g), float(b), float(a))) def set_specular(self, r, g, b, a): self.material.set_specular( VBase4(float(r), float(g), float(b), float(a))) def set_shininess(self, n): self.material.set_shininess(n)
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
def __init__(self): # This code puts the standard title and instruction text on screen self.title = OnscreenText(text="Panda3D: Tutorial - Collision Detection", style=1, fg=(1,1,1,1), pos=(0.7,-0.95), scale = .07) self.instructions = OnscreenText(text="Mouse pointer tilts the board", pos = (-1.3, .95), fg=(1,1,1,1), align = TextNode.ALeft, scale = .05) self.accept("escape", sys.exit) # Escape quits base.disableMouse() # Disable mouse-based camera control camera.setPosHpr(0, 0, 25, 0, -90, 0) # Place the camera # Load the maze and place it in the scene self.maze = loader.loadModel("models/maze") self.maze.reparentTo(render) # Most times, you want collisions to be tested against invisible geometry # rather than every polygon. This is because testing against every polygon # in the scene is usually too slow. You can have simplified or approximate # geometry for the solids and still get good results. # # Sometimes you'll want to create and position your own collision solids in # code, but it's often easier to have them built automatically. This can be # done by adding special tags into an egg file. Check maze.egg and ball.egg # and look for lines starting with <Collide>. The part is brackets tells # Panda exactly what to do. Polyset means to use the polygons in that group # as solids, while Sphere tells panda to make a collision sphere around them # Keep means to keep the polygons in the group as visable geometry (good # for the ball, not for the triggers), and descend means to make sure that # the settings are applied to any subgroups. # # Once we have the collision tags in the models, we can get to them using # NodePath's find command # Find the collision node named wall_collide self.walls = self.maze.find("**/wall_collide") # Collision objects are sorted using BitMasks. BitMasks are ordinary numbers # with extra methods for working with them as binary bits. Every collision # solid has both a from mask and an into mask. Before Panda tests two # objects, it checks to make sure that the from and into collision masks # have at least one bit in common. That way things that shouldn't interact # won't. Normal model nodes have collision masks as well. By default they # are set to bit 20. If you want to collide against actual visable polygons, # set a from collide mask to include bit 20 # # For this example, we will make everything we want the ball to collide with # include bit 0 self.walls.node().setIntoCollideMask(BitMask32.bit(0)) # CollisionNodes are usually invisible but can be shown. Uncomment the next # line to see the collision walls # self.walls.show() # We will now find the triggers for the holes and set their masks to 0 as # well. We also set their names to make them easier to identify during # collisions self.loseTriggers = [] for i in range(6): trigger = self.maze.find("**/hole_collide" + str(i)) trigger.node().setIntoCollideMask(BitMask32.bit(0)) trigger.node().setName("loseTrigger") self.loseTriggers.append(trigger) # Uncomment this line to see the triggers # trigger.show() # Ground_collide is a single polygon on the same plane as the ground in the # maze. We will use a ray to collide with it so that we will know exactly # what height to put the ball at every frame. Since this is not something # that we want the ball itself to collide with, it has a different # bitmask. self.mazeGround = self.maze.find("**/ground_collide") self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1)) # Load the ball and attach it to the scene # It is on a root dummy node so that we can rotate the ball itself without # rotating the ray that will be attached to it self.ballRoot = render.attachNewNode("ballRoot") self.ball = loader.loadModel("models/ball") self.ball.reparentTo(self.ballRoot) # Find the collison sphere for the ball which was created in the egg file # Notice that it has a from collision mask of bit 0, and an into collison # mask of no bits. This means that the ball can only cause collisions, not # be collided into self.ballSphere = self.ball.find("**/ball") self.ballSphere.node().setFromCollideMask(BitMask32.bit(0)) self.ballSphere.node().setIntoCollideMask(BitMask32.allOff()) # No we create a ray to start above the ball and cast down. This is to # Determine the height the ball should be at and the angle the floor is # tilting. We could have used the sphere around the ball itself, but it # would not be as reliable self.ballGroundRay = CollisionRay() # Create the ray self.ballGroundRay.setOrigin(0,0,10) # Set its origin self.ballGroundRay.setDirection(0,0,-1) # And its direction # Collision solids go in CollisionNode self.ballGroundCol = CollisionNode('groundRay') # Create and name the node self.ballGroundCol.addSolid(self.ballGroundRay) # Add the ray self.ballGroundCol.setFromCollideMask(BitMask32.bit(1)) # Set its bitmasks self.ballGroundCol.setIntoCollideMask(BitMask32.allOff()) # Attach the node to the ballRoot so that the ray is relative to the ball # (it will always be 10 feet over the ball and point down) self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol) # Uncomment this line to see the ray # self.ballGroundColNp.show() # Finally, we create a CollisionTraverser. CollisionTraversers are what # do the job of calculating collisions self.cTrav = CollisionTraverser() # Collision traverservs tell collision handlers about collisions, and then # the handler decides what to do with the information. We are using a # CollisionHandlerQueue, which simply creates a list of all of the # collisions in a given pass. There are more sophisticated handlers like # one that sends events and another that tries to keep collided objects # apart, but the results are often better with a simple queue self.cHandler = CollisionHandlerQueue() # Now we add the collision nodes that can create a collision to the # traverser. The traverser will compare these to all others nodes in the # scene. There is a limit of 32 CollisionNodes per traverser # We add the collider, and the handler to use as a pair self.cTrav.addCollider(self.ballSphere, self.cHandler) self.cTrav.addCollider(self.ballGroundColNp, self.cHandler) # Collision traversers have a built in tool to help visualize collisions. # Uncomment the next line to see it. # self.cTrav.showCollisions(render) # This section deals with lighting for the ball. Only the ball was lit # because the maze has static lighting pregenerated by the modeler ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0, 0, -1)) directionalLight.setColor(Vec4(0.375, 0.375, 0.375, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) self.ballRoot.setLight(render.attachNewNode(ambientLight)) self.ballRoot.setLight(render.attachNewNode(directionalLight)) # This section deals with adding a specular highlight to the ball to make # it look shiny m = Material() m.setSpecular(Vec4(1,1,1,1)) m.setShininess(96) self.ball.setMaterial(m, 1) # Finally, we call start for more initialization self.start()
def getStateFromMaterial(prim_material): state = RenderState.makeFullDefault() emission = None ambient = None diffuse = None specular = None shininess = None reflection = None reflectivity = None if prim_material: for prop in prim_material.supported: value = getattr(prim_material, prop) if value is None: continue if type(value) is tuple: val4 = value[3] if len(value) > 3 else 1.0 value = VBase4(value[0], value[1], value[2], val4) if isinstance(value, collada.material.Map): texture_file = value.sampler.surface.image.path if not texture_file is None: (root, leaf) = os.path.split(sys.argv[1]) tex_absolute = os.path.join(root, texture_file) myImage = PNMImage() myImage.read(Filename(tex_absolute)) myTexture = Texture(texture_file) myTexture.load(myImage) state = state.addAttrib(TextureAttrib.make(myTexture)) elif prop == 'emission': emission = value elif prop == 'ambient': ambient = value elif prop == 'diffuse': diffuse = value elif prop == 'specular': specular = value elif prop == 'shininess': shininess = value elif prop == 'reflective': reflective = value elif prop == 'reflectivity': reflectivity = value elif prop == 'transparent': pass elif prop == 'transparency': pass else: raise mat = Material() if not emission is None: mat.setEmission(emission) if not ambient is None: mat.setAmbient(ambient) if not diffuse is None: mat.setDiffuse(diffuse) if not specular is None: mat.setSpecular(specular) if not shininess is None: mat.setShininess(shininess) state = state.addAttrib(MaterialAttrib.make(mat)) return state
class ProceduralSurface(Body): """Planet is a parent nodepath that the icosphere will parent to. Planet can be moved, scale, and rotated with no problems. This uses an icosphere.""" def init(self, scale=1, debug=False): self.node_path = shape_generator_advanced.IcoSphere(1, 5) # create sane material defaults self.material = Material() self.material.set_diffuse(VBase4(1.0, 1.0, 1.0, 1.0)) self.material.set_ambient(VBase4(1.0, 1.0, 1.0, 1.0)) self.material.set_emission(VBase4(0.0, 0.0, 0.0, 1.0)) self.material.set_shininess(1) self.material.set_specular(VBase4(0.5, 0.0, 0.0, 1.0)) self.node_path.set_material(self.material) def load_shaders(self): shaders = Shader.load(Shader.SL_GLSL, 'Shader/Planet/surface_vertex.glsl', 'Shader/Planet/surface_fragment.glsl', '', "Shader/DefaultShaders/Opaque/tesscontrol.glsl", "Shader/DefaultShaders/Opaque/tesseval.glsl") convertToPatches(self.node_path) self.node_path.set_shader(shaders, 51) def set_ambient(self, r, g, b, a): self.material.set_ambient( VBase4(float(r), float(g), float(b), float(a))) def set_diffuse(self, r, g, b, a): self.material.set_diffuse( VBase4(float(r), float(g), float(b), float(a))) def set_specular(self, r, g, b, a): self.material.set_specular( VBase4(float(r), float(g), float(b), float(a))) def set_shininess(self, n): self.material.set_shininess(n)
def _add_visualization(self): if self.render: [path, scale, x_y_z_offset, H] = self.path[self.np_random.randint(0, len(self.path))] if path not in BaseVehicle.model_collection: car_model = self.loader.loadModel( AssetLoader.file_path("models", path)) BaseVehicle.model_collection[path] = car_model else: car_model = BaseVehicle.model_collection[path] car_model.setScale(scale) car_model.setH(H) car_model.setPos(x_y_z_offset) car_model.setZ(-self.TIRE_RADIUS - self.CHASSIS_TO_WHEEL_AXIS + x_y_z_offset[-1]) car_model.instanceTo(self.origin) if self.config["random_color"]: material = Material() material.setBaseColor( (self.panda_color[0] * self.MATERIAL_COLOR_COEFF, self.panda_color[1] * self.MATERIAL_COLOR_COEFF, self.panda_color[2] * self.MATERIAL_COLOR_COEFF, 0.2)) material.setMetallic(self.MATERIAL_METAL_COEFF) material.setSpecular(self.MATERIAL_SPECULAR_COLOR) material.setRefractiveIndex(1.5) material.setRoughness(self.MATERIAL_ROUGHNESS) material.setShininess(self.MATERIAL_SHININESS) material.setTwoside(False) self.origin.setMaterial(material, True)
def __init__(self): # Setup window size, title and so on load_prc_file_data( "", """ win-size 1600 900 window-title Render Pipeline - Lights demo """) # ------ Begin of render pipeline code ------ # Insert the pipeline path to the system path, this is required to be # able to import the pipeline classes pipeline_path = "../../" # Just a special case for my development setup, so I don't accidentally # commit a wrong path. You can remove this in your own programs. if not os.path.isfile(os.path.join(pipeline_path, "setup.py")): pipeline_path = "../../RenderPipeline/" sys.path.insert(0, pipeline_path) from rpcore import RenderPipeline, SpotLight self.render_pipeline = RenderPipeline() self.render_pipeline.create(self) # This is a helper class for better camera movement - its not really # a rendering element, but it included for convenience from rpcore.util.movement_controller import MovementController # ------ End of render pipeline code, thats it! ------ # Set time of day self.render_pipeline.daytime_mgr.time = "4:50" self.half_energy = 5000 self.lamp_fov = 70 self.lamp_radius = 10 # Load the scene model = loader.loadModel("scene/Scene.bam") model.reparent_to(render) # Animate balls, this is for testing the motion blur blend_type = "noBlend" np = model.find("**/MBRotate") np.hprInterval(1.5, Vec3(360, 360, 0), Vec3(0, 0, 0), blendType=blend_type).loop() np = model.find("**/MBUpDown") np_pos = np.get_pos() - Vec3(0, 0, 2) Sequence( np.posInterval(0.15, np_pos + Vec3(0, 0, 6), np_pos, blendType=blend_type), np.posInterval(0.15, np_pos, np_pos + Vec3(0, 0, 6), blendType=blend_type)).loop() np = model.find("**/MBFrontBack") np_pos = np.get_pos() - Vec3(0, 0, 2) Sequence( np.posInterval(0.15, np_pos + Vec3(0, 6, 0), np_pos, blendType=blend_type), np.posInterval(0.15, np_pos, np_pos + Vec3(0, 6, 0), blendType=blend_type)).loop() np = model.find("**/MBScale") Sequence( np.scaleInterval(0.2, Vec3(1.5), Vec3(1), blendType=blend_type), np.scaleInterval(0.2, Vec3(1), Vec3(1.5), blendType=blend_type)).loop() # Generate temperature lamps # This shows how to procedurally create lamps. In this case, we # base the lights positions on empties created in blender. self._lights = [] light_key = lambda light: int(light.get_name().split("LampLum")[-1]) lumlamps = sorted(model.find_all_matches("**/LampLum*"), key=light_key) for lumlamp in lumlamps: lum = float(lumlamp.get_name()[len("LampLum"):]) light = SpotLight() light.direction = (0, -1.5, -1) light.fov = self.lamp_fov light.set_color_from_temperature(lum * 1000.0) light.energy = self.half_energy light.pos = lumlamp.get_pos(self.render) light.radius = self.lamp_radius light.casts_shadows = False light.shadow_map_resolution = 256 self.render_pipeline.add_light(light) # Put Pandas on the edges if lumlamp in lumlamps[0:2] + lumlamps[-2:]: panda = loader.loadModel("panda") panda.reparent_to(render) panda_mat = Material("default") panda_mat.emission = 0 panda.set_material(panda_mat) panda.set_pos(light.pos) panda.set_z(0.65) panda.set_h(180 + randint(-60, 60)) panda.set_scale(0.2) panda.set_y(panda.get_y() - 3.0) self._lights.append(light) self.render_pipeline.prepare_scene(model) # Init movement controller self.controller = MovementController(self) self.controller.set_initial_position(Vec3(23.9, 42.5, 13.4), Vec3(23.8, 33.4, 10.8)) self.controller.setup() self.day_time = 0.3 self.time_direction = 0 # Keys to modify the time, disabled in the demo self.accept("k", self.reset) self.accept("p", self.set_time_direction, [ 1, ]) self.accept("p-up", self.set_time_direction, [ 0, ]) self.accept("i", self.set_time_direction, [ -1, ]) self.accept("i-up", self.set_time_direction, [ 0, ]) self.addTask(self.update, "update")
class Surface(Body): """planet is a parent nodepath that the 6 side mesh nodepaths will parent to. planet can be moved, scale, and rotated with no problems""" def init(self): shaders = Shader.load(Shader.SLGLSL, "planet_surface_vert.glsl", "planet_surface_frag.glsl") self.node_path.setShader(shaders) tex = Texture() # create sane material defaults self.material = Material() self.material.set_ambient(VBase4(0.0, 0.0, 0.0, 0.0)) self.material.set_diffuse(VBase4(0.0, 0.0, 0.0, 0.0)) self.material.set_emission(VBase4(0.0, 0.0, 0.0, 0.0)) self.material.set_shininess(0) self.material.set_specular(VBase4(0.0, 0.0, 0.0, 0.0)) for m in self.sides: m.set_material(self.material) """m.set_shader_input('colorTexture', tex) m.set_shader_input('nightTesture', tex) m.set_shader_input('glossTexture', tex)""" def set_texture(self, texture_path): """Textures the surface. texture_path is a string in the same format as loader.loadCubeMap('texture_#.png') for a multifile cubemap. The orientation is a little different than what is described in the panda manual. North pole is z-up""" for i in range(0, 6): self.sides[i].setShaderInput("colorTexture", loader.loadTexture(texture_path.replace("#", str(i)))) def set_textures(self, texture_path="", night_path="", gloss_path=""): """MultiTextures the surface. t_path is a string in the same format as loader.loadCubeMap('texture_#.png') for a multifile cubemap. The orientation is a little different than what is described in the panda manual. North pole is z-up""" for i in range(0, 6): texture = loader.loadTexture(texture_path.replace("#", str(i))) texture.setMinfilter(Texture.FTLinearMipmapLinear) texture.setAnisotropicDegree(4) self.sides[i].set_shader_input("colorTexture", texture) if night_path: self.sides[i].set_shader_input("nightTesture", loader.loadTexture(night_path.replace("#", str(i)))) if gloss_path: self.sides[i].set_shader_input("glossTexture", loader.loadTexture(gloss_path.replace("#", str(i)))) def set_ambient(self, r, g, b, a): self.material.set_ambient(VBase4(float(r), float(g), float(b), float(a))) def set_diffuse(self, r, g, b, a): self.material.set_diffuse(VBase4(float(r), float(g), float(b), float(a))) def set_specular(self, r, g, b, a): self.material.set_specular(VBase4(float(r), float(g), float(b), float(a))) def set_shininess(self, n): self.material.set_shininess(n)
def __init__(self): ShowBase.__init__(self) self.render.setShaderAuto() ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(0.25, 0.25, 0.25, 1)) ambientLightNP = render.attachNewNode(ambientLight) self.render.setLight(ambientLightNP) # Directional light 01 directionalLight = DirectionalLight('directionalLight') directionalLight.setColor(Vec4(0.5, 0.5, 0.5, 1)) directionalLightNP = self.render.attachNewNode(directionalLight) self.dlnp = directionalLightNP # This light is facing backwards, towards the camera. directionalLightNP.setHpr(180, -20, 0) self.render.setLight(directionalLightNP) n = self.render.attachNewNode(um_GN) myMaterial = Material() myMaterial.setShininess(30.0) #Make this material shiny myMaterial.setAmbient(VBase4(1,1,1,1)) myMaterial.setDiffuse(VBase4(0.5,0.6,0.5,1)) myMaterial.setSpecular(VBase4(1,1,1,1)) myMaterial.setTwoside(True) n.setMaterial(myMaterial) n.reparentTo(self.render) # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") class KeyMgr(DirectObject.DirectObject): def __init__(self): self.states = {'up':False,'down':False,'left':False,'right':False,'pgup':False,'pgdn':False, 'a':False} self.accept('arrow_up',self.state, ['up', True]) self.accept('arrow_up-up',self.state, ['up', False]) self.accept('arrow_down',self.state, ['down', True]) self.accept('arrow_down-up',self.state, ['down', False]) self.accept('arrow_left',self.state, ['left', True]) self.accept('arrow_left-up',self.state, ['left', False]) self.accept('arrow_right',self.state, ['right', True]) self.accept('arrow_right-up',self.state, ['right', False]) self.accept('page_up',self.state, ['pgup',True]) self.accept('page_up-up',self.state, ['pgup',False]) self.accept('page_down',self.state, ['pgdn',True]) self.accept('page_down-up',self.state, ['pgdn',False]) self.accept('a', self.impulse, ['a',]) self.accept('escape', sys.exit ) # exit on esc self.impulses = list() def state(self, key, st): self.states[key] = st def impulse(self, key): self.impulses.append(key) def __getitem__(self, key): return self.states.__getitem__(key) self.keymgr = KeyMgr() self.auto = False self.campos = spherical_coordinate(10,90,90)
def __init__(self): base.setBackgroundColor(0.1, 0.1, 0.8, 1) base.setFrameRateMeter(True) base.cam.setPosHpr(0, 0, 25, 0, -90, 0) base.disableMouse() # Input self.accept('escape', self.exitGame) self.accept('f1', self.toggleWireframe) self.accept('f2', self.toggleTexture) self.accept('f3', self.toggleDebug) self.accept('f5', self.doScreenshot) # Setup scene 1: World self.debugNP = render.attachNewNode(BulletDebugNode('Debug')) self.debugNP.node().showWireframe(True) self.debugNP.node().showConstraints(True) self.debugNP.node().showBoundingBoxes(True) self.debugNP.node().showNormals(True) self.debugNP.show() self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Setup scene 2: Ball visNP = loader.loadModel('models/ball.egg') visNP.clearModelNodes() bodyNPs = BulletHelper.fromCollisionSolids(visNP, True) self.ballNP = bodyNPs[0] self.ballNP.reparentTo(render) self.ballNP.node().setMass(1.0) self.ballNP.setPos(4, -4, 1) self.ballNP.node().setDeactivationEnabled(False) visNP.reparentTo(self.ballNP) # Setup scene 3: Maze visNP = loader.loadModel('models/maze.egg') visNP.clearModelNodes() visNP.reparentTo(render) self.holes = [] self.maze = [] self.mazeNP = visNP bodyNPs = BulletHelper.fromCollisionSolids(visNP, True); for bodyNP in bodyNPs: bodyNP.reparentTo(render) if isinstance(bodyNP.node(), BulletRigidBodyNode): bodyNP.node().setMass(0.0) bodyNP.node().setKinematic(True) self.maze.append(bodyNP) elif isinstance(bodyNP.node(), BulletGhostNode): self.holes.append(bodyNP) # Lighting and material for the ball ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(0.55, 0.55, 0.55, 1)) directionalLight = DirectionalLight('directionalLight') directionalLight.setDirection(Vec3(0, 0, -1)) directionalLight.setColor(Vec4(0.375, 0.375, 0.375, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) self.ballNP.setLight(render.attachNewNode(ambientLight)) self.ballNP.setLight(render.attachNewNode(directionalLight)) m = Material() m.setSpecular(Vec4(1,1,1,1)) m.setShininess(96) self.ballNP.setMaterial(m, 1) # Startup self.startGame()
def __init__(self): ShowBase.__init__(self) # Window winprops = WindowProperties() winprops .setSize(640, 360) base.win.requestProperties(winprops ) base.setFrameRateMeter(True) # gamepad self.gamepad = None devices = self.devices.getDevices(InputDevice.DeviceClass.gamepad) if devices: print("Devices founds..." + str(len(devices))) # gamepad yet. if devices[0].device_class == InputDevice.DeviceClass.gamepad and not self.gamepad: print("Found %s" % (devices[0])) self.gamepad = devices[0] # Disable the camera trackball controls. self.disableMouse() # create material myMaterial = Material() myMaterial.setShininess(0.5) #Make this material shiny myMaterial.setSpecular(LColor(255,255,0,0)) #myMaterial.setAmbient((0, 0, 1, 1)) #Make this material blue # load circuit model self.circuitNodePath = self.loader.loadModel("/c/tmp/media/circuit.bam") self.circuitNodePath.reparentTo(self.render) self.circuitNodePath.setScale(1.0, 1.0, 1.0) self.circuitNodePath.setPos(1.0,-5,0) self.circuitNodePath.setHpr(0,90, 270) self.circuitNodePath.setMaterial(myMaterial) # load the environment model. self.scene = self.loader.loadModel("models/environment") self.scene.reparentTo(self.render) self.scene.setScale(1.25, 1.25, 1.25) self.scene.setPos(0,0, -0.1) # Load the environment model. self.car = self.loader.loadModel("models/box") self.car.reparentTo(self.render) self.car.setScale(1.0, 1.0, 1.0) self.car.setPos(0, 40, 0.0) # Lights render.clearLight() alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.2, 0.2, 0.2, 1)) alightNP = render.attachNewNode(alight) render.setLight(alightNP) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) #dlight.setColor(Vec4(1.0, 1.0, 0.8, 1)) dlight.setColorTemperature(6500) dlightNP = render.attachNewNode(dlight) render.setLight(dlightNP) s1light = PointLight('spot1Light') s1light.setColor(Vec4(0.0, 1.0, 0.0, 1.0)) s1light.setPoint((0, 0, 0.3)) s1light.setMaxDistance(4.0) s1light.setAttenuation((0.1,0.01,0.001)) s1lightNP = render.attachNewNode(s1light) render.setLight(s1lightNP) self.circuitNodePath.setLight(s1lightNP) # camera self.camLens.setFov(80) self.camLens.setNear(0.01) self.camera.setPos(0.0,0.1,0.2) self.camera.setHpr(0,0,0) self.camera.setHpr(0,-12,0) self.camera.reparentTo(self.car) # osd self.dr = self.win.makeDisplayRegion() self.dr.setSort(20) myCamera2d = NodePath(Camera('myCam2d')) lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setNearFar(-1000, 1000) myCamera2d.node().setLens(lens) myRender2d = NodePath('myRender2d') myRender2d.setDepthTest(False) myRender2d.setDepthWrite(False) myCamera2d.reparentTo(myRender2d) self.dr.setCamera(myCamera2d) # lines = LineSegs() # lines.moveTo(100,0,0) # lines.drawTo(100,500,0) # lines.setThickness(4) # node = lines.create() # np = NodePath(node) # np.reparentTo(myRender2d) # controls self.quit_button = KeyboardButton.ascii_key('q') self.quit = False self.recording_button = KeyboardButton.ascii_key('r') self.recording = False self.autopilot_button = KeyboardButton.ascii_key('a') self.humanpilot_button = KeyboardButton.ascii_key('m') self.autopilot = True self.autopilot_dir = 0.0 # tasks self.taskMgr.add(self.move_task, 'moveTask')
def render_level(map): from direct.showbase.Loader import Loader tex=Loader("foo").loadTexture("BrickOldSharp0215_2_thumbhuge.jpg") nor=Loader("foo").loadTexture("BrickOldSharp0215_2_thumbhuge-n.jpg") ts = TextureStage('ts') ts.setMode(TextureStage.MNormal) myMaterial = Material() myMaterial.setShininess(0.0) myMaterial.setAmbient(Vec4(0,0,0,1)) myMaterial.setEmission(Vec4(0.0,0.0,0.0,1)) myMaterial.setDiffuse(Vec4(0.2,0.2,0.2,1)) myMaterial.setSpecular(Vec4(0.5,0.5,0.5,1)) level_node = NodePath("level") for i in range(0,22,1): x = i * 2.0 for j in range(0,22,1): y = j * 2.0 hideset = set() cell = map[i][j] if cell.north == OPEN: hideset.add(2) if cell.west == OPEN: hideset.add(3) if cell.south == OPEN: hideset.add(0) if cell.east == OPEN: hideset.add(1) xcube = makeCube(inverse=True, hide=hideset) cube = NodePath(xcube) cube.setTexture(tex) cube.setTexture(ts,nor) cube.reparentTo(level_node) cube.setPos(x, y, 0 ) #cube.setMaterial(myMaterial) return level_node