def __init__(self,conf): GEntity.__init__(self,conf) self.p3dobject.reparentTo(self.gmap.units_node) self.p3dobject.setTransparency(TransparencyAttrib.MAlpha) #to be put under condition for non pickable units (bonuses npc for instance) self.p3dobject.setTag('GUnit-pickable','1') self.p3dobject.setPos(self.gmap.root.find('**/tile_'+str(conf['tileid'])),0,0,0) #supposedly already a float, but will screw up if not, so just making sure. self.move_speed=float(conf['move_speed']) self.path=[] self.popout_when_move_over=False self.pid=conf['pid'] #highlight self.ts_highlighted=TextureStage('ts_highlighted') self.ts_highlighted.setMode(TextureStage.MDecal) self.ts_highlighted.setSort(2) #highlight self.ts_selected=TextureStage('ts_selected') self.ts_selected.setMode(TextureStage.MDecal) self.ts_selected.setSort(3)
def create_instance(self): self.create_buffer() # Water surface maker = CardMaker('water') maker.setFrame(self.x1, self.x2, self.y1, self.y2) self.waterNP = self.parent.instance.attachNewNode(maker.generate()) self.waterNP.setHpr(0, -90, 0) self.waterNP.setPos(0, 0, self.z) self.waterNP.setTransparency(TransparencyAttrib.MAlpha) self.waterNP.setShader(Shader.load(Shader.SL_GLSL, vertex=defaultDirContext.find_shader('water-vertex.glsl'), fragment=defaultDirContext.find_shader('water-fragment.glsl'))) self.waterNP.setShaderInput('wateranim', Vec4(0.03, -0.015, self.scale, 0)) # vx, vy, scale, skip # offset, strength, refraction factor (0=perfect mirror, 1=total refraction), refractivity self.waterNP.setShaderInput('waterdistort', Vec4(0.4, 4.0, 0.25, 0.45)) self.waterNP.setShaderInput('time', 0) # Reflection plane self.waterPlane = Plane(Vec3(0, 0, self.z + 1), Point3(0, 0, self.z)) planeNode = PlaneNode('waterPlane') planeNode.setPlane(self.waterPlane) # reflection texture, created in realtime by the 'water camera' tex0 = self.buffer.getTexture() tex0.setWrapU(Texture.WMClamp) tex0.setWrapV(Texture.WMClamp) ts0 = TextureStage('reflection') self.waterNP.setTexture(ts0, tex0) # distortion texture tex1 = loader.loadTexture('textures/water.png') ts1 = TextureStage('distortion') self.waterNP.setTexture(ts1, tex1) self.task = taskMgr.add(self.update, "waterTask")
def setupTexture(self): """ This is the overlay/decal/etc. which contains the typed characters. The texture size and the font size are currently tied together. :return: """ self.texImage = PNMImage(1024, 1024) self.texImage.addAlpha() self.texImage.fill(1.0) self.texImage.alphaFill(1.0) self.tex = Texture('typing') self.tex.setMagfilter(Texture.FTLinear) self.tex.setMinfilter(Texture.FTLinear) self.typingStage = TextureStage('typing') self.typingStage.setMode(TextureStage.MModulate) self.tex.load(self.texImage) # ensure we can quickly update subimages self.tex.setKeepRamImage(True) # temp for drawing chars self.chImage = PNMImage(*self.fontCharSize)
def _gen_flowers(self, surf_mod, angle, side): """Generate texture flowers. Args: surf_mod (panda3d.core.NodePath): Surface model. angle (int): Surface model angle. side (str): Surface model side. """ for i in range(random.randint(0, 3)): ts = TextureStage("ts_flower{}".format(str(i))) ts.setMode(TextureStage.MDecal) tex = loader.loadTexture( # noqa: F821 "just_tex/flower{}.png".format(str(random.randint(1, 5)))) tex.setWrapU(Texture.WMClamp) tex.setWrapV(Texture.WMClamp) surf_mod.setTexture(ts, tex) surf_mod.setTexPos( ts, random.randint(*FLOWER_RANGES[(angle, side)]["u"]), random.randint(*FLOWER_RANGES[(angle, side)]["v"]), 0, ) surf_mod.setTexScale(ts, 20, 20)
def generateSurfaceTextures(self): # Textureize self.grassTexture = loader.loadTexture("Textures/grass.png") self.grassTS = TextureStage('grass') self.grassTS.setSort(1) self.rockTexture = loader.loadTexture("Textures/rock.jpg") self.rockTS = TextureStage('rock') self.rockTS.setSort(2) self.rockTS.setCombineRgb(TextureStage.CMAdd, TextureStage.CSLastSavedResult, TextureStage.COSrcColor, TextureStage.CSTexture, TextureStage.COSrcColor) self.sandTexture = loader.loadTexture("Textures/sand.jpg") self.sandTS = TextureStage('sand') self.sandTS.setSort(3) self.sandTS.setPriority(5) self.snowTexture = loader.loadTexture("Textures/ice.png") self.snowTS = TextureStage('snow') self.snowTS.setSort(4) self.snowTS.setPriority(0) # Grid for city placement and guide and stuff self.gridTexture = loader.loadTexture("Textures/grid.png") self.gridTexture.setWrapU(Texture.WMRepeat) self.gridTexture.setWrapV(Texture.WMRepeat) self.gridTS = TextureStage('grid') self.gridTS.setSort(5) self.gridTS.setPriority(10)
def __init__(self, name, resource): """Arguments: resource -- name of a directory in assets/skyboxes that contains 6 images. """ ManagedAsset.__init__(self, "sky") self.name = name tex = None for ext in ("png", "jpg", "tga"): f = Filename("skyboxes/{}/0.{}".format(resource, ext)) if f.resolveFilename(getModelPath().getValue()): tex = TexturePool.loadCubeMap("skyboxes/{}/#.{}".format(resource, ext)) break if tex is None: raise ResourceLoadError("assets/skyboxes/%s" % resource, "maybe wrong names or different extensions?") self.node = loader.loadModel("misc/invcube") self.node.clearTexture() self.node.clearMaterial() self.node.setScale(10000) self.node.setTwoSided(True) self.node.setBin('background', 0) self.node.setDepthTest(False) self.node.setDepthWrite(False) self.node.setLightOff() self.node.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) self.node.setTexProjector(TextureStage.getDefault(), render, self.node); self.node.setTexture(tex, 1) self.node.flattenLight() #self.node.setCompass() # not needed with world-space-UVs self.addTask(self.update, "sky repositioning", sort=10, taskChain="world")
def loadPrisonCrater(): ## Sky color base.win.setClearColor(Vec4(.46,.824,.904,1)) ## Load Ground sand = loader.loadModel("data/models/sand.bam") sand.reparentTo(render) sand.setTexScale(TextureStage.getDefault(),5000,5000) craterwalls = loader.loadModel("data/models/craterwalls.bam") craterwalls.reparentTo(render) craterwalls.setTexScale(TextureStage.getDefault(),500,50) ## World Effects fog = Fog("Fog") fog.setColor(255,215,143) fog.setExpDensity(.0000001) render.setFog(fog) alight = render.attachNewNode(AmbientLight("Abient")) alight.node().setColor(Vec4(.9,.9,.9,1)) render.setLight(alight) sun = DirectionalLight('Sun') sun.setColor(Vec4(1,1,1,1)) sunNP = render.attachNewNode(sun) sunNP.setPos(0,0,4000) sunNP.setHpr(0,-90,0) render.setLight(sunNP)
def makeSprite(name, texture, scale, add = False): from panda3d.core import (GeomVertexFormat, GeomVertexData, GeomEnums, InternalName, GeomVertexWriter, GeomPoints, Geom, GeomNode, NodePath, TextureStage, TexGenAttrib, BoundingSphere) format = GeomVertexFormat.getV3() data = GeomVertexData(name + "_data", format, GeomEnums.UHStatic) writer = GeomVertexWriter(data, InternalName.getVertex()) writer.addData3f((0, 0, 0)) primitive = GeomPoints(GeomEnums.UHStatic) primitive.addVertex(0) primitive.closePrimitive() geom = Geom(data) geom.addPrimitive(primitive) geomNode = GeomNode(name) geomNode.addGeom(geom) np = NodePath(geomNode) np.setLightOff(1) np.setMaterialOff(1) np.setRenderModePerspective(True) ts = TextureStage('sprite') if add: ts.setMode(TextureStage.MAdd) np.setTexture(ts, texture) np.setTexGen(ts, TexGenAttrib.MPointSprite) np.setDepthWrite(False) np.setDepthOffset(1) np.setTransparency(True) np.node().setBounds(BoundingSphere((0, 0, 0), 1)) np.node().setFinal(True) np.flattenStrong() np.setScale(scale) return np
def setup(self): self.tex1 = MovieTexture('videos/saturn5_apollo_launch.mp4') assert self.tex1.read('videos/saturn5_apollo_launch.mp4') self.tex2 = MovieTexture('videos/boards_eye_view.mp4') assert self.tex2.read('videos/boards_eye_view.mp4') self.cm1 = CardMaker('saturn') self.cm1.setFrameFullscreenQuad() self.cm1.setUvRange(self.tex1) self.card1 = NodePath(self.cm1.generate()) self.card1.reparentTo(self.path) self.card1.setPos(0,0,10) self.card1.setP(50) self.cm2 = CardMaker('board') self.cm2.setFrameFullscreenQuad() self.cm2.setUvRange(self.tex2) self.card2 = NodePath(self.cm2.generate()) self.card2.reparentTo(self.path) self.card2.setPos(0,0,-10) self.card2.setP(-50) self.card1.setTexture(self.tex1) self.card1.setTexScale(TextureStage.getDefault(), self.tex1.getTexScale()) self.card2.setTexture(self.tex2) self.card2.setTexScale(TextureStage.getDefault(), self.tex2.getTexScale()) self.card1.setScale(10) self.card2.setScale(10)
def __init__(self, name, inclination, baseDimension): #public props self.baseDimension = baseDimension tex = loader.loadTexture(resourceManager.getResource(name) + '.png') xscaled = tex.getOrigFileXSize() / self.baseDimension yscaled = tex.getOrigFileYSize() / self.baseDimension cm = CardMaker("unscrollobject") cm.setFrame(0, xscaled, 0, yscaled) ts = TextureStage('ts') ts.setMode(TextureStage.MDecal) uvscroll = UvScrollNode("uvscrollnode", 1, 0.0, 0.0, 0.0) uvscroll.addChild(cm.generate()) self.node = NodePath(uvscroll) self.node.setTwoSided(True) self.node.setX((-xscaled / 2) + 0.5) self.node.setP(-(360 - int(inclination))) self.node.setTexture(tex) self.node.setTransparency(TransparencyAttrib.MAlpha) self.node.reparentTo(render)
def __init__(self, render, loader, location, sizeX, sizeY): self.water = loader.loadModel( 'assets/environment/arctic/nature/water.bam') self.water.setPos(location) self.water.setSx(sizeX) self.water.setSy(sizeY) self.newTS = TextureStage('ts') self.normal_TS = TextureStage('normal') self.normal_TS.setMode(TextureStage.MNormal) self.water.setTexture( self.newTS, loader.loadTexture( 'assets/environment/arctic/nature/textures/water_colormap.jpg') ) self.water.setTexScale(self.newTS, 80) self.water.setTexture( self.normal_TS, loader.loadTexture( 'assets/environment/arctic/nature/textures/water_normalmap.jpg' )) self.water.setTexScale(self.normal_TS, 80) self.water.setShaderAuto() ambiet = AmbientLight('ambient') ambiet.setColor((0.2, 0.2, 0.2, 1)) alight = self.water.attachNewNode(ambiet) self.water.setLight(alight) self.water.reparentTo(render) self.skybox = loader.loadModel( "assets/environment/arctic/nature/skybox.bam") self.skybox.setPos(location) self.skybox.setScale(2000)
def enable(self): camNode = Camera('shadowCam') camNode.setCameraMask(CIGlobals.ShadowCameraBitmask) self.shadowLens = OrthographicLens() self.shadowLens.setFilmSize(60 * 4, 60 * 4) camNode.setLens(self.shadowLens) self.shadowCamArm = camera.attachNewNode('shadowCamArm') self.shadowCam = self.shadowCamArm.attachNewNode(camNode) self.shadowCamArm.setPos(0, 40, 0) self.shadowCam.setPos(0, -40, 0) self.shadowTex = Texture('shadow') self.shadowTex.setBorderColor(self.clearColor) self.shadowTex.setWrapU(Texture.WMBorderColor) self.shadowTex.setWrapV(Texture.WMBorderColor) self.casterState = NodePath('temp') self.casterState.setColorScaleOff(10) self.casterState.setColor(self.shadowColor, self.shadowColor, self.shadowColor, 1, 10) self.casterState.setTextureOff(10) self.casterState.setLightOff(10) self.casterState.setFogOff(10) camNode.setInitialState(self.casterState.getState()) render.hide(CIGlobals.ShadowCameraBitmask) self.shadowStage = TextureStage('shadow') self.shadowStage.setSort(1000) self.turnOnShadows()
def makeTextureMap(self): '''Citymania function that generates and sets the 4 channel texture map''' self.colorTextures = [] for terrain in self.terrains: terrain.getRoot().clearTexture() heightmap = terrain.heightfield() colormap = PNMImage(heightmap.getXSize()-1, heightmap.getYSize()-1) colormap.addAlpha() slopemap = terrain.makeSlopeImage() for x in range(0, colormap.getXSize()): for y in range(0, colormap.getYSize()): # Else if statements used to make sure one channel is used per pixel # Also for some optimization # Snow. We do things funky here as alpha will be 1 already. if heightmap.getGrayVal(x, y) < 200: colormap.setAlpha(x, y, 0) else: colormap.setAlpha(x, y, 1) # Beach. Estimations from http://www.simtropolis.com/omnibus/index.cfm/Main.SimCity_4.Custom_Content.Custom_Terrains_and_Using_USGS_Data if heightmap.getGrayVal(x,y) < 62: colormap.setBlue(x, y, 1) # Rock elif slopemap.getGrayVal(x, y) > 170: colormap.setRed(x, y, 1) else: colormap.setGreen(x, y, 1) colorTexture = Texture() colorTexture.load(colormap) colorTS = TextureStage('color') colorTS.setSort(0) colorTS.setPriority(1) self.colorTextures.append((colorTexture, colorTS))
def __init__(self): fn = Filename.fromOsSpecific(self.filepath) self.terrain = GeoMipTerrain("mySimpleTerrain") self.terrain.setHeightfield("Entities/Maps/heightmap.png") self.terrain.getRoot().setSz(40) #terrain.setBruteforce(True) self.terrain.getRoot().reparentTo(render) # Set terrain properties self.terrain.setBlockSize(16) self.terrain.setNear(500) self.terrain.setFar(100) self.terrain.setFocalPoint(base.camera) # Store the root NodePath for convenience root = self.terrain.getRoot() root.reparentTo(render) # some tinkering """ # tell renderer to repeat texture when reading over the edge. texGrass.setWrapU(Texture.WM_repeat) texGrass.setWrapV(Texture.WM_repeat) # apply mipmapping: tell renderer how to handle multiple texture pixels being rendered t a single screen pixel (makes textures 30% larger in GPU mem.) texGrass.setMinfilter(SamplerState.FT_linear_mipmap_linear) """ self.terrain.generate() """ new attempt to include blend mapping: """ # determine terrain size self.heightmap = self.terrain.heightfield() if self.heightmap.getXSize() > self.heightmap.getYSize(): self.size = self.heightmap.getXSize() - 1 else: self.size = self.heightmap.getYSize() - 1 self.xsize = self.heightmap.getXSize() - 1 self.ysize = self.heightmap.getYSize() - 1 # Set multi texture # Source http://www.panda3d.org/phpbb2/viewtopic.php?t=4536 self.generateSurfaceTextures() # load a blend texture from file: self.blendTexture = loader.loadTexture("Entities/Maps/blendMap.png") self.blendTS = TextureStage('blend') self.blendTS.setSort(0) self.blendTS.setPriority(1) # apply textures to the terrain and connect custom shader for blend mapping: self.setSurfaceTextures() # Add a task to keep updating the terrain (for changing terrain, or synamic resolution) def updateTask(task): self.terrain.update() return task.cont taskMgr.add(updateTask, "update")
def applyNoGlow(np): global NoGlowTS global NoGlowTex if not NoGlowTS: NoGlowTS = TextureStage('noglow') NoGlowTS.setMode(TextureStage.MGlow) if not NoGlowTex: NoGlowTex = loader.loadTexture("phase_3/maps/black.png") np.setTexture(NoGlowTS, NoGlowTex)
def apply(self, instance): if self.texture is None: if self.image is None: self.image = self.generate() self.texture = Texture() self.texture.load(self.image) instance.setTexGen(TextureStage.getDefault(), TexGenAttrib.MPointSprite) instance.setTransparency(TransparencyAttrib.MAlpha, 1) instance.setTexture(TextureStage('ts'), self.texture, 1)
def __apply_Textures(self, recipe, tex_dict): for i, ter_dict in enumerate(recipe['terrains']): tex_img = PNMImage() tex_img.read(Filename("{}/tex/{}".format(recipe['planet_path'], ter_dict['texture']))) tex = Texture() tex.load(tex_img) tex.setMinfilter(Texture.FTLinear) ts = TextureStage(str(i)) ts.setSort(i) self.NP.setTexture(ts, tex, i*10)
def changeDKFrame(self, frame): dk = self.scene.find("hammer1") #remember that the name is wrong here if( frame == 1): dk.setTexOffset(TextureStage.getDefault() , 0.140867 - 0.0446603 ,0.0 ) if( frame == 2): dk.setTexOffset(TextureStage.getDefault() , 0.0431023 - 0.0446603 , 0.806672 - 0.703844 ) if( frame == 3): dk.setTexOffset(TextureStage.getDefault() , 0 ,0.0 ) """
def makeRenderState(material = None, diffuseTexture=None, normalTexture=None, glowTexture=None): n = NodePath("n") if not material: material = makeMaterial((0,0,0,1), (1,1,1,1), (0.01,0.01,0.01,1), 1, (1,1,1,1)) n.setMaterial(material) if diffuseTexture: tsDiffuse = TextureStage('diffuse') tsDiffuse.setMode(TextureStage.MModulate) n.setTexture(tsDiffuse, diffuseTexture) if glowTexture: tsGlow = TextureStage('glow') tsGlow.setMode(TextureStage.MGlow) n.setTexture(tsGlow, glowTexture) if normalTexture: tsNormal = TextureStage('normal') tsNormal.setMode(TextureStage.MNormal) n.setTexture(tsNormal, normalTexture) # weird bugs :| #n.setTransparency(True) #n.setColorOff() return n.getState()
def __init__(self, np, reflectiveness): self.nodePath = np self.stage = TextureStage(self.nodePath.getName() + "-cubemap_stage") self.stage.setPriority(1) self.stage.setMode(TextureStage.MModulate) self.stage.setColor( VBase4(reflectiveness, reflectiveness, reflectiveness, 1.0)) self.nodePath.setTexGen(self.stage, TexGenAttrib.MWorldCubeMap) self.currentCube = None
def patchInvertDDSV(np, tex, debug=False): from panda3d.core import Texture from panda3d.core import TextureStage cmpr = tex.getCompression() if cmpr == Texture.CMDxt1 or cmpr == Texture.CMDxt5: scale2d = np.getTexScale(TextureStage.getDefault()) scale2d[1] = -scale2d[1] np.setTexScale(TextureStage.getDefault(), scale2d) else: if debug: print(" NOT INVERTING.. type was " + str(tex.getCompression()))
def patchInvertDDSV(np,tex,debug=False): from panda3d.core import Texture from panda3d.core import TextureStage cmpr = tex.getCompression() if cmpr == Texture.CMDxt1 or cmpr == Texture.CMDxt5: scale2d = np.getTexScale( TextureStage.getDefault() ) scale2d[1] = -scale2d[1] np.setTexScale( TextureStage.getDefault(), scale2d ) else: if debug: print( " NOT INVERTING.. type was " + str(tex.getCompression()))
def __init__(self, block_index: int, pre_block_socket: BlockSocket, global_network: RoadNetwork, random_seed): super(Block, self).__init__(random_seed) # block information assert self.ID is not None, "Each Block must has its unique ID When define Block" assert self.SOCKET_NUM is not None, "The number of Socket should be specified when define a new block" if block_index == 0: from pgdrive.scene_creator.blocks import FirstBlock assert isinstance(self, FirstBlock), "only first block can use block index 0" elif block_index < 0: logging.debug("It is recommended that block index should > 1") self._block_name = str(block_index) + self.ID self.block_index = block_index self.number_of_sample_trial = 0 # each block contains its own road network and a global network self._global_network = global_network self.block_network = RoadNetwork() # used to spawn npc self._reborn_roads = [] # own sockets, one block derives from a socket, but will have more sockets to connect other blocks self._sockets = [] # used to connect previous blocks, save its info here self._pre_block_socket = pre_block_socket self.pre_block_socket_index = pre_block_socket.index # a bounding box used to improve efficiency x_min, x_max, y_min, y_max self.bounding_box = None # used to create this block, but for first block it is nonsense if block_index != 0: self.positive_lanes = self._pre_block_socket.positive_road.get_lanes(self._global_network) self.negative_lanes = self._pre_block_socket.negative_road.get_lanes(self._global_network) self.positive_lane_num = len(self.positive_lanes) self.negative_lane_num = len(self.negative_lanes) self.positive_basic_lane = self.positive_lanes[-1] # most right or outside lane is the basic lane self.negative_basic_lane = self.negative_lanes[-1] # most right or outside lane is the basic lane self.lane_width = self.positive_basic_lane.width_at(0) if self.render: # render pre-load self.road_texture = self.loader.loadTexture(AssetLoader.file_path("textures", "sci", "color.jpg")) self.road_texture.setMinfilter(SamplerState.FT_linear_mipmap_linear) self.road_texture.setAnisotropicDegree(8) self.road_normal = self.loader.loadTexture(AssetLoader.file_path("textures", "sci", "normal.jpg")) self.ts_color = TextureStage("color") self.ts_normal = TextureStage("normal") self.side_texture = self.loader.loadTexture(AssetLoader.file_path("textures", "side_walk", "color.png")) self.side_texture.setMinfilter(SamplerState.FT_linear_mipmap_linear) self.side_texture.setAnisotropicDegree(8) self.side_normal = self.loader.loadTexture(AssetLoader.file_path("textures", "side_walk", "normal.png")) self.side_walk = self.loader.loadModel(AssetLoader.file_path("models", "box.bam"))
def update_key_map(control_name, control_state, entity, walking): key_map[control_name] = control_state if walking: entity.find('**/+SequenceNode').node().loop(True, 0, 9) else: entity.find('**/+SequenceNode').node().loop(True, 10, 19) if control_name == "left": entity.setTexScale(TextureStage.getDefault(), -1, 1) elif control_name == "right": entity.setTexScale(TextureStage.getDefault(), 1, 1)
def setOwnerTextures(self): self.ownerview = True root = self.terrain.getRoot() root.clearShader() root.clearTexture() cityTexture = Texture() cityTexture.load(self.citymap) cityTS = TextureStage('citymap') cityTS.setSort(0) root.setTexture( self.gridTS, self.gridTexture ) root.setTexScale(self.gridTS, self.terrain.xchunks, self.terrain.ychunks) root.setTexture(cityTS, cityTexture, 1)
def setOwnerTextures(self): self.ownerview = True root = self.terrain.getRoot() root.clearShader() root.clearTexture() cityTexture = Texture() cityTexture.load(self.citymap) cityTS = TextureStage('citymap') cityTS.setSort(0) root.setTexture(self.gridTS, self.gridTexture) root.setTexScale(self.gridTS, self.terrain.xchunks, self.terrain.ychunks) root.setTexture(cityTS, cityTexture, 1)
def flipTexture(self): """ Sets the texture coordinates of the texture to the current frame""" sU = self.offsetX * self.repeatX sV = self.offsetY * self.repeatY oU = 0 + self.frames[self.currentFrame].col * self.uSize oV = 1 - self.frames[self.currentFrame].row * self.vSize - self.offsetY if self.flip['x']: sU *= -1 oU = self.uSize + self.frames[self.currentFrame].col * self.uSize if self.flip['y']: sV *= -1 oV = 1 - self.frames[self.currentFrame].row * self.vSize self.node.setTexScale(TextureStage.getDefault(), sU, sV) self.node.setTexOffset(TextureStage.getDefault(), oU, oV)
def fillTextureStages(self, nodePath): """ Prepares all materials of a given nodepath to have at least the 4 default textures in the correct order: [diffuse, normal, specular, roughness] """ emptyDiffuseTex = loader.loadTexture("Data/Textures/EmptyDiffuseTexture.png") emptyNormalTex = loader.loadTexture("Data/Textures/EmptyNormalTexture.png") emptySpecularTex = loader.loadTexture("Data/Textures/EmptySpecularTexture.png") emptyRoughnessTex = loader.loadTexture("Data/Textures/EmptyRoughnessTexture.png") textureOrder = [emptyDiffuseTex, emptyNormalTex, emptySpecularTex, emptyRoughnessTex] textureSorts = [0, 10, 20, 30] # Prepare the textures for tex in textureOrder: tex.setMinfilter(SamplerState.FTLinear) tex.setMagfilter(SamplerState.FTLinear) tex.setFormat(Texture.FRgba) # Iterate over all geom nodes for np in nodePath.findAllMatches("**/+GeomNode"): # Check how many texture stages the nodepath already has stages = np.findAllTextureStages() numStages = len(stages) # Fill the texture stages up for i in xrange(numStages, 4): stage = TextureStage("DefaultTexStage" + str(i)) stage.setSort(textureSorts[i]) stage.setMode(TextureStage.CMModulate) stage.setColor(Vec4(0, 0, 0, 1)) np.setTexture(stage, textureOrder[i])
def create16To9LogoCard(logoPath, tsName): cm = CardMaker("fade") scale = abs(base.a2dLeft) / 1.7776 cm.setFrame(-1, 1, -1 * scale, 1 * scale) logo = NodePath(cm.generate()) logo.setTransparency(TransparencyAttrib.MAlpha) logoTex = loader.loadTexture(logoPath) logoTs = TextureStage(tsName) logoTs.setMode(TextureStage.MReplace) logo.setTexture(logoTs, logoTex) logo.setBin("fixed", 5000) logo.reparentTo(render2d) logo.hide() return logo
def initSwitchSigns(self): self.switchSigns = [] for i in range(11): cm = CardMaker('card%d'%i) cm.setColor(0,0,0,0) cm.setFrame(-0.5, 0.5, -0.5, 0.5) card = self.level.attachNewNode(cm.generate()) card.setAttrib(TransparencyAttrib.make(TransparencyAttrib.M_alpha)) tex = loader.loadTexture('%d.png'%i) ts = TextureStage('ts') ts.setMode(TextureStage.MReplace) card.setTexture(ts, tex) card.setEffect(BillboardEffect.makePointEye()) card.hide() self.switchSigns.append(card)
def __init__(self): self.enabled = True sMgr = CIGlobals.getSettingsMgr() reso = sMgr.ReflectionQuality[sMgr.getSetting("refl").getValue()] if reso == 0: self.enabled = False return self.waterPlaneNP = None self.waterNodes = [] # Buffer and reflection camera buffer = base.win.makeTextureBuffer('waterBuffer', reso, reso) buffer.setClearColor(Vec4(0, 0, 0, 1)) cfa = CullFaceAttrib.makeReverse() rs = RenderState.make(cfa) self.watercamNP = base.makeCamera(buffer) self.watercamNP.reparentTo(render) self.makePlane(0.0) cam = self.watercamNP.node() cam.getLens().setFov(base.camLens.getFov()) cam.getLens().setNear(1) cam.getLens().setFar(5000) cam.setInitialState(rs) cam.setTagStateKey('Clipped') self.ts0 = TextureStage("tex_0") self.tex0 = buffer.getTexture() self.tex0.setWrapU(Texture.WMClamp) self.tex0.setWrapV(Texture.WMClamp) self.ts1 = TextureStage("tex_1") self.waterTex = loader.loadTexture('phase_3/maps/water_distort.png') self.waterQuad = None self.waterStage = TextureStage("waterStage") image0 = OnscreenImage(image=self.tex0, scale=0.3, pos=(-0.5, 0, 0.7)) image1 = OnscreenImage(image=waterTex, scale=0.3, pos=(0.5, 0, 0.7)) taskMgr.add(self.update, "waterTask")
def apply_panda(self, shape, texture, texture_lod): texture_stage = TextureStage(shape.str_id() + self.__class__.__name__) self.init_texture_stage(texture_stage, texture) if self.tex_matrix: shape.set_texture_to_lod(self, texture_stage, texture_lod, self.source.is_patched()) shape.instance.setTexture(texture_stage, texture, 1)
def on_pick(self): if not self._update_pick_ray(): return # traverse scene graph and determine nearest selection (if pickable) self.pick_traverser.traverse(self.board_renderer.base.render) self.pick_queue.sortEntries() if not self.pick_queue.getNumEntries(): return node = self.pick_queue.getEntry(0).getIntoNodePath().findNetTag('pickable') if node.isEmpty() or node.getTag('pickable') == 'False': return # add some color ts = TextureStage('ts') ts.setMode(TextureStage.MModulate) colors = list(Game.player_colors) colors.remove('white') node.setTexture(ts, self.board_renderer.tileset.load_texture('textures/player%s.png' % random.choice(colors).capitalize()))
def playVideo(self, video): # check if it is loadable try: # load the video texture self.tex = MovieTexture("MovieTexture") #print video self.tex.read(video) # Set up a fullscreen card to set the video texture on it. cm = CardMaker("Movie Card") cm.setFrameFullscreenQuad() cm.setUvRange(self.tex) self.card = NodePath(cm.generate()) self.card.reparentTo(base.render2d) self.card.setTexture(self.tex) self.card.setTexScale(TextureStage.getDefault(), self.tex.getTexScale()) # load the video self.sound = loader.loadSfx(video) # Synchronize the video to the sound. self.tex.synchronizeTo(self.sound) # play the video and audio self.sound.play() # start the task which checks if the video is finished taskMgr.add(self.isVideoFinish, "task_isVideoFinised") except: logging.error("Failed to load video: %s %s", video, sys.exc_info()) self.stopVideo() base.messenger.send(self.vidFinEvt)
def loadFlatQuad(self, fullFilename): cm = CardMaker('cm-%s' % fullFilename) cm.setColor(1.0, 1.0, 1.0, 1.0) aspect = base.camLens.getAspectRatio() htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH) htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT) cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0) bottomRightX = WEB_WIDTH_PIXELS / float(WEB_WIDTH + 1) bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1) cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1)) card = cm.generate() quad = NodePath(card) jpgFile = PNMImage(WEB_WIDTH, WEB_HEIGHT) smallerJpgFile = PNMImage() readFile = smallerJpgFile.read(Filename(fullFilename)) if readFile: jpgFile.copySubImage(smallerJpgFile, 0, 0) guiTex = Texture('guiTex') guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) guiTex.setMinfilter(Texture.FTLinear) guiTex.load(jpgFile) guiTex.setWrapU(Texture.WMClamp) guiTex.setWrapV(Texture.WMClamp) ts = TextureStage('webTS') quad.setTexture(ts, guiTex) quad.setTransparency(0) quad.setTwoSided(True) quad.setColor(1.0, 1.0, 1.0, 1.0) result = quad else: result = None Texture.setTexturesPower2(1) return result
def setupTexture(self): cm = CardMaker('quadMaker') cm.setColor(1.0, 1.0, 1.0, 1.0) aspect = base.camLens.getAspectRatio() htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH) htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT) cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0) bottomRightX = WEB_WIDTH_PIXELS / float(WEB_WIDTH + 1) bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1) cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1)) card = cm.generate() self.quad = NodePath(card) self.quad.reparentTo(self.parent_) self.guiTex = Texture('guiTex') self.guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) self.guiTex.setMinfilter(Texture.FTLinear) self.guiTex.setKeepRamImage(True) self.guiTex.makeRamImage() self.guiTex.setWrapU(Texture.WMRepeat) self.guiTex.setWrapV(Texture.WMRepeat) ts = TextureStage('webTS') self.quad.setTexture(ts, self.guiTex) self.quad.setTexScale(ts, 1.0, -1.0) self.quad.setTransparency(0) self.quad.setTwoSided(True) self.quad.setColor(1.0, 1.0, 1.0, 1.0) self.calcMouseLimits()
def __init__(self, texture_cube, window_size=512, texture_size=512): super().__init__() self.cube_ind = 0 self.num_slices = texture_cube.shape[0] self.cube = texture_cube # SET Frame rate ShowBaseGlobal.globalClock.setMode(ClockObject.MLimited) ShowBaseGlobal.globalClock.setFrameRate(40) #can lock this at #Create texture stage self.texture = Texture("Stimulus") # self.texture.setMagfilter(SamplerState.FT_nearest) # self.texture.setMinfilter(SamplerState.FT_nearest) self.texture.setup2dTexture(texture_size, texture_size, Texture.T_unsigned_byte, Texture.F_luminance) self.texture.setRamImageAs(self.cube[0, :, :], "L") self.textureStage = TextureStage("Stimulus") #Create scenegraph cm = CardMaker('card1') cm.setFrameFullscreenQuad() self.card1 = self.aspect2d.attachNewNode(cm.generate()) self.card1.setTexture(self.textureStage, self.texture) #ts, tx ShowBaseGlobal.base.setFrameRateMeter(True) self.taskMgr.add(self.setTextureTask, "setTextureTask")
def __init__(self): ShowBase.__init__(self) scene = base.loader.load_model('lightmap.test.egg') scene.set_x(1) scene.set_z(0) scene.set_scale(10) scene.reparent_to(render) render.set_shader_auto() ts = TextureStage("lightmap") lightmap = base.loader.load_texture("tex/ligtmap.png") ts.setTexcoordName("lightmap") scene.set_texture(ts, lightmap)
def applySettings(self, jsonfile): if not jsonfile: raise IOError('no file specified!') info = open(jsonfile, 'r') jsonInfo = json.load(info) settings = jsonInfo['settings'] width, height = settings['resolution'] fs = settings['fullscreen'] music = settings['music'] sfx = settings['sfx'] tex_detail = settings['texture-detail'] model_detail = settings['model-detail'] aa = settings['aa'] af = settings.get('af', None) if af == None: self.writeSettingToFile('af', 'off', 'settings.json') base.enableMusic(music) base.enableSoundEffects(sfx) if aa == 'on': render.set_antialias(AntialiasAttrib.MMultisample) aspect2d.set_antialias(AntialiasAttrib.MMultisample) else: render.clear_antialias() ts = TextureStage('ts') if tex_detail == 'high': pass else: if tex_detail == 'low': loadPrcFileData('', 'compressed-textures 1') wp = WindowProperties() wp.setSize(width, height) wp.setFullscreen(fs) base.win.requestProperties(wp) info.close() return
def enterShow(self, ts=0): self.darkenInterior() self.cr.playGame.hood.loader.interiorMusic.stop() videoFile = CinemaGlobals.Cinemas[self.cinemaIndex][0] audioFile = CinemaGlobals.Cinemas[self.cinemaIndex][1] self.movieTex = MovieTexture(self.uniqueName("movieTex")) self.movieTex.read(videoFile) card = CardMaker(self.uniqueName('movieCard')) card.setFrame(-1.5, 1.5, -1, 1) self.movieCard = NodePath(card.generate()) self.movieCard.reparentTo(render) self.movieCard.setPos( self.interior.find('**/sign_origin;+s').getPos(render)) #self.movieCard.setX(self.movieCard, -0.05) self.movieCard.setHpr( self.interior.find('**/sign_origin;+s').getHpr(render)) self.movieCard.setDepthWrite(1, 1) self.movieCard.setTwoSided(True) self.movieCard.setTexture(self.movieTex) self.movieCard.setTexScale(TextureStage.getDefault(), self.movieTex.getTexScale()) self.movieCard.setScale(2.5) self.movieSound = base.loadSfx(audioFile) self.movieTex.synchronizeTo(self.movieSound) self.movieTrack = SoundInterval(self.movieSound, name=self.uniqueName('movieTrack')) self.movieTrack.setDoneEvent(self.movieTrack.getName()) self.acceptOnce(self.movieTrack.getDoneEvent(), self.fsm.request, ['off']) self.movieTrack.start(ts)
def createFadeableImage(img, tsName, big=False): cm = CardMaker("FadableCard") cm.setFrame(-1, 1, -1, 1) image = NodePath(cm.generate()) image.setTransparency(TransparencyAttrib.MAlpha) imageTex = loader.loadTexture(img) imageTs = TextureStage(tsName) imageTs.setMode(TextureStage.MReplace) image.setTexture(imageTs, imageTex) image.reparentTo(render2d) if big: image.setScale(0.75) else: image.setScale(0.5) image.setPos(0, 0, 0.25) image.hide() return image
def createGround(self, terrainData): """Create ground using a heightmap""" # Create heightfield for physics heightRange = terrainData["heightRange"] # Image needs to have dimensions that are a power of 2 + 1 heightMap = PNMImage(self.basePath + terrainData["elevation"]) xdim = heightMap.getXSize() ydim = heightMap.getYSize() shape = BulletHeightfieldShape(heightMap, heightRange, ZUp) shape.setUseDiamondSubdivision(True) np = self.outsideWorldRender.attachNewNode(BulletRigidBodyNode("terrain")) np.node().addShape(shape) np.setPos(0, 0, 0) self.physicsWorld.attachRigidBody(np.node()) # Create graphical terrain from same height map terrain = GeoMipTerrain("terrain") terrain.setHeightfield(heightMap) terrain.setBlockSize(32) terrain.setBruteforce(True) rootNP = terrain.getRoot() rootNP.reparentTo(self.worldRender) rootNP.setSz(heightRange) offset = xdim / 2.0 - 0.5 rootNP.setPos(-offset, -offset, -heightRange / 2.0) terrain.generate() # Apply texture diffuse = self.loader.loadTexture(Filename(self.basePath + terrainData["texture"])) diffuse.setWrapU(Texture.WMRepeat) diffuse.setWrapV(Texture.WMRepeat) rootNP.setTexture(diffuse) textureSize = 6.0 ts = TextureStage.getDefault() rootNP.setTexScale(ts, xdim / textureSize, ydim / textureSize) # Create planes around area to prevent player flying off the edge # Levels can define barriers around them but it's probably a good # idea to leave this here just in case sides = ( (Vec3(1, 0, 0), -xdim / 2.0), (Vec3(-1, 0, 0), -xdim / 2.0), (Vec3(0, 1, 0), -ydim / 2.0), (Vec3(0, -1, 0), -ydim / 2.0), ) for sideNum, side in enumerate(sides): normal, offset = side sideShape = BulletPlaneShape(normal, offset) sideNode = BulletRigidBodyNode("side%d" % sideNum) sideNode.addShape(sideShape) self.physicsWorld.attachRigidBody(sideNode)
def _load_chairs(self): """Load and place chairs""" self.chairs = self.p_constants["NPHILOSOPHERS"] * [0] for i in xrange(self.p_constants["NPHILOSOPHERS"]): x, y, angle = self._get_chair_coord(i, 5.0) self.chairs[i] = self._load_model( "chair1", scale=[7, 7, 7], pos=[x, y - 1, 0], H=rad2deg(angle) + 15) self.chairs[i].setTexture(self.chair_tex) self.chairs[i].setTexScale( TextureStage.getDefault(), 0.005, 0.005)
def loadBallModel(self): #loads the character, a ball model #ballModelStartPos = (-8, -8, 0.701) #THIS IS THE END ballModelStartPos = (8, 8, 13.301) #level 0 ballScale = 0.01 self.ballModel = loader.loadModel("/Users/jianwei/Documents/School/Freshman/Semester1/15-112/TERMPROJECT/Project/ball") self.ballModel.reparentTo(render) self.ballModel.setScale(ballScale) self.ballModel.setPos(ballModelStartPos) ### Setting ball texture ### texScale = 0.08 self.ballModel.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) self.ballModel.setTexProjector(TextureStage.getDefault(), render, self.ballModel) self.ballModel.setTexScale(TextureStage.getDefault(), texScale) tex = loader.load3DTexture('/Users/jianwei/Documents/School/Freshman/Semester1/15-112/TERMPROJECT/Project/ballTex/ballTex_#.png') self.ballModel.setTexture(tex)
def __init__(self, bulletWorld): self.sky = SkyDome() # model used as collision mesh collisionModel = loader.loadModel('models/walledTrack') # model used as display model model = loader.loadModel('models/FullTrack') tex = loader.loadTexture("models/tex/Main.png") ts = TextureStage('ts') ts.setMode(TextureStage.MBlend) model.setTexture(ts, tex, 2) #model.setTexScale(ts, 70) # renders track from two camera views model.setTwoSided(True) mesh = BulletTriangleMesh() for geomNP in collisionModel.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNP.getTransform(collisionModel) for geom in geomNode.getGeoms(): mesh.addGeom(geom, ts) shape = BulletTriangleMeshShape(mesh, dynamic=False) self.rigidNode = BulletRigidBodyNode('Track') self.rigidNode.notifyCollisions(False) np = render.attachNewNode(self.rigidNode) np.node().addShape(shape) model.reparentTo(np) np.setScale(70) np.setPos(0, 0, -5) np.setCollideMask(BitMask32(0xf0)) np.node().notifyCollisions(False) bulletWorld.attachRigidBody(np.node()) self.hf = np.node() # To enable/disable debug visualisation
def _load_bowls(self): """Load and place bowls""" self.bowls = [{} for x in xrange(self.p_constants["NPHILOSOPHERS"])] for i in xrange(self.p_constants["NPHILOSOPHERS"]): x, y, angle = self._get_chair_coord(i, 3.6) self.bowls[i]["bowl"] = self._load_model( "bowl", scale=[2, 2, 2], pos=[100, 100, 100], H=rad2deg(angle)) self.bowls[i]["pos"] = [x, y - 1, self.fork_height] self.bowls[i]["num_up"] = 0 self.bowls[i]["meals"] = 0 self.bowls[i]["bowl"].setTexture(self.bowl_tex) self.bowls[i]["bowl"].setTexScale( TextureStage.getDefault(), 0.005, 0.005)
def terrainFromHeightMap(self, main): self.parentNodePath = NodePath("FloorNodePath") self.parentNodePath.setPos(0, 0, -2) self.parentNodePath.setScale(5, 5, 0.75) # Heightfield (static) height = 8.0 img = PNMImage(Filename('models/elevation.png')) xdim = img.getXSize() ydim = img.getYSize() shape = BulletHeightfieldShape(img, height, ZUp) shape.setUseDiamondSubdivision(True) self.rigidNode = BulletRigidBodyNode('Heightfield') self.rigidNode.notifyCollisions(False) self.rigidNodePath = self.parentNodePath.attachNewNode(self.rigidNode) self.rigidNodePath.node().addShape(shape) self.rigidNodePath.setPos(0, 0, 0) self.rigidNodePath.setCollideMask(BitMask32.allOn()) self.rigidNodePath.node().notifyCollisions(False) main.world.attachRigidBody(self.rigidNodePath.node()) self.hf = self.rigidNodePath.node() # To enable/disable debug visualisation self.terrain = GeoMipTerrain('terrain') self.terrain.setHeightfield(img) self.terrain.setBlockSize(32) self.terrain.setNear(50) self.terrain.setFar(100) self.terrain.setFocalPoint(base.camera) rootNP = self.terrain.getRoot() rootNP.reparentTo(self.parentNodePath) rootNP.setSz(8.0) offset = img.getXSize() / 2.0 - 0.5 rootNP.setPos(-offset, -offset, -height / 2.0) self.terrain.generate() # Apply texture diffuseTexture = loader.loadTexture(Filename('models/diffuseMap.jpg')) diffuseTexture.setWrapU(Texture.WMRepeat) diffuseTexture.setWrapV(Texture.WMRepeat) rootNP.setTexture(diffuseTexture) # Normal map texStage = TextureStage('texStageNormal') texStage.setMode(TextureStage.MNormal) normalTexture = loader.loadTexture(Filename('models/normalMap.jpg')) rootNP.setTexture(texStage, normalTexture) # Glow map texStage = TextureStage('texStageNormal') texStage.setMode(TextureStage.MGlow) glowTexture = loader.loadTexture(Filename('models/glowMap.jpg')) rootNP.setTexture(texStage, glowTexture)
def __init__(self,conf): self.p3dobject=self.gmap.tile_matrix_node.attachNewNode('tile_'+str(conf['eid'])) self.p3dobject.setTransparency(TransparencyAttrib.MAlpha) #self.test_sphere=loader.loadModel('data/models/test_sphere.egg') #self.test_sphere.reparentTo(self.p3dobject) GEntity.__init__(self,conf) self.x,self.y=x,y=conf['x'],conf['y'] self.p3dobject.setTag('x',str(x)) self.p3dobject.setTag('y',str(y)) self.p3dobject.setPythonTag('ref',self) #half of a tile side t=self.gmap.tile_matrix_node.getScale()[0]/2. self.p3dobject.setPos(self.gmap.tile_matrix_node,(-self.gmap.resx/2.+x+t)*2.,(y-self.gmap.resy/2.+t)*2.,0) #preload texture holder quad self.quad=GTile.resources['quad']() self.quad.setTransparency(TransparencyAttrib.MAlpha) #self.quad.reparentTo(self.p3dobject) self.quad.reparentTo(self.gmap.tiles_quads_node) self.quad.setPos(self.p3dobject.getPos()) self.quad.hide() #pid of the player that owns the tile self.pawner=None self.ts_pawn=TextureStage('ts_pawn') self.ts_pawn.setMode(TextureStage.MReplace) self.ts_pawn.setSort(2) #selection self.is_selected=False self.ts_selected=TextureStage('ts_selected') self.ts_selected.setMode(TextureStage.MReplace) self.ts_selected.setSort(3) #highlight self.is_highlighted=False self.ts_highlighted=TextureStage('ts_highlighted') self.ts_highlighted.setMode(TextureStage.MDecal) self.ts_highlighted.setSort(4)
def __init__(self): ShowBase.__init__(self) # self.wp = WindowProperties() self.wp.setSize(1280, 720) base.win.requestProperties(self.wp) self.fork_height = 2.3 self.frame_time = 0.0 self.textObject = OnscreenText(text='', pos=(-1.0, 0.9), scale = 0.10, fg=(255, 255, 255, 200)) # create sockets, get h constants self.p_constants = get_constants() self.context, self.socket = self._create_socket_context() # Load textures self.bowl_tex = self.loader.loadTexture( ASSETS_DIR + "marble.jpg") self.wood_tex = self.loader.loadTexture( ASSETS_DIR + "derevo_mebel.jpg") self.chair_tex = self.loader.loadTexture( ASSETS_DIR + "02_1.bmp") self.black_tex = self.loader.loadTexture(ASSETS_DIR + "black.png") # Load models # Load environment (really just a plane) self.environ = self._load_model( "house", scale=[25, 25, 25], pos=[0, 0, -10]) # Load the "table" self.table = self._load_model( "round_table", scale=[27, 27, 14], pos=[0, 0, 0]) # Load and place forks, chairs self._load_forks() self._load_chairs() self._load_bowls() # Apply textures to models self.environ.setTexture(self.black_tex) self.table.setTexture(self.wood_tex) self.table.setTexScale( TextureStage.getDefault(), 0.005, 0.005) # Start sim self.rnum = 0 self.philos = subprocess.Popen("./philos", shell=True) # Tasks self.taskMgr.add(self.spin_camera, "spin_camera") self.taskMgr.add(self._comm, "comm")
def __init__(self, name, bodyDB): Body.__init__(self, name, bodyDB) self.mesh.reparentTo(render) self.spectral = bodyDB['spectral'] # We use the data from the spectral database to properly color our star. color = colorDatabase[self.spectral] self.mesh.setColor(color[0]/255.0,color[1]/255.0,color[2]/255.0,1) # We will use a point light to cast our main light self.light = self.mesh.attachNewNode( PointLight( "sunPointLight" ) ) # Color is set by spectral type. THIS IS NOT PROPER BLACKBODY! self.light.node().setColor( Vec4(color[0]/255.0,color[1]/255.0,color[2]/255.0,1) ) # Attenuation controls how the light fades with distance. The numbers are # The three values represent the three constants (constant, linear, and # quadratic) in the internal lighting equation. The higher the numbers the # shorter the light goes. #self.light.node().setAttenuation( Vec3( .1, 0.04, 0.0 ) ) texture1 = loader.loadTexture('sun_1k_tex.jpg') ts1 = TextureStage('textures1') ts1.setMode(TextureStage.MGlow) self.mesh.setTexture(ts1, texture1) render.setLight( self.light ) starlights.append(self.light)
def loadWallModel(self): #loads the wall model (the maze) wallScale = 0.3 wallModelName = self.randomWallModel() #randomly select a maze self.wallModel = loader.loadModel(wallModelName) self.wallModel.setScale(wallScale) self.wallModel.setPos(0, 0, 0) self.wallModel.setCollideMask(BitMask32.allOff()) self.wallModel.reparentTo(render) ### Setting Texture ### texScale = 0.08 self.wallModel.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldNormal) self.wallModel.setTexProjector(TextureStage.getDefault(), render, self.wallModel) self.wallModel.setTexScale(TextureStage.getDefault(), texScale) tex = loader.load3DTexture('/Users/jianwei/Documents/School/Freshman/Semester1/15-112/TERMPROJECT/Project/wallTex/wallTex_#.png') self.wallModel.setTexture(tex) #creating visual geometry collision self.wallModel.setCollideMask(BitMask32.bit(0))
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
def regionViewFound(self): '''Gui for founding a new city!''' self.setOwnerTextures() root = self.terrain.getRoot() task = taskMgr.add(self.newTerrainOverlay, "newTerrainOverlay") tileTexture = loader.loadTexture("Textures/tile.png") tileTexture.setWrapU(Texture.WMClamp) tileTexture.setWrapV(Texture.WMClamp) self.tileTS = TextureStage('tile') self.tileTS.setSort(6) self.tileTS.setMode(TextureStage.MDecal) #self.tileTS.setColor(Vec4(1,0,1,1)) root.setTexture(self.tileTS, tileTexture) root.setTexScale(self.tileTS, self.terrain.xchunks, self.terrain.ychunks) self.acceptOnce("mouse1", self.regionViewFound2) self.acceptOnce("escape", self.cancelRegionViewFound)
def loadIcon(self, iconsFile, name): retVal = iconsFile.find(name) retVal.setBillboardAxis() retVal.reparentTo(self) dark = retVal.copyTo(NodePath()) dark.reparentTo(retVal) dark.setColor(0.5, 0.5, 0.5, 1) retVal.setEffect(DecalEffect.make()) retVal.setTransparency(TransparencyAttrib.MAlpha, 1) ll, ur = dark.getTightBounds() center = retVal.attachNewNode('center') center.setPos(0, 0, ll[2]) dark.wrtReparentTo(center) dark.setTexProjector(TextureStage.getDefault(), center, retVal) retVal.hide() return (retVal, center)