def __createBuffer(self): ''' create the buffer we render in the background into ''' print "I: TexturePainter.__createBuffer" # the window has been modified if WindowManager.activeWindow: # on window resize there seems to be never a active window win = WindowManager.activeWindow.win else: win = base.win # get the window size self.windowSizeX = win.getXSize() self.windowSizeY = win.getYSize() # create a buffer in which we render the model using a shader self.paintMap = Texture() # 1.5.4 cant handle non power of 2 buffers self.modelColorBuffer = createOffscreenBuffer( -3, TEXTUREPAINTER_BACKGROUND_BUFFER_RENDERSIZE[0], TEXTUREPAINTER_BACKGROUND_BUFFER_RENDERSIZE[1] ) #self.windowSizeX, self.windowSizeY) self.modelColorBuffer.addRenderTexture(self.paintMap, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) self.modelColorCam = base.makeCamera(self.modelColorBuffer, lens=base.cam.node().getLens(), sort=1) # Create a small buffer for the shader program that will fetch the point from the texture made # by the self.modelColorBuffer self.colorPickerImage = PNMImage() self.colorPickerTex = Texture() self.colorPickerBuffer = base.win.makeTextureBuffer( "color picker buffer", 2, 2, self.colorPickerTex, True) self.colorPickerScene = NodePath('color picker scene') self.colorPickerCam = base.makeCamera(self.colorPickerBuffer, lens=base.cam.node().getLens(), sort=2) self.colorPickerCam.reparentTo(self.colorPickerScene) self.colorPickerCam.setY(-2) cm = CardMaker('color picker scene card') cm.setFrameFullscreenQuad() pickerCard = self.colorPickerScene.attachNewNode(cm.generate()) loadPicker = NodePath(PandaNode('pointnode')) loadPicker.setShader(Shader.make(COLOR_PICKER_SHADER), 10001) # Feed the paintmap from the paintBuffer to the shader and initial mouse positions self.colorPickerScene.setShaderInput('paintmap', self.paintMap) self.colorPickerScene.setShaderInput('mousepos', 0, 0, 0, 1) self.colorPickerCam.node().setInitialState(loadPicker.getState())
def setupRightTexture(self): cm = CardMaker('quadMaker') cm.setColor(1.0, 1.0, 1.0, 1.0) aspect = base.camLens.getAspectRatio() htmlWidth = 2.0 * aspect * WEB_WIDTH / float(WIN_WIDTH) htmlHeight = 2.0 * float(WEB_HEIGHT) / float(WIN_HEIGHT) # the html area will be center aligned and vertically top aligned #cm.setFrame(-htmlWidth/2.0, htmlWidth/2.0, 1.0 - htmlHeight, 1.0) cm.setFrame(0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0) card = cm.generate() self.rightQuad = NodePath(card) self.rightQuad.reparentTo(self.parent) self.rightGuiTex = Texture("guiTex") self.rightGuiTex.setupTexture(Texture.TT2dTexture, WEB_HALF_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) self.rightGuiTex.setKeepRamImage(True) self.rightGuiTex.makeRamImage() self.rightGuiTex.setWrapU(Texture.WMClamp) self.rightGuiTex.setWrapV(Texture.WMClamp) ts = TextureStage('rightWebTS') self.rightQuad.setTexture(ts, self.rightGuiTex) self.rightQuad.setTexScale(ts, 1.0, -1.0) self.rightQuad.setTransparency(0) self.rightQuad.setTwoSided(True) self.rightQuad.setColor(1.0, 1.0, 1.0, 1.0)
def _createMaskTextureCard(self): """ This will return a NodePath with a card textured with the map mask. It also creates several other members that re needed to change the mask. """ # create and fill empty mask image self._maskImage = PNMImage(self._maskResolution, self._maskResolution, 4) for x in range(self._maskResolution): for y in range(self._maskResolution): #maskImage.setXel(x,y,mapImage.getRed(x/13,y/10),mapImage.getGreen(x/13,y/10),mapImage.getBlue(x/13,y/10)) self._maskImage.setXelA(x,y,0,0,0,1) # create the texture for the mask self.maskTexture = Texture("maskTexture") self.maskTexture.setupTexture(Texture.TT2dTexture, self._maskResolution, self._maskResolution, 1, Texture.TUnsignedByte, Texture.FRgba) self.maskTexture.setMinfilter(Texture.FTLinear) self.maskTexture.setWrapU(Texture.WMClamp) self.maskTexture.setWrapV(Texture.WMClamp) self.maskTexture.load(self._maskImage) base.graphicsEngine.renderFrame() # put the mask texture on a card and return it cm = CardMaker("mask_cardMaker") cm.setFrame(-1.0,1.0,-1.0,1.0) mask = self.attachNewNode(cm.generate()) mask.setTexture(self.maskTexture, 1) mask.setTransparency(1) return mask
def get_heightmap_tex(self, size, filename=None): """Generate texture of map """ mod = self.world_size / size image = PNMImage(size, size) for x in xrange(size): for y in xrange(size): px = x * mod py = y * mod height = self[px, py] color = height / 50 r = 0 g = 0 b = 0 if color > 255: color = 255 if color < 0: color = abs(color) b = color else: g = color image.setPixel(x, y, (r, g, b)) if filename != None: image.write(filename) #for x in xrange(-1, 2): #for y in xrange(-1, 2): #image.setPixel(int(world.chunks_map.charX)+x, int(world.chunks_map.charY)+y, (255, 0, 0)) texture = Texture() texture.load(image) return texture
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 _createMapTextureCard(self): mapImage = PNMImage(MAP_RESOLUTION, MAP_RESOLUTION) mapImage.fill(*self._bgColor) fgColor = VBase4D(*self._fgColor) for x in range(self._mazeHeight): for y in range(self._mazeWidth): if self._mazeCollTable[y][x] == 1: ax = float(x) / self._mazeWidth * MAP_RESOLUTION invertedY = self._mazeHeight - 1 - y ay = float(invertedY) / self._mazeHeight * MAP_RESOLUTION self._drawSquare(mapImage, int(ax), int(ay), 10, fgColor) mapTexture = Texture('mapTexture') mapTexture.setupTexture(Texture.TT2dTexture, self._maskResolution, self._maskResolution, 1, Texture.TUnsignedByte, Texture.FRgba) mapTexture.setMinfilter(Texture.FTLinear) mapTexture.load(mapImage) mapTexture.setWrapU(Texture.WMClamp) mapTexture.setWrapV(Texture.WMClamp) mapImage.clear() del mapImage cm = CardMaker('map_cardMaker') cm.setFrame(-1.0, 1.0, -1.0, 1.0) map = self.attachNewNode(cm.generate()) map.setTexture(mapTexture, 1) return map
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 enable(self): ''' Enables the filter. It is assumed that after this operation the rendering operation has been altered such that the filter effects will be visible. ''' if self.isEnabled(): return shader = self.game.getResources().loadShader(self.shader) if shader is not None: self.postProcess = FilterManager( self.game.getView().getWindow(), self.game.getView().panoRenderer.getCamera()) self.postProcess.windowEvent(self.game.getView().getWindow( )) # auto resize buffers when window resizes tex = Texture() self.screenQuad = self.postProcess.renderSceneInto(colortex=tex) self.screenQuad.setShader(shader) self.screenQuad.setShaderInput("tex", tex) self._applyShaderInputs() self.enabled = True else: self.log.error( 'failed to set screen filter BlackAndWhite because shader %s was not found' % self.shader)
def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None): if textures: colortex = textures.get('color', None) depthtex = textures.get('depth', None) auxtex = textures.get('aux', None) if colortex == None: colortex = Texture('filter-base-color') colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup = (depthtex, colortex, auxtex, None) (winx, winy) = self.getScaledSize(1, 1, 1) buffer = self.createBuffer('filter-base', winx, winy, texgroup) if buffer == None: return None cm = CardMaker('filter-base-quad') cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(Vec4(1, 0.5, 0.5, 1)) cs = NodePath('dummy') cs.setState(self.camstate) if auxbits: cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) self.camera.node().setInitialState(cs.getState()) quadcamnode = Camera('filter-quad-cam') lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) dr = buffer.getDisplayRegion(0) self.setStackedClears(dr, self.rclears, self.wclears) if auxtex: dr.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) dr.setClearValue(GraphicsOutput.RTPAuxRgba0, Vec4(0.5, 0.5, 1.0, 0.0)) self.region.disableClears() if self.isFullscreen(): self.win.disableClears() dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1, 1, 1)) return quad
def loadFlatQuad(self, fullFilename): """Load the flat jpg into a quad.""" assert self.notify.debugStateCall(self) #Texture.setTexturesPower2(AutoTextureScale.ATSUp) #Texture.setTexturesPower2(2) 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) # the html area will be center aligned and vertically top aligned #cm.setFrame(-htmlWidth/2.0, htmlWidth/2.0, 1.0 - htmlHeight, 1.0) 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,0), Point2(bottomRightX, bottomRightY)) cm.setUvRange(Point2(0,1-bottomRightY), Point2(bottomRightX,1)) card = cm.generate() quad = NodePath(card) #quad.reparentTo(self.parent) 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.setKeepRamImage(True) #guiTex.makeRamImage() guiTex.setWrapU(Texture.WMClamp) guiTex.setWrapV(Texture.WMClamp) ts = TextureStage('webTS') quad.setTexture(ts, guiTex) #quad.setTexScale(ts, 1.0, -1.0) quad.setTransparency(0) quad.setTwoSided(True) quad.setColor(1.0, 1.0, 1.0, 1.0) result= quad else: # if we have an error loading the file, return None to signify an error result = None #Texture.setTexturesPower2(AutoTextureScale.ATSDown) Texture.setTexturesPower2(1) return result
def __init__(self, scene=base.render, ambient=0.2, hardness=16, fov=40, near=10, far=100): """Create an instance of this class to initiate shadows. Also, a shadow casting 'light' is created when this class is called. The first parameter is the nodepath in the scene where you want to apply your shadows on, by default this is render.""" # Read and store the function parameters self.scene = scene self.__ambient = ambient self.__hardness = hardness # By default, mark every object as textured. self.flagTexturedObject(self.scene) # Create the buffer plus a texture to store the output in buffer = createOffscreenBuffer(-3) depthmap = Texture() buffer.addRenderTexture(depthmap, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) # Set the shadow filter if it is supported if (base.win.getGsg().getSupportsShadowFilter()): depthmap.setMinfilter(Texture.FTShadow) depthmap.setMagfilter(Texture.FTShadow) # Make the camera self.light = base.makeCamera(buffer) self.light.node().setScene(self.scene) self.light.node().getLens().setFov(fov) self.light.node().getLens().setNearFar(near, far) # Put a shader on the Light camera. lci = NodePath(PandaNode("lightCameraInitializer")) lci.setShader(loader.loadShader("caster.sha")) self.light.node().setInitialState(lci.getState()) # Put a shader on the Main camera. mci = NodePath(PandaNode("mainCameraInitializer")) mci.setShader(loader.loadShader("softshadow.sha")) base.cam.node().setInitialState(mci.getState()) # Set up the blurring buffers, one that blurs horizontally, the other vertically #blurXBuffer = makeFilterBuffer(buffer, "Blur X", -2, loader.loadShader("blurx.sha")) #blurYBuffer = makeFilterBuffer(blurXBuffer, "Blur Y", -1, loader.loadShader("blury.sha")) # Set the shader inputs self.scene.setShaderInput("light", self.light) #self.scene.setShaderInput("depthmap", blurYBuffer.getTexture()) self.scene.setShaderInput("depthmap", buffer.getTexture()) self.scene.setShaderInput("props", ambient, hardness, 0, 1)
def __destroyPreview(self): """Destroys the preview.""" if self.previewBuffer != None: base.graphicsEngine.removeWindow(self.previewBuffer) if self.previewCamera != None: self.previewCamera.node().setActive(False) self.preview.Destroy() self.preview = None self.previewBuffer = None self.previewCamera = None self.previewPlane.removeNode() self.previewPlane = None self.previewTexture = Texture() self.Layout()
def get_map_3d_tex(self, size, filename=None, charPos=None): """Generate texture of map """ mod = self.world_size / size image = PNMImage(size, size) for x in xrange(size): for y in xrange(size): px = x * mod py = y * mod height = self[px, py] if height <= 0: color = (abs(height) / 50) + 50 if color > 255: color = 255 image.setPixel(x, y, (0, 0, 255 - color)) else: if height <= self.config.low_mount_level[1]: color = height / 20 r = 0 g = 50 + color b = 0 image.setPixel(x, y, (r, g, b)) elif height > self.config.low_mount_level[1]: color = height / 50 r = color g = color b = color if r > 255: r = 255 if g > 255: r = 255 if b > 255: b = 255 image.setPixel(x, y, (r, g, b)) if filename != None: image.write(filename) if charPos != None: charX, charY = charPos for x in xrange(-1, 2): for y in xrange(-1, 2): image.setPixel( int(charX / mod) + x, int(charY / mod) + y, (255, 0, 0)) texture = Texture() texture.load(image) return texture
def get_map_2d_tex(self, map2d, factor=1): """Generate texture for map2d, factor - for size [size / factor] """ size = map2d.size / factor image = PNMImage(size, size) for x in xrange(size): for y in xrange(size): px = x * factor py = y * factor if map2d[(px, py)] <= map2d.water_z: image.setPixel(x, y, (0, 0, 100)) else: image.setPixel(x, y, (0, 100, 0)) texture = Texture() texture.load(image) return texture
def _createMapTextureCard(self): """ This will return a NodePath with a card textured with the minimap. The minimap texture is dynamically created from the map data. """ # create and fill empty map image mapImage = PNMImage(MAP_RESOLUTION, MAP_RESOLUTION) blockFiles = [] for i in range(5): blockFiles.append(PNMImage()) #blockFiles[i].read(Filename("mapBlock%i.jpg"%(i+1))) # TODO:maze either reference a set of textures for each piece or fill with color blockFiles[i].read(Filename('phase_4/maps/male_sleeve4New.jpg')) mapImage.fill(0.8, 0.8, 0.8) # iterate through the map data and place a block in the map image where appropriate for x in range( len(self._mazeLayout[0]) ): for y in range( len(self._mazeLayout) ): if self._mazeLayout[y][x]: ax = float(x)/len(self._mazeLayout[0]) * MAP_RESOLUTION ay = float(y)/len(self._mazeLayout) * MAP_RESOLUTION #TODO:maze use different blocks for different wall types or items #mapImage.copySubImage(random.choice(blockFiles), int(ax), int(ay), 20, 20, 32, 32) #TODO:maze find the ideal block texture size for the map so we dont # have to do this strange offset #mapImage.copySubImage(blockFiles[0], int(ax), int(ay), 0, 0, 32, 32) self._drawSquare(mapImage, int(ax), int(ay), 10, VBase4D(0.5, 0.5, 0.5, 1.0)) # create a texture from the map image mapTexture = Texture("mapTexture") mapTexture.setupTexture(Texture.TT2dTexture, self._maskResolution, self._maskResolution, 1, Texture.TUnsignedByte, Texture.FRgba) mapTexture.setMinfilter(Texture.FTLinear) mapTexture.load(mapImage) mapTexture.setWrapU(Texture.WMClamp) mapTexture.setWrapV(Texture.WMClamp) mapImage.clear() del mapImage # put the texture on a card and return it cm = CardMaker("map_cardMaker") cm.setFrame(-1.0,1.0,-1.0,1.0) map = self.attachNewNode(cm.generate()) map.setTexture(mapTexture, 1) return map
def _createMaskTextureCard(self): self._maskImage = PNMImage(self._maskResolution, self._maskResolution, 4) for x in range(self._maskResolution): for y in range(self._maskResolution): self._maskImage.setXelA(x, y, 0, 0, 0, 1) self.maskTexture = Texture('maskTexture') self.maskTexture.setupTexture(Texture.TT2dTexture, self._maskResolution, self._maskResolution, 1, Texture.TUnsignedByte, Texture.FRgba) self.maskTexture.setMinfilter(Texture.FTLinear) self.maskTexture.setWrapU(Texture.WMClamp) self.maskTexture.setWrapV(Texture.WMClamp) self.maskTexture.load(self._maskImage) base.graphicsEngine.renderFrame() cm = CardMaker('mask_cardMaker') cm.setFrame(-1.1, 1.1, -1.1, 1.1) mask = self.attachNewNode(cm.generate()) mask.setTexture(self.maskTexture, 1) mask.setTransparency(1) return mask
def __setupPreview(self): """Creates the preview.""" if not self.previewCheck.Value: return if self.preview != None: self.__destroyPreview() self.preview = wx.StaticBitmap(self, style = wx.SUNKEN_BORDER, size = PREVIEW_SIZE) self.sizer.Add(self.preview, 0, wx.ADJUST_MINSIZE | wx.ALIGN_CENTER, 0) cm = CardMaker("preview") cm.setFrame(-1, 1, -1, 1) cm.setUvRange(Point2(0, 0), Point2(1, 1)) self.previewTexture = Texture() self.previewBuffer = WindowManager.windows[0].win.makeTextureBuffer("preview", *PREVIEW_SIZE) self.previewBuffer.setClearColor(Vec4(1, 1, 1, 1)) self.previewCamera = base.makeCamera2d(self.previewBuffer) self.previewPlane = NodePath(cm.generate()) self.previewPlane.setFogOff(1000) self.previewPlane.setLightOff(1000) self.previewCamera.node().setScene(self.previewPlane) self.previewBuffer.addRenderTexture(self.previewTexture, GraphicsOutput.RTMCopyRam) self.previewCamera.node().setActive(texturePainter.texturePainterStatus == TEXTURE_PAINTER_STATUS_ENABLED) self.Layout()
def __init__(self, *args): ''' ''' ShowBase.__init__(self) base.setBackgroundColor(0, 0, 0) self.mdl = self.loader.loadModel("data/models/vehicles/vehicle01.egg") self.mdl.reparentTo(render) # Add the Skybox self.skybox = self.loader.loadModel("data/models/skybox.egg") t = Texture() # t.load(PNMImage("../skybox/skybox_tronic.png")) t.load(PNMImage("../skybox/test.png")) self.skybox.setTexture(t) self.skybox.setBin("background", 1) self.skybox.setDepthWrite(0) self.skybox.setDepthTest(0) self.skybox.setLightOff() self.skybox.setScale(10000) self.skybox.reparentTo(render)
def make_blocks_texmap(self): images = [] # 0 - sand images.append( PNMImage('res/textures/{0}sand.png'.format(Config().tex_suffix))) # 1 - land images.append( PNMImage('res/textures/{0}land.png'.format(Config().tex_suffix))) # 2 - low_mount images.append( PNMImage("res/textures/{0}low_mount.png".format( Config().tex_suffix))) # 3 - mid_mount images.append( PNMImage("res/textures/{0}mid_mount.png".format( Config().tex_suffix))) # 4 - high_mount images.append( PNMImage("res/textures/{0}high_mount.png".format( Config().tex_suffix))) d = images[0].getReadXSize() # 16 x 16 textures size = d * self.map_size image_all = PNMImage(size, size) n = 0 for i in xrange(0, size, d): for j in xrange(0, size, d): image_all.copySubImage(images[n], j, i) n += 1 if n >= len(images): break if n >= len(images): break self['world_blocks'] = Texture() self['world_blocks'].load(image_all) self['world_blocks'].setMagfilter(Texture.FTLinearMipmapLinear) self['world_blocks'].setMinfilter(Texture.FTLinearMipmapLinear)
def make(self): TerrainTile.make(self) self.makeSlopeMap() textureMapper = self.terrain.texturer.textureMapper #try to read textureMaps readTexMaps = True texNum = 0 for tex in textureMapper.textures: texNum += 1 fileName = "maps/textures/" + self.name + "+_texture" + str( texNum) + ".png" if not tex.image.read(Filename(fileName)): readTexMaps = False #otherwise calculate textureMaps if not readTexMaps: self.terrain.texturer.textureMapper.calculateTextures(self) #copy textureMaps to this terrainTile and save if necessary texNum = 0 for tex in self.terrain.texturer.textureMapper.textures: texNum += 1 self.textureMaps.append(tex.image) if not readTexMaps: tex.image.write( Filename("maps/textures/" + self.name + "+_texture" + str(texNum) + ".png")) #load textureMaps as actual textures for the shaders use num = 0 for tex in self.textureMaps: num += 1 newTexture = Texture() newTexture.load(tex) ts = TextureStage('alp' + str(num)) self.getRoot().setTexture(ts, newTexture)
def reconfigure(self, fullrebuild, changed): configuration = self.configuration if fullrebuild: self.cleanup() if len(configuration) == 0: return None auxbits = 0 needtex = {} needtex['color'] = True if configuration.has_key('CartoonInk'): needtex['aux'] = True auxbits |= AuxBitplaneAttrib.ABOAuxNormal if configuration.has_key('AmbientOcclusion'): needtex['depth'] = True needtex['ssao0'] = True needtex['ssao1'] = True needtex['ssao2'] = True needtex['aux'] = True auxbits |= AuxBitplaneAttrib.ABOAuxNormal if configuration.has_key('BlurSharpen'): needtex['blur0'] = True needtex['blur1'] = True if configuration.has_key('Bloom'): needtex['bloom0'] = True needtex['bloom1'] = True needtex['bloom2'] = True needtex['bloom3'] = True auxbits |= AuxBitplaneAttrib.ABOGlow if configuration.has_key('ViewGlow'): auxbits |= AuxBitplaneAttrib.ABOGlow for tex in needtex: self.textures[tex] = Texture('scene-' + tex) self.textures[tex].setWrapU(Texture.WMClamp) self.textures[tex].setWrapV(Texture.WMClamp) needtexpix = True self.finalQuad = self.manager.renderSceneInto( textures=self.textures, auxbits=auxbits) if self.finalQuad == None: self.cleanup() return False if configuration.has_key('BlurSharpen'): blur0 = self.textures['blur0'] blur1 = self.textures['blur1'] self.blur.append( self.manager.renderQuadInto(colortex=blur0, div=2)) self.blur.append(self.manager.renderQuadInto(colortex=blur1)) self.blur[0].setShaderInput('src', self.textures['color']) self.blur[0].setShader(self.loadShader('filter-blurx.sha')) self.blur[1].setShaderInput('src', blur0) self.blur[1].setShader(self.loadShader('filter-blury.sha')) if configuration.has_key('AmbientOcclusion'): ssao0 = self.textures['ssao0'] ssao1 = self.textures['ssao1'] ssao2 = self.textures['ssao2'] self.ssao.append(self.manager.renderQuadInto(colortex=ssao0)) self.ssao.append( self.manager.renderQuadInto(colortex=ssao1, div=2)) self.ssao.append(self.manager.renderQuadInto(colortex=ssao2)) self.ssao[0].setShaderInput('depth', self.textures['depth']) self.ssao[0].setShaderInput('normal', self.textures['aux']) self.ssao[0].setShaderInput( 'random', loader.loadTexture('maps/random.rgb')) self.ssao[0].setShader(self.loadShader('filter-ssao.sha')) self.ssao[1].setShaderInput('src', ssao0) self.ssao[1].setShader(self.loadShader('filter-blurx.sha')) self.ssao[2].setShaderInput('src', ssao1) self.ssao[2].setShader(self.loadShader('filter-blury.sha')) if configuration.has_key('Bloom'): bloomconf = configuration['Bloom'] bloom0 = self.textures['bloom0'] bloom1 = self.textures['bloom1'] bloom2 = self.textures['bloom2'] bloom3 = self.textures['bloom3'] if bloomconf.size == 'large': scale = 8 downsampler = 'filter-down4.sha' elif bloomconf.size == 'medium': scale = 4 downsampler = 'filter-copy.sha' else: scale = 2 downsampler = 'filter-copy.sha' self.bloom.append( self.manager.renderQuadInto(colortex=bloom0, div=2, align=scale)) self.bloom.append( self.manager.renderQuadInto(colortex=bloom1, div=scale, align=scale)) self.bloom.append( self.manager.renderQuadInto(colortex=bloom2, div=scale, align=scale)) self.bloom.append( self.manager.renderQuadInto(colortex=bloom3, div=scale, align=scale)) self.bloom[0].setShaderInput('src', self.textures['color']) self.bloom[0].setShader(self.loadShader('filter-bloomi.sha')) self.bloom[1].setShaderInput('src', bloom0) self.bloom[1].setShader(self.loadShader(downsampler)) self.bloom[2].setShaderInput('src', bloom1) self.bloom[2].setShader(self.loadShader('filter-bloomx.sha')) self.bloom[3].setShaderInput('src', bloom2) self.bloom[3].setShader(self.loadShader('filter-bloomy.sha')) text = '//Cg\n' text += 'void vshader(float4 vtx_position : POSITION,\n' text += ' out float4 l_position : POSITION,\n' text += ' uniform float4 texpad_txcolor,\n' text += ' uniform float4 texpix_txcolor,\n' text += ' out float4 l_texcoordC : TEXCOORD0,\n' if configuration.has_key('CartoonInk'): text += ' uniform float4 texpad_txaux,\n' text += ' uniform float4 texpix_txaux,\n' text += ' out float4 l_texcoordN : TEXCOORD1,\n' if configuration.has_key('Bloom'): text += ' uniform float4 texpad_txbloom3,\n' text += ' out float4 l_texcoordB : TEXCOORD2,\n' if configuration.has_key('BlurSharpen'): text += ' uniform float4 texpad_txblur1,\n' text += ' out float4 l_texcoordBS : TEXCOORD3,\n' if configuration.has_key('AmbientOcclusion'): text += ' uniform float4 texpad_txssao2,\n' text += ' out float4 l_texcoordAO : TEXCOORD4,\n' text += ' uniform float4x4 mat_modelproj)\n' text += '{\n' text += ' l_position=mul(mat_modelproj, vtx_position);\n' text += ' l_texcoordC=(vtx_position.xzxz * texpad_txcolor) + texpad_txcolor;\n' if configuration.has_key('CartoonInk'): text += ' l_texcoordN=(vtx_position.xzxz * texpad_txaux) + texpad_txaux;\n' if configuration.has_key('Bloom'): text += ' l_texcoordB=(vtx_position.xzxz * texpad_txbloom3) + texpad_txbloom3;\n' if configuration.has_key('BlurSharpen'): text += ' l_texcoordBS=(vtx_position.xzxz * texpad_txblur1) + texpad_txblur1;\n' if configuration.has_key('AmbientOcclusion'): text += ' l_texcoordAO=(vtx_position.xzxz * texpad_txssao2) + texpad_txssao2;\n' if configuration.has_key('HalfPixelShift'): text += ' l_texcoordC+=texpix_txcolor*0.5;\n' if configuration.has_key('CartoonInk'): text += ' l_texcoordN+=texpix_txaux*0.5;\n' text += '}\n' text += 'void fshader(\n' text += 'float4 l_texcoordC : TEXCOORD0,\n' text += 'uniform float4 texpix_txcolor,\n' if configuration.has_key('CartoonInk'): text += 'float4 l_texcoordN : TEXCOORD1,\n' text += 'uniform float4 texpix_txaux,\n' if configuration.has_key('Bloom'): text += 'float4 l_texcoordB : TEXCOORD2,\n' if configuration.has_key('BlurSharpen'): text += 'float4 l_texcoordBS : TEXCOORD3,\n' text += 'uniform float4 k_blurval,\n' if configuration.has_key('AmbientOcclusion'): text += 'float4 l_texcoordAO : TEXCOORD4,\n' for key in self.textures: text += 'uniform sampler2D k_tx' + key + ',\n' if configuration.has_key('CartoonInk'): text += 'uniform float4 k_cartoonseparation,\n' if configuration.has_key('VolumetricLighting'): text += 'uniform float4 k_casterpos,\n' text += 'uniform float4 k_vlparams,\n' text += 'out float4 o_color : COLOR)\n' text += '{\n' text += ' o_color = tex2D(k_txcolor, l_texcoordC.xy);\n' if configuration.has_key('CartoonInk'): text += CARTOON_BODY if configuration.has_key('AmbientOcclusion'): text += 'o_color *= tex2D(k_txssao2, l_texcoordAO.xy).r;\n' if configuration.has_key('BlurSharpen'): text += ' o_color = lerp(tex2D(k_txblur1, l_texcoordBS.xy), o_color, k_blurval.x);\n' if configuration.has_key('Bloom'): text += 'o_color = saturate(o_color);\n' text += 'float4 bloom = 0.5*tex2D(k_txbloom3, l_texcoordB.xy);\n' text += 'o_color = 1-((1-bloom)*(1-o_color));\n' if configuration.has_key('ViewGlow'): text += 'o_color.r = o_color.a;\n' if configuration.has_key('VolumetricLighting'): text += 'float decay = 1.0f;\n' text += 'float2 curcoord = l_texcoordC.xy;\n' text += 'float2 lightdir = curcoord - k_casterpos.xy;\n' text += 'lightdir *= k_vlparams.y;\n' text += 'half4 sample = tex2D(k_txcolor, curcoord);\n' text += 'float3 vlcolor = sample.rgb * sample.a;\n' text += 'for (int i = 0; i < k_vlparams.x; i++) {\n' text += ' curcoord -= lightdir;\n' text += ' sample = tex2D(k_txcolor, curcoord);\n' text += ' sample *= sample.a * decay;//*weight\n' text += ' vlcolor += sample.rgb;\n' text += ' decay *= k_vlparams.z;\n' text += '}\n' text += 'o_color += float4(vlcolor * k_vlparams.w, 1);\n' if configuration.has_key('Inverted'): text += 'o_color = float4(1, 1, 1, 1) - o_color;\n' text += '}\n' self.finalQuad.setShader(Shader.make(text)) for tex in self.textures: self.finalQuad.setShaderInput('tx' + tex, self.textures[tex]) self.task = taskMgr.add(self.update, 'common-filters-update') if changed == 'CartoonInk' or fullrebuild: if configuration.has_key('CartoonInk'): separation = configuration['CartoonInk'] self.finalQuad.setShaderInput( 'cartoonseparation', Vec4(separation, 0, separation, 0)) if changed == 'BlurSharpen' or fullrebuild: if configuration.has_key('BlurSharpen'): blurval = configuration['BlurSharpen'] self.finalQuad.setShaderInput( 'blurval', Vec4(blurval, blurval, blurval, blurval)) if changed == 'Bloom' or fullrebuild: if configuration.has_key('Bloom'): bloomconf = configuration['Bloom'] intensity = bloomconf.intensity * 3.0 self.bloom[0].setShaderInput('blend', bloomconf.blendx, bloomconf.blendy, bloomconf.blendz, bloomconf.blendw * 2.0) self.bloom[0].setShaderInput( 'trigger', bloomconf.mintrigger, 1.0 / (bloomconf.maxtrigger - bloomconf.mintrigger), 0.0, 0.0) self.bloom[0].setShaderInput('desat', bloomconf.desat) self.bloom[3].setShaderInput('intensity', intensity, intensity, intensity, intensity) if changed == 'VolumetricLighting' or fullrebuild: if configuration.has_key('VolumetricLighting'): config = configuration['VolumetricLighting'] tcparam = config.density / float(config.numsamples) self.finalQuad.setShaderInput('vlparams', config.numsamples, tcparam, config.decay, config.exposure) if changed == 'AmbientOcclusion' or fullrebuild: if configuration.has_key('AmbientOcclusion'): config = configuration['AmbientOcclusion'] self.ssao[0].setShaderInput( 'params1', config.numsamples, -float(config.amount) / config.numsamples, config.radius, 0) self.ssao[0].setShaderInput('params2', config.strength, config.falloff, 0, 0) self.update() return True
def __init__(self, effectFileName, parent=None, loop=False, effectIsCentered=True, effectAdjustment=[0, 0, 0]): self.effectAdjustment = effectAdjustment self.loopEffect = loop self.effectIsCentered = effectIsCentered self.loadedFormat = None if effectFileName != None: effectFileNameSplit = effectFileName.split('.') self.loadedFormat = effectFileNameSplit[len(effectFileNameSplit)-2] # Get value at penultimate index if self.loadedFormat == effectFileNameSplit[0]: self.loadedFormat = None # Get rid of bad format name. pass # Load texture; supply alpha channel if it doesn't exist. p = transparencyKey(effectFileName) self.tex = Texture() self.tex.setup2dTexture(p.getXSize(), p.getYSize(), Texture.TUnsignedByte, Texture.FRgba) self.tex.load(p) if self.loadedFormat != None: try: self.tree = etree.parse("./"+GAME+"/effects/"+self.loadedFormat+"/sprite.xml") except IOError: self.loadedFormat = None pass if self.loadedFormat != None: root = self.tree.getroot() self.frames = root.find('.//frames') self.colors = root.find('.//colors') self.tweens = root.find('.//motion-tweens') self.compositeFrames = root.find('.//composite-frames') self.baseWidth = 0 if root.attrib.get("base-width") == None else float(root.attrib.get("base-width")) self.baseHeight = 0 if root.attrib.get("base-height") == None else float(root.attrib.get("base-height")) self.effectWidth = 1 if root.attrib.get("frame-width") == None else float(root.attrib.get("frame-width")) self.effectHeight = 1 if root.attrib.get("frame-height") == None else float(root.attrib.get("frame-height")) self.effectTargetMS = 143 if root.attrib.get("target-ms") == None else float(root.attrib.get("target-ms")) self.startIndex = 1 if root.attrib.get("target-start") == None else int(root.attrib.get("target-start")) self.endIndex = 1 if root.attrib.get("target-end") == None else int(root.attrib.get("target-end")) self.noSampling = False if root.attrib.get("no-sampling") == None else bool(root.attrib.get("no-sampling")) if self.noSampling==True: self.tex.setMagfilter(Texture.FTNearest) self.tex.setMinfilter(Texture.FTNearest) cm = CardMaker('card-'+effectFileName) cardDeltaX = self.effectWidth / self.pixelScaleX cardDeltaZ = self.effectHeight / self.pixelScaleZ if self.effectIsCentered == True: cm.setFrame(0, 0, 0, 0) deltaX = (cardDeltaX/2.0) - (-cardDeltaX/2.0) deltaY = 0 deltaZ = (cardDeltaZ/2.0) - (-cardDeltaZ/2.0) #occluder = OccluderNode('effect-parent-occluder', Point3((-cardDeltaX/2.0), 0, (-cardDeltaZ/2.0)), Point3((-cardDeltaX/2.0), 0, (cardDeltaZ/2.0)), Point3((cardDeltaX/2.0), 0, (cardDeltaZ/2.0)), Point3((cardDeltaX/2.0), 0, (-cardDeltaZ/2.0))) else: cm.setFrame(0, 0, 0, 0) deltaX = (cardDeltaX/2.0) - (-cardDeltaX/2.0) deltaY = 0 deltaZ = cardDeltaZ - 0 #occluder = OccluderNode('effect-parent-occluder', Point3((-cardDeltaX/2.0), 0, 0), Point3((-cardDeltaX/2.0), 0, cardDeltaZ), Point3((cardDeltaX/2.0), 0, cardDeltaZ), Point3((cardDeltaX/2.0), 0, 0)) self.effectCardNodePath = render.attachNewNode(cm.generate()) self.effectCardNodePath.setBillboardPointEye() self.effectCardNodePath.reparentTo(parent) #occluder_nodepath = self.effectCardNodePath.attachNewNode(occluder) #self.effectCardNodePath.setOccluder(occluder_nodepath) emptyNode = NodePath('effect-parent-translator') emptyNode.reparentTo(self.effectCardNodePath) if effectIsCentered == True: emptyNode.setPos(-deltaX/2.0+self.effectAdjustment[0], 0+self.effectAdjustment[1], deltaZ/2.0+self.effectAdjustment[2]) else: emptyNode.setPos(-deltaX/2.0+self.effectAdjustment[0], 0+self.effectAdjustment[1], deltaZ+self.effectAdjustment[2]) #emptyNode.place() emptyNode.setSx(float(deltaX)/self.effectWidth) emptyNode.setSz(float(deltaZ)/self.effectHeight) self.effectCameraNodePath = emptyNode if parent != None: self.effectCardNodePath.reparentTo(parent) else: self.effectCardNodePath.reparentTo(render) #self.effectCardNodePath.place() self.effectCardNodePath.setBin("fixed", 40) self.effectCardNodePath.setDepthTest(False) self.effectCardNodePath.setDepthWrite(False) pass
def reconfigure(self, fullrebuild, changed): """ Reconfigure is called whenever any configuration change is made. """ configuration = self.configuration if (fullrebuild): self.cleanup() if (len(configuration) == 0): return auxbits = 0 needtex = {} needtex["color"] = True if (configuration.has_key("CartoonInk")): needtex["aux"] = True auxbits |= AuxBitplaneAttrib.ABOAuxNormal if (configuration.has_key("AmbientOcclusion")): needtex["depth"] = True needtex["ssao0"] = True needtex["ssao1"] = True needtex["ssao2"] = True needtex["aux"] = True auxbits |= AuxBitplaneAttrib.ABOAuxNormal if (configuration.has_key("BlurSharpen")): needtex["blur0"] = True needtex["blur1"] = True if (configuration.has_key("Bloom")): needtex["bloom0"] = True needtex["bloom1"] = True needtex["bloom2"] = True needtex["bloom3"] = True auxbits |= AuxBitplaneAttrib.ABOGlow if (configuration.has_key("ViewGlow")): auxbits |= AuxBitplaneAttrib.ABOGlow for tex in needtex: self.textures[tex] = Texture("scene-" + tex) self.textures[tex].setWrapU(Texture.WMClamp) self.textures[tex].setWrapV(Texture.WMClamp) needtexpix = True self.finalQuad = self.manager.renderSceneInto( textures=self.textures, auxbits=auxbits) if (self.finalQuad == None): self.cleanup() return False if (configuration.has_key("BlurSharpen")): blur0 = self.textures["blur0"] blur1 = self.textures["blur1"] self.blur.append( self.manager.renderQuadInto(colortex=blur0, div=2)) self.blur.append(self.manager.renderQuadInto(colortex=blur1)) self.blur[0].setShaderInput("src", self.textures["color"]) self.blur[0].setShader(self.loadShader("filter-blurx.sha")) self.blur[1].setShaderInput("src", blur0) self.blur[1].setShader(self.loadShader("filter-blury.sha")) if (configuration.has_key("AmbientOcclusion")): ssao0 = self.textures["ssao0"] ssao1 = self.textures["ssao1"] ssao2 = self.textures["ssao2"] self.ssao.append(self.manager.renderQuadInto(colortex=ssao0)) self.ssao.append( self.manager.renderQuadInto(colortex=ssao1, div=2)) self.ssao.append(self.manager.renderQuadInto(colortex=ssao2)) self.ssao[0].setShaderInput("depth", self.textures["depth"]) self.ssao[0].setShaderInput("normal", self.textures["aux"]) self.ssao[0].setShaderInput( "random", loader.loadTexture("maps/random.rgb")) self.ssao[0].setShader(self.loadShader("filter-ssao.sha")) self.ssao[1].setShaderInput("src", ssao0) self.ssao[1].setShader(self.loadShader("filter-blurx.sha")) self.ssao[2].setShaderInput("src", ssao1) self.ssao[2].setShader(self.loadShader("filter-blury.sha")) if (configuration.has_key("Bloom")): bloomconf = configuration["Bloom"] bloom0 = self.textures["bloom0"] bloom1 = self.textures["bloom1"] bloom2 = self.textures["bloom2"] bloom3 = self.textures["bloom3"] if (bloomconf.size == "large"): scale = 8 downsampler = "filter-down4.sha" elif (bloomconf.size == "medium"): scale = 4 downsampler = "filter-copy.sha" else: scale = 2 downsampler = "filter-copy.sha" self.bloom.append( self.manager.renderQuadInto(colortex=bloom0, div=2, align=scale)) self.bloom.append( self.manager.renderQuadInto(colortex=bloom1, div=scale, align=scale)) self.bloom.append( self.manager.renderQuadInto(colortex=bloom2, div=scale, align=scale)) self.bloom.append( self.manager.renderQuadInto(colortex=bloom3, div=scale, align=scale)) self.bloom[0].setShaderInput("src", self.textures["color"]) self.bloom[0].setShader(self.loadShader("filter-bloomi.sha")) self.bloom[1].setShaderInput("src", bloom0) self.bloom[1].setShader(self.loadShader(downsampler)) self.bloom[2].setShaderInput("src", bloom1) self.bloom[2].setShader(self.loadShader("filter-bloomx.sha")) self.bloom[3].setShaderInput("src", bloom2) self.bloom[3].setShader(self.loadShader("filter-bloomy.sha")) text = "//Cg\n" text += "void vshader(float4 vtx_position : POSITION,\n" text += " out float4 l_position : POSITION,\n" text += " uniform float4 texpad_txcolor,\n" text += " uniform float4 texpix_txcolor,\n" text += " out float4 l_texcoordC : TEXCOORD0,\n" if (configuration.has_key("CartoonInk")): text += " uniform float4 texpad_txaux,\n" text += " uniform float4 texpix_txaux,\n" text += " out float4 l_texcoordN : TEXCOORD1,\n" if (configuration.has_key("Bloom")): text += " uniform float4 texpad_txbloom3,\n" text += " out float4 l_texcoordB : TEXCOORD2,\n" if (configuration.has_key("BlurSharpen")): text += " uniform float4 texpad_txblur1,\n" text += " out float4 l_texcoordBS : TEXCOORD3,\n" if (configuration.has_key("AmbientOcclusion")): text += " uniform float4 texpad_txssao2,\n" text += " out float4 l_texcoordAO : TEXCOORD4,\n" text += " uniform float4x4 mat_modelproj)\n" text += "{\n" text += " l_position=mul(mat_modelproj, vtx_position);\n" text += " l_texcoordC=(vtx_position.xzxz * texpad_txcolor) + texpad_txcolor;\n" if (configuration.has_key("CartoonInk")): text += " l_texcoordN=(vtx_position.xzxz * texpad_txaux) + texpad_txaux;\n" if (configuration.has_key("Bloom")): text += " l_texcoordB=(vtx_position.xzxz * texpad_txbloom3) + texpad_txbloom3;\n" if (configuration.has_key("BlurSharpen")): text += " l_texcoordBS=(vtx_position.xzxz * texpad_txblur1) + texpad_txblur1;\n" if (configuration.has_key("AmbientOcclusion")): text += " l_texcoordAO=(vtx_position.xzxz * texpad_txssao2) + texpad_txssao2;\n" if (configuration.has_key("HalfPixelShift")): text += " l_texcoordC+=texpix_txcolor*0.5;\n" if (configuration.has_key("CartoonInk")): text += " l_texcoordN+=texpix_txaux*0.5;\n" text += "}\n" text += "void fshader(\n" text += "float4 l_texcoordC : TEXCOORD0,\n" text += "uniform float4 texpix_txcolor,\n" if (configuration.has_key("CartoonInk")): text += "float4 l_texcoordN : TEXCOORD1,\n" text += "uniform float4 texpix_txaux,\n" if (configuration.has_key("Bloom")): text += "float4 l_texcoordB : TEXCOORD2,\n" if (configuration.has_key("BlurSharpen")): text += "float4 l_texcoordBS : TEXCOORD3,\n" text += "uniform float4 k_blurval,\n" if (configuration.has_key("AmbientOcclusion")): text += "float4 l_texcoordAO : TEXCOORD4,\n" for key in self.textures: text += "uniform sampler2D k_tx" + key + ",\n" if (configuration.has_key("CartoonInk")): text += "uniform float4 k_cartoonseparation,\n" if (configuration.has_key("VolumetricLighting")): text += "uniform float4 k_casterpos,\n" text += "uniform float4 k_vlparams,\n" text += "out float4 o_color : COLOR)\n" text += "{\n" text += " o_color = tex2D(k_txcolor, l_texcoordC.xy);\n" if (configuration.has_key("CartoonInk")): text += CARTOON_BODY if (configuration.has_key("AmbientOcclusion")): text += "o_color *= tex2D(k_txssao2, l_texcoordAO.xy).r;\n" if (configuration.has_key("BlurSharpen")): text += " o_color = lerp(tex2D(k_txblur1, l_texcoordBS.xy), o_color, k_blurval.x);\n" if (configuration.has_key("Bloom")): text += "o_color = saturate(o_color);\n" text += "float4 bloom = 0.5*tex2D(k_txbloom3, l_texcoordB.xy);\n" text += "o_color = 1-((1-bloom)*(1-o_color));\n" if (configuration.has_key("ViewGlow")): text += "o_color.r = o_color.a;\n" if (configuration.has_key("VolumetricLighting")): text += "float decay = 1.0f;\n" text += "float2 curcoord = l_texcoordC.xy;\n" text += "float2 lightdir = curcoord - k_casterpos.xy;\n" text += "lightdir *= k_vlparams.x;\n" text += "half4 sample = tex2D(k_txcolor, curcoord);\n" text += "float3 vlcolor = sample.rgb * sample.a;\n" text += "for (int i = 0; i < %s; i++) {\n" % int( configuration["VolumetricLighting"].numsamples) text += " curcoord -= lightdir;\n" text += " sample = tex2D(k_txcolor, curcoord);\n" text += " sample *= sample.a * decay;//*weight\n" text += " vlcolor += sample.rgb;\n" text += " decay *= k_vlparams.y;\n" text += "}\n" text += "o_color += float4(vlcolor * k_vlparams.z, 1);\n" if (configuration.has_key("Inverted")): text += "o_color = float4(1, 1, 1, 1) - o_color;\n" text += "}\n" self.finalQuad.setShader(Shader.make(text)) for tex in self.textures: self.finalQuad.setShaderInput("tx" + tex, self.textures[tex]) self.task = taskMgr.add(self.update, "common-filters-update") if (changed == "CartoonInk") or fullrebuild: if (configuration.has_key("CartoonInk")): separation = configuration["CartoonInk"] self.finalQuad.setShaderInput( "cartoonseparation", Vec4(separation, 0, separation, 0)) if (changed == "BlurSharpen") or fullrebuild: if (configuration.has_key("BlurSharpen")): blurval = configuration["BlurSharpen"] self.finalQuad.setShaderInput( "blurval", Vec4(blurval, blurval, blurval, blurval)) if (changed == "Bloom") or fullrebuild: if (configuration.has_key("Bloom")): bloomconf = configuration["Bloom"] intensity = bloomconf.intensity * 3.0 self.bloom[0].setShaderInput("blend", bloomconf.blendx, bloomconf.blendy, bloomconf.blendz, bloomconf.blendw * 2.0) self.bloom[0].setShaderInput( "trigger", bloomconf.mintrigger, 1.0 / (bloomconf.maxtrigger - bloomconf.mintrigger), 0.0, 0.0) self.bloom[0].setShaderInput("desat", bloomconf.desat) self.bloom[3].setShaderInput("intensity", intensity, intensity, intensity, intensity) if (changed == "VolumetricLighting") or fullrebuild: if (configuration.has_key("VolumetricLighting")): config = configuration["VolumetricLighting"] tcparam = config.density / float(config.numsamples) self.finalQuad.setShaderInput("vlparams", tcparam, config.decay, config.exposure, 0.0) if (changed == "AmbientOcclusion") or fullrebuild: if (configuration.has_key("AmbientOcclusion")): config = configuration["AmbientOcclusion"] self.ssao[0].setShaderInput( "params1", config.numsamples, -float(config.amount) / config.numsamples, config.radius, 0) self.ssao[0].setShaderInput("params2", config.strength, config.falloff, 0, 0) self.update() return True
def __init__(self, image_path, rowPerFace, name=None,\ rows=1, cols=1, scale=1.0,\ twoSided=False, alpha=TRANS_ALPHA,\ repeatX=1, repeatY=1,\ anchorX=ALIGN_CENTER, anchorY=ALIGN_BOTTOM): """ Create a card textured with an image. The card is sized so that the ratio between the card and image is the same. """ global SpriteId self.spriteNum = str(SpriteId) SpriteId += 1 scale *= self.PIXEL_SCALE self.animations = {} self.scale = scale self.repeatX = repeatX self.repeatY = repeatY self.flip = {'x': False, 'y': False} self.rows = rows self.cols = cols self.currentFrame = 0 self.currentAnim = None self.loopAnim = False self.frameInterrupt = True # Create the NodePath if name: self.node = NodePath("Sprite2d:%s" % name) else: self.node = NodePath("Sprite2d:%s" % image_path) # Set the attribute for transparency/twosided self.node.node().setAttrib(TransparencyAttrib.make(alpha)) if twoSided: self.node.setTwoSided(True) # Make a filepath self.imgFile = Filename(image_path) if self.imgFile.empty(): raise IOError, "File not found" # Instead of loading it outright, check with the PNMImageHeader if we can open # the file. imgHead = PNMImageHeader() if not imgHead.readHeader(self.imgFile): raise IOError, "PNMImageHeader could not read file. Try using absolute filepaths" # Load the image with a PNMImage image = PNMImage() image.read(self.imgFile) self.sizeX = image.getXSize() self.sizeY = image.getYSize() # We need to find the power of two size for the another PNMImage # so that the texture thats loaded on the geometry won't have artifacts textureSizeX = self.nextsize(self.sizeX) textureSizeY = self.nextsize(self.sizeY) # The actual size of the texture in memory self.realSizeX = textureSizeX self.realSizeY = textureSizeY self.paddedImg = PNMImage(textureSizeX, textureSizeY) if image.hasAlpha(): self.paddedImg.alphaFill(0) # Copy the source image to the image we're actually using self.paddedImg.blendSubImage(image, 0, 0) # We're done with source image, clear it image.clear() # The pixel sizes for each cell self.colSize = self.sizeX / self.cols self.rowSize = self.sizeY / self.rows # How much padding the texture has self.paddingX = textureSizeX - self.sizeX self.paddingY = textureSizeY - self.sizeY # Set UV padding self.uPad = float(self.paddingX) / textureSizeX self.vPad = float(self.paddingY) / textureSizeY # The UV dimensions for each cell self.uSize = (1.0 - self.uPad) / self.cols self.vSize = (1.0 - self.vPad) / self.rows self.cards = [] self.rowPerFace = rowPerFace for i in range(len(rowPerFace)): card = CardMaker("Sprite2d-Geom") # The positions to create the card at if anchorX == self.ALIGN_LEFT: posLeft = 0 posRight = (self.colSize / scale) * repeatX elif anchorX == self.ALIGN_CENTER: posLeft = -(self.colSize / 2.0 / scale) * repeatX posRight = (self.colSize / 2.0 / scale) * repeatX elif anchorX == self.ALIGN_RIGHT: posLeft = -(self.colSize / scale) * repeatX posRight = 0 if anchorY == self.ALIGN_BOTTOM: posTop = 0 posBottom = (self.rowSize / scale) * repeatY elif anchorY == self.ALIGN_CENTER: posTop = -(self.rowSize / 2.0 / scale) * repeatY posBottom = (self.rowSize / 2.0 / scale) * repeatY elif anchorY == self.ALIGN_TOP: posTop = -(self.rowSize / scale) * repeatY posBottom = 0 card.setFrame(posLeft, posRight, posTop, posBottom) card.setHasUvs(True) self.cards.append(self.node.attachNewNode(card.generate())) self.cards[-1].setH(i * 360 / len(rowPerFace)) # Since the texture is padded, we need to set up offsets and scales to make # the texture fit the whole card self.offsetX = (float(self.colSize) / textureSizeX) self.offsetY = (float(self.rowSize) / textureSizeY) # self.node.setTexScale(TextureStage.getDefault(), self.offsetX * repeatX, self.offsetY * repeatY) # self.node.setTexOffset(TextureStage.getDefault(), 0, 1-self.offsetY) self.texture = Texture() self.texture.setXSize(textureSizeX) self.texture.setYSize(textureSizeY) self.texture.setZSize(1) # Load the padded PNMImage to the texture self.texture.load(self.paddedImg) self.texture.setMagfilter(Texture.FTNearest) self.texture.setMinfilter(Texture.FTNearest) #Set up texture clamps according to repeats if repeatX > 1: self.texture.setWrapU(Texture.WMRepeat) else: self.texture.setWrapU(Texture.WMClamp) if repeatY > 1: self.texture.setWrapV(Texture.WMRepeat) else: self.texture.setWrapV(Texture.WMClamp) self.node.setTexture(self.texture) self.setFrame(0)
def collectPlayer(self, task): ''' Wait until all players are ready ''' if len(self._players) > 0 and self.player_buttonpressed[0] < task.time: if self._players[0].device.boost and self.countdown <= 0: loading = False for player in self._players: if player.vehicle.model_loading: loading = True break self._notify.debug("Loading vehicle: %s" % (loading)) if not loading: taskMgr.remove("selectVehicle") self.track = trackgen3d.Track3d(1000, 1800, 1600, 1200, 5) # len(self._players)) self.streetPath = render.attachNewNode( self.track.createRoadMesh()) # self.borderleftPath = render.attachNewNode(self.track.createBorderLeftMesh()) self.borderleftPath = render.attachNewNode( self.track.createBorderLeftMesh()) self.borderrightPath = render.attachNewNode( self.track.createBorderRightMesh()) self.borderleftcollisionPath = NodePath( self.track.createBorderLeftCollisionMesh()) self.borderrightcollisionPath = NodePath( self.track.createBorderRightCollisionMesh()) # #self.borderPath = render.attachNewNode(self.track.createBorderMesh()) textures = ["tube", "tube2", "street"] tex = textures[random.randint(0, len(textures) - 1)] roadtex = loader.loadTexture('data/textures/' + tex + '.png') bordertex = loader.loadTexture('data/textures/border.png') self.streetPath.setTexture(roadtex) self.borderleftPath.setTexture(bordertex) self.borderrightPath.setTexture(bordertex) # self.streetPath = loader.loadModel('data/models/Street.egg') # self.streetPath = loader.loadModel('data/models/Street.egg') # tex = loader.loadTexture('data/models/StreetTex.png') # self.nodePath.setTexture(tex) self._parent.startGame(self.streetPath, self.borderleftPath, self.borderrightPath, self.track.trackpoints, self.borderleftcollisionPath, self.borderrightcollisionPath) return task.done for device in self.unusedDevices: if device.boost: self.countdown = COUNTDOWN_START self.player_buttonpressed.append(0) self._parent.addPlayer(device) # Set the PlayerCam to the Vehicle select menu Node vehicleSelectNode = NodePath("VehicleSelectNode") self._players[-1].camera.camera.reparentTo(vehicleSelectNode) # Light, that casts shadows plight = Spotlight('plight') plight.setColor(VBase4(10.0, 10.0, 10.0, 1)) if (base.win.getGsg().getSupportsBasicShaders() != 0): pass # plight.setShadowCaster(True, 2048, 2048)#enable shadows for this light ##TODO wegen Linux # Light plight.getLens().setFov(80) plnp = vehicleSelectNode.attachNewNode(plight) plnp.setPos(2, -10, 10) plnp.lookAt(0, 0, 0) vehicleSelectNode.setLight(plnp) # vehicleSelectNode.setShaderAuto()#enable autoshader so we can use shadows # Light ambilight = AmbientLight('ambilight') ambilight.setColor(VBase4(0.2, 0.2, 0.2, 1)) vehicleSelectNode.setLight( vehicleSelectNode.attachNewNode(ambilight)) self.platform.instanceTo( vehicleSelectNode) # Load the platform # instance shown text self.countdown_node.instanceTo( vehicleSelectNode) # Instance the Countdown self.loading.instanceTo( vehicleSelectNode) # Show the Loading-Text self.attributes.copyTo(vehicleSelectNode).hide() self._players[-1].vehicle.model_loading = True # start loading the model loader.loadModel(self.vehicle_list[0], callback=self._players[-1].setVehicle) self._notify.debug("Loading initial vehicle: %s" % (self.vehicle_list[0])) self.unusedDevices.remove(device) self.player_buttonpressed[-1] = task.time + self.KEY_DELAY # Add the Skybox skybox = loader.loadModel("data/models/skybox.egg") t = Texture() t.load(PNMImage("data/textures/skybox_hangar.png")) skybox.setTexture(t) skybox.setBin("background", 1) skybox.setDepthWrite(0) skybox.setDepthTest(0) skybox.setLightOff() skybox.setScale(10000) skybox.reparentTo(vehicleSelectNode) for player in self._players: if self.player_buttonpressed[self._players.index( player)] < task.time: if player.device.use_item: self.countdown = COUNTDOWN_START self._notify.debug("Removing player: %s" % (player)) self.unusedDevices.append(player.device) self.player_buttonpressed.pop(self._players.index(player)) self._parent.removePlayer(player) return task.cont
def _initializeFlare(self): # Parameters self.distance = 130000.0 self.threshold = 0.3 self.radius = 0.8 self.strength = 1.0 self.suncolor = Vec4(1, 1, 1, 1) self.suncardcolor = Vec4(1, 1, 0, 0) # Initialize some values self.obscured = 0.0 # flaredata will hold the rendered image self.flaredata = PNMImage() # flaretexture will store the rendered buffer self.flaretexture = Texture() # Create a 10x10 texture buffer for the flare self.flarebuffer = base.win.makeTextureBuffer("Flare Buffer", 10, 10) # Attach the texture to the buffer self.flarebuffer.addRenderTexture(self.flaretexture, GraphicsOutput.RTMCopyRam) self.flarebuffer.setSort(-100) # Camera that renders the flare buffer self.flarecamera = base.makeCamera(self.flarebuffer) #self.flarecamera.reparentTo(base.cam) #self.flarecamera.setPos(-50,0,0) self.ortlens = OrthographicLens() self.ortlens.setFilmSize( 10, 10) # or whatever is appropriate for your scene self.ortlens.setNearFar(1, self.distance) self.flarecamera.node().setLens(self.ortlens) self.flarecamera.node().setCameraMask(GXMgr.MASK_GXM_HIDDEN) # Create a light for the flare self.sunlight = self.baseNode.attachNewNode( PointLight("Sun:Point Light")) self.sunlight.node().setColor(self.suncolor) self.sunlight.node().setAttenuation(Vec3(0.1, 0.04, 0.0)) # Load texture cards # Create a nodepath that'll hold the texture cards for the new lens-flare self.texcardNP = aspect2d.attachNewNode('Sun:flareNode1') self.texcardNP.attachNewNode('Sun:fakeHdr') self.texcardNP.attachNewNode('Sun:starburstNode') # Load a circle and assign it a color. This will be used to calculate # Flare occlusion self.starcard = loader.loadModel('../data/models/unitcircle.egg') self.starcard.reparentTo(self.baseNode) self.starcard.setColor(self.suncardcolor) self.starcard.setScale(1) #self.starcard.setTransparency(TransparencyAttrib.MAlpha) # This is necessary since a billboard always rotates the y-axis to the # target but we need the z-axis self.starcard.setP(-90) self.starcard.setBillboardPointEye(self.flarecamera, 0.0) # Don't let the main camera see the star card self.starcard.show(GXMgr.MASK_GXM_HIDDEN) self.starcard.hide(GXMgr.MASK_GXM_VISIBLE) #the models are really just texture cards create with egg-texture-cards # from the actual pictures self.hdr = loader.loadModel('../data/models/fx_flare.egg') self.hdr.reparentTo(self.texcardNP.find('**/Sun:fakeHdr')) # Flare specs self.starburst_0 = loader.loadModel( '../data/models/fx_starburst_01.egg') self.starburst_1 = loader.loadModel( '../data/models/fx_starburst_02.egg') self.starburst_2 = loader.loadModel( '../data/models/fx_starburst_03.egg') self.starburst_0.setPos(0.5, 0, 0.5) self.starburst_1.setPos(0.5, 0, 0.5) self.starburst_2.setPos(0.5, 0, 0.5) self.starburst_0.setScale(.2) self.starburst_1.setScale(.2) self.starburst_2.setScale(.2) self.starburst_0.reparentTo( self.texcardNP.find('**/Sun:starburstNode')) self.starburst_1.reparentTo( self.texcardNP.find('**/Sun:starburstNode')) self.starburst_2.reparentTo( self.texcardNP.find('**/Sun:starburstNode')) self.texcardNP.setTransparency(TransparencyAttrib.MAlpha) # Put the texture cards in the background bin self.texcardNP.setBin('background', 0) # The texture cards do not affect the depth buffer self.texcardNP.setDepthWrite(False) #attach a node to the screen middle, used for some math self.mid2d = aspect2d.attachNewNode('mid2d') #start the task that implements the lens-flare taskMgr.add(self._flareTask, 'Sun:flareTask')
def reconfigure(self, fullrebuild, changed): """ Reconfigure is called whenever any configuration change is made. """ configuration = self.configuration if (fullrebuild): self.cleanup() if (len(configuration) == 0): return auxbits = 0 needtex = set(["color"]) needtexcoord = set(["color"]) if ("CartoonInk" in configuration): needtex.add("aux") auxbits |= AuxBitplaneAttrib.ABOAuxNormal needtexcoord.add("aux") if ("AmbientOcclusion" in configuration): needtex.add("depth") needtex.add("ssao0") needtex.add("ssao1") needtex.add("ssao2") needtex.add("aux") auxbits |= AuxBitplaneAttrib.ABOAuxNormal needtexcoord.add("ssao2") if ("BlurSharpen" in configuration): needtex.add("blur0") needtex.add("blur1") needtexcoord.add("blur1") if ("Bloom" in configuration): needtex.add("bloom0") needtex.add("bloom1") needtex.add("bloom2") needtex.add("bloom3") auxbits |= AuxBitplaneAttrib.ABOGlow needtexcoord.add("bloom3") if ("ViewGlow" in configuration): auxbits |= AuxBitplaneAttrib.ABOGlow if ("VolumetricLighting" in configuration): needtex[configuration["VolumetricLighting"].source] = True for tex in needtex: self.textures[tex] = Texture("scene-" + tex) self.textures[tex].setWrapU(Texture.WMClamp) self.textures[tex].setWrapV(Texture.WMClamp) self.finalQuad = self.manager.renderSceneInto( textures=self.textures, auxbits=auxbits) if (self.finalQuad == None): self.cleanup() return False if ("BlurSharpen" in configuration): blur0 = self.textures["blur0"] blur1 = self.textures["blur1"] self.blur.append( self.manager.renderQuadInto(colortex=blur0, div=2)) self.blur.append(self.manager.renderQuadInto(colortex=blur1)) self.blur[0].setShaderInput("src", self.textures["color"]) self.blur[0].setShader(self.loadShader("filter-blurx.sha")) self.blur[1].setShaderInput("src", blur0) self.blur[1].setShader(self.loadShader("filter-blury.sha")) if ("AmbientOcclusion" in configuration): ssao0 = self.textures["ssao0"] ssao1 = self.textures["ssao1"] ssao2 = self.textures["ssao2"] self.ssao.append(self.manager.renderQuadInto(colortex=ssao0)) self.ssao.append( self.manager.renderQuadInto(colortex=ssao1, div=2)) self.ssao.append(self.manager.renderQuadInto(colortex=ssao2)) self.ssao[0].setShaderInput("depth", self.textures["depth"]) self.ssao[0].setShaderInput("normal", self.textures["aux"]) self.ssao[0].setShaderInput( "random", loader.loadTexture("maps/random.rgb")) self.ssao[0].setShader( Shader.make(SSAO_BODY % configuration["AmbientOcclusion"].numsamples)) self.ssao[1].setShaderInput("src", ssao0) self.ssao[1].setShader(self.loadShader("filter-blurx.sha")) self.ssao[2].setShaderInput("src", ssao1) self.ssao[2].setShader(self.loadShader("filter-blury.sha")) if ("Bloom" in configuration): bloomconf = configuration["Bloom"] bloom0 = self.textures["bloom0"] bloom1 = self.textures["bloom1"] bloom2 = self.textures["bloom2"] bloom3 = self.textures["bloom3"] if (bloomconf.size == "large"): scale = 8 downsampler = "filter-down4.sha" elif (bloomconf.size == "medium"): scale = 4 downsampler = "filter-copy.sha" else: scale = 2 downsampler = "filter-copy.sha" self.bloom.append( self.manager.renderQuadInto(colortex=bloom0, div=2, align=scale)) self.bloom.append( self.manager.renderQuadInto(colortex=bloom1, div=scale, align=scale)) self.bloom.append( self.manager.renderQuadInto(colortex=bloom2, div=scale, align=scale)) self.bloom.append( self.manager.renderQuadInto(colortex=bloom3, div=scale, align=scale)) self.bloom[0].setShaderInput("src", self.textures["color"]) self.bloom[0].setShader(self.loadShader("filter-bloomi.sha")) self.bloom[1].setShaderInput("src", bloom0) self.bloom[1].setShader(self.loadShader(downsampler)) self.bloom[2].setShaderInput("src", bloom1) self.bloom[2].setShader(self.loadShader("filter-bloomx.sha")) self.bloom[3].setShaderInput("src", bloom2) self.bloom[3].setShader(self.loadShader("filter-bloomy.sha")) texcoords = {} texcoordPadding = {} for tex in needtexcoord: if self.textures[tex].getAutoTextureScale() != ATSNone or \ "HalfPixelShift" in configuration: texcoords[tex] = "l_texcoord_" + tex texcoordPadding["l_texcoord_" + tex] = tex else: # Share unpadded texture coordinates. texcoords[tex] = "l_texcoord" texcoordPadding["l_texcoord"] = None texcoordSets = list(enumerate(texcoordPadding.keys())) text = "//Cg\n" text += "void vshader(float4 vtx_position : POSITION,\n" text += " out float4 l_position : POSITION,\n" for texcoord, padTex in texcoordPadding.items(): if padTex is not None: text += " uniform float4 texpad_tx%s,\n" % (padTex) if ("HalfPixelShift" in configuration): text += " uniform float4 texpix_tx%s,\n" % (padTex) for i, name in texcoordSets: text += " out float2 %s : TEXCOORD%d,\n" % (name, i) text += " uniform float4x4 mat_modelproj)\n" text += "{\n" text += " l_position = mul(mat_modelproj, vtx_position);\n" for texcoord, padTex in texcoordPadding.items(): if padTex is None: text += " %s = vtx_position.xz * float2(0.5, 0.5) + float2(0.5, 0.5);\n" % ( texcoord) else: text += " %s = (vtx_position.xz * texpad_tx%s.xy) + texpad_tx%s.xy;\n" % ( texcoord, padTex, padTex) if ("HalfPixelShift" in configuration): text += " %s += texpix_tx%s.xy * 0.5;\n" % (texcoord, padTex) text += "}\n" text += "void fshader(\n" for i, name in texcoordSets: text += " float2 %s : TEXCOORD%d,\n" % (name, i) for key in self.textures: text += " uniform sampler2D k_tx" + key + ",\n" if ("CartoonInk" in configuration): text += " uniform float4 k_cartoonseparation,\n" text += " uniform float4 k_cartooncolor,\n" text += " uniform float4 texpix_txaux,\n" if ("BlurSharpen" in configuration): text += " uniform float4 k_blurval,\n" if ("VolumetricLighting" in configuration): text += " uniform float4 k_casterpos,\n" text += " uniform float4 k_vlparams,\n" text += " out float4 o_color : COLOR)\n" text += "{\n" text += " o_color = tex2D(k_txcolor, %s);\n" % ( texcoords["color"]) if ("CartoonInk" in configuration): text += CARTOON_BODY % {"texcoord": texcoords["aux"]} if ("AmbientOcclusion" in configuration): text += " o_color *= tex2D(k_txssao2, %s).r;\n" % ( texcoords["ssao2"]) if ("BlurSharpen" in configuration): text += " o_color = lerp(tex2D(k_txblur1, %s), o_color, k_blurval.x);\n" % ( texcoords["blur1"]) if ("Bloom" in configuration): text += " o_color = saturate(o_color);\n" text += " float4 bloom = 0.5 * tex2D(k_txbloom3, %s);\n" % ( texcoords["bloom3"]) text += " o_color = 1-((1-bloom)*(1-o_color));\n" if ("ViewGlow" in configuration): text += " o_color.r = o_color.a;\n" if ("VolumetricLighting" in configuration): text += " float decay = 1.0f;\n" text += " float2 curcoord = %s;\n" % (texcoords["color"]) text += " float2 lightdir = curcoord - k_casterpos.xy;\n" text += " lightdir *= k_vlparams.x;\n" text += " half4 sample = tex2D(k_txcolor, curcoord);\n" text += " float3 vlcolor = sample.rgb * sample.a;\n" text += " for (int i = 0; i < %s; i++) {\n" % (int( configuration["VolumetricLighting"].numsamples)) text += " curcoord -= lightdir;\n" text += " sample = tex2D(k_tx%s, curcoord);\n" % ( configuration["VolumetricLighting"].source) text += " sample *= sample.a * decay;//*weight\n" text += " vlcolor += sample.rgb;\n" text += " decay *= k_vlparams.y;\n" text += " }\n" text += " o_color += float4(vlcolor * k_vlparams.z, 1);\n" if ("GammaAdjust" in configuration): gamma = configuration["GammaAdjust"] if gamma == 0.5: text += " o_color.rgb = sqrt(o_color.rgb);\n" elif gamma == 2.0: text += " o_color.rgb *= o_color.rgb;\n" elif gamma != 1.0: text += " o_color.rgb = pow(o_color.rgb, %ff);\n" % ( gamma) if ("Inverted" in configuration): text += " o_color = float4(1, 1, 1, 1) - o_color;\n" text += "}\n" self.finalQuad.setShader(Shader.make(text)) for tex in self.textures: self.finalQuad.setShaderInput("tx" + tex, self.textures[tex]) self.task = taskMgr.add(self.update, "common-filters-update") if (changed == "CartoonInk") or fullrebuild: if ("CartoonInk" in configuration): c = configuration["CartoonInk"] self.finalQuad.setShaderInput( "cartoonseparation", Vec4(c.separation, 0, c.separation, 0)) self.finalQuad.setShaderInput("cartooncolor", c.color) if (changed == "BlurSharpen") or fullrebuild: if ("BlurSharpen" in configuration): blurval = configuration["BlurSharpen"] self.finalQuad.setShaderInput( "blurval", Vec4(blurval, blurval, blurval, blurval)) if (changed == "Bloom") or fullrebuild: if ("Bloom" in configuration): bloomconf = configuration["Bloom"] intensity = bloomconf.intensity * 3.0 self.bloom[0].setShaderInput("blend", bloomconf.blendx, bloomconf.blendy, bloomconf.blendz, bloomconf.blendw * 2.0) self.bloom[0].setShaderInput( "trigger", bloomconf.mintrigger, 1.0 / (bloomconf.maxtrigger - bloomconf.mintrigger), 0.0, 0.0) self.bloom[0].setShaderInput("desat", bloomconf.desat) self.bloom[3].setShaderInput("intensity", intensity, intensity, intensity, intensity) if (changed == "VolumetricLighting") or fullrebuild: if ("VolumetricLighting" in configuration): config = configuration["VolumetricLighting"] tcparam = config.density / float(config.numsamples) self.finalQuad.setShaderInput("vlparams", tcparam, config.decay, config.exposure, 0.0) if (changed == "AmbientOcclusion") or fullrebuild: if ("AmbientOcclusion" in configuration): config = configuration["AmbientOcclusion"] self.ssao[0].setShaderInput( "params1", config.numsamples, -float(config.amount) / config.numsamples, config.radius, 0) self.ssao[0].setShaderInput("params2", config.strength, config.falloff, 0, 0) self.update() return True
def __init__(self, markerImage='marker.jpg', calib_file='test.npz'): ShowBase.__init__(self) base.disableMouse() self.marker = cv2.imread(markerImage) self.marker = cv2.flip(self.marker, 0) self.kp_marker, self.des_marker = getDes(self.marker) if useCamera: self.cap = cv2.VideoCapture(0) ret, frame = self.cap.read() else: ret, frame = True, cv2.imread("sample_0.jpg") if ret: self.frame = frame self.criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) with np.load(calib_file) as calib_File: self.K = calib_File['mtx'] self.D = calib_File['coef'] (h, w) = frame.shape[0:2] print w, h far = 100 near = 0.1 fovx, fovy, f, (cx, cy), a = cv2.calibrationMatrixValues( self.K, (w, h), w, h) print fovx, fovy, f, cx, cy base.camLens.setFilmSize(w, h) base.camLens.setFilmOffset(w * 0.5 - cx, h * 0.5 - cy) base.camLens.setFocalLength(f) base.camLens.setFov(fovx, fovy) base.camLens.setNearFar(near, far) #base.camLens.setCoordinateSystem(4) base.camLens.setCoordinateSystem(4) #base.camLens.setViewVector(Vec3(0,0,1), Vec3(0,1,0)) #self.render.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise)) self.tex = Texture("detect") #self.buff.getTexture() self.tex.setCompression(Texture.CMOff) self.tex.setup2dTexture(w, h, Texture.TUnsignedByte, Texture.FRgb) self.b = OnscreenImage(parent=render2d, image=self.tex) base.cam.node().getDisplayRegion(0).setSort(20) self.taskMgr.add(self.updateFrameTask, "UpdateCameraFrameTask") self.modelroot = NodePath('ARRootNode') self.modelroot.reparentTo(self.render) ''' self.x = self.loader.loadModel("models/box") self.x.reparentTo(self.modelroot) self.x.setScale(3, 0.1, 0.1) self.x.setPos(0, -0.05, -0.05) self.x.setColor(1,0,0,1,1) self.y = self.loader.loadModel("models/box") self.y.reparentTo(self.modelroot) self.y.setScale(0.1, 3, 0.1) self.y.setPos(-0.05, 0, -0.05) self.y.setColor(0,1,0,1,1) self.z = self.loader.loadModel("models/box") self.z.reparentTo(self.modelroot) self.z.setScale(0.1, 0.1, 3) self.z.setPos(-0.05, -0.05, 0) self.z.setColor(0,0,1,1,1) ''' self.panda = NodePath('PandaRoot') self.panda.reparentTo(self.modelroot) # Load and transform the panda actor. self.pandaActor = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor.setScale(0.003, 0.003, 0.003) self.pandaActor.reparentTo(self.panda) self.pandaActor.loop("walk") self.pandaActor.setH(180) #self.pandaMotion = MopathInterval("Panda Path", self.panda, "Interval Name") self.pathCurve = createNurbsCurve() for i in range(0, 30): self.pathCurve.addPoint( (random.uniform(1, 7), random.uniform(1, 7), 0)) ''' self.pathCurve.addPoint((1, 5, 0)) self.pathCurve.addPoint((5, 5, 0)) self.pathCurve.addPoint((5, 1, 0)) self.pathCurve.addPoint((1, 1, 0)) ''' curveNode = self.pathCurve.getNodepath() self.myMopath = Mopath() self.myMopath.loadNodePath(curveNode) self.myMopath.fFaceForward = True myInterval = MopathInterval(self.myMopath, self.panda, duration=100, name="Name") myInterval.loop()
def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None): """ Causes the scene to be rendered into the supplied textures instead of into the original window. Puts a fullscreen quad into the original window to show the render-to-texture results. Returns the quad. Normally, the caller would then apply a shader to the quad. To elaborate on how this all works: * An offscreen buffer is created. It is set up to mimic the original display region - it is the same size, uses the same clear colors, and contains a DisplayRegion that uses the original camera. * A fullscreen quad and an orthographic camera to render that quad are both created. The original camera is removed from the original window, and in its place, the orthographic quad-camera is installed. * The fullscreen quad is textured with the data from the offscreen buffer. A shader is applied that tints the results pink. * Automatic shader generation NOT enabled. If you have a filter that depends on a render target from the auto-shader, you either need to set an auto-shader attrib on the main camera or scene, or, you need to provide these outputs in your own shader. * All clears are disabled on the original display region. If the display region fills the whole window, then clears are disabled on the original window as well. It is assumed that rendering the full-screen quad eliminates the need to do clears. Hence, the original window which used to contain the actual scene, now contains a pink-tinted quad with a texture of the scene. It is assumed that the user will replace the shader on the quad with a more interesting filter. """ if (textures): colortex = textures.get("color", None) depthtex = textures.get("depth", None) auxtex = textures.get("aux", None) auxtex0 = textures.get("aux0", auxtex) auxtex1 = textures.get("aux1", None) else: auxtex0 = auxtex auxtex1 = None if (colortex == None): colortex = Texture("filter-base-color") colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup = (depthtex, colortex, auxtex0, auxtex1) # Choose the size of the offscreen buffer. (winx, winy) = self.getScaledSize(1,1,1) buffer = self.createBuffer("filter-base", winx, winy, texgroup) if (buffer == None): return None cm = CardMaker("filter-base-quad") cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(Vec4(1,0.5,0.5,1)) cs = NodePath("dummy") cs.setState(self.camstate) # Do we really need to turn on the Shader Generator? #cs.setShaderAuto() if (auxbits): cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) self.camera.node().setInitialState(cs.getState()) quadcamnode = Camera("filter-quad-cam") lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) self.setStackedClears(buffer, self.rclears, self.wclears) if (auxtex0): buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, Vec4(0.5, 0.5, 1.0, 0.0)) if (auxtex1): buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1) self.region.disableClears() if (self.isFullscreen()): self.win.disableClears() dr = buffer.makeDisplayRegion() dr.disableClears() dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1, 1, 1)) return quad
def __init__(self, actor, state, lvl): #Setzte die Parameter self.CActor = actor #Spieler erstellen self.CGame = state #FSM - Gamestate erstellen self.mission = lvl #Aktuelle Mission self.mMission = None #Grundeinstellen fuer die Welt base.disableMouse() #Mouse ausmachen self.slowdown = 1 #Schnelligkeitsfaktor 1=Normal self.hud = False file, filename, description = imp.find_module("mission" + str(self.mission)) self.mMission = imp.load_module("mission" + str(self.mission), file, filename, description) #SPIELER - Variablen self.oldactorlevel = self.CActor.getLevel() self.CActor.CActorShip.setX( -165) #Setze den Spieler links im Bildschirm self.CActor.CActorShip.setY(0) self.CActor.nActorShip.reparentTo(render) self.CActor.CActorShip.getWeapon().setWeapon( "laserGun") #Standardwaffe setzen self.maxshield = self.CActor.CActorShip.getShield( ) #Schild speichern um Prozent berechnen zu koennen self.hitted = False #Variable um abzufragen ob man getroffen wurde self.dead = False #Spieler lebt self.lbullets = [] #Spielerbullets self.lbulletsspeed = [] self.lcanon = [] #Spielercanonbullets self.lcanonspeed = [] self.cameraeffectx = 0 #X-Wert der Camera um eine Sinuskurve zu implementieren self.cameraeffectamplitude = 5 #Die Amplitude der Sinuswelle - Maxima self.exppercent = (self.CActor.getExperience() * 100 ) / self.CActor.getMaxExperience() #EXP in Prozent self.oldcash = self.CActor.getMoney() self.secweapon = 3 #Resultattexte, wenn die Mission zu ende ist self.txtresultmission = addText(-0.15, 0.35, "") self.txtresultkills = addText(-0.15, 0.25, "") self.txtresultleft = addText(-0.15, 0.20, "") self.txtresultcash = addText(-0.15, 0.15, "") self.txtresultlevel = addText(-0.15, 0.10, "") self.txtresultmessage = addText(-0.15, 0.0, "") #ALLES FUER MOTION BLUR *********************************************************************** #Eine Texture erstellen, welches in das Hauptfenster kopiert wird self.CTex = Texture() self.CTex.setMinfilter(Texture.FTLinear) base.win.addRenderTexture(self.CTex, GraphicsOutput.RTMTriggeredCopyTexture) #Eine andere 2D Kamera erstellen, welches vor der Hauptkamera gerendert wird self.backcam = base.makeCamera2d(base.win, sort=-10) self.background = NodePath("background") self.backcam.reparentTo(self.background) self.background.setDepthTest(0) self.background.setDepthWrite(0) self.backcam.node().getDisplayRegion(0).setClearDepthActive(0) #Zwei Texturekarten ersten. Eins bevor, eins danach self.bcard = base.win.getTextureCard() self.bcard.reparentTo(self.background) self.bcard.setTransparency(1) self.fcard = base.win.getTextureCard() self.fcard.reparentTo(render2d) self.fcard.setTransparency(1) #********************************************************************************************** #Drops als Liste self.ldrop = [] #Explosionen - oder besser gesagt Splittereffekt als Liste self.lexplosions = [] #Soundklasse erstellen um Zugriff auf die Sound zu haben self.CSound = SoundMng() self.CSound.sndFlyAmbience.play() #GEGNER - Variablen self.destroyedenemy = 0 self.lostenemy = 0 self.lenemys = [] #Gegnerspeicher self.lbulletsenemy = [] #Gegnerbullets self.newwave = False #Boolean,welches eine neue Gegnerwelle angibt #Effekte self.CEffects = Effects() #Effektklasse erstellen #self.CEffects.createSpaceStars("particle/background.ptf") #Hintergrundeffekt erstellen #Die Game-Loop Voreinstellungen self.gameTask = taskMgr.add(self.gameLoop, "gameLoop") self.gameTask.last = 0 self.gameTask.nextbullet = 0 #Timer wann geschossen werden darf, vom Spieler self.gameTask.gotHit = 0 self.gameTask.lnextenemybullet = [ ] #Timer wann geschossen werden darf, unabhaengig von welche Gegner self.gameTask.resultkills = 0 #Timer fuer die Kills, im Resultat self.gameTask.resultleft = 0 #Timer fuer die geflohenen Gegner, im Resultat self.gameTask.introduction = 0 self.gameTask.introdelete = 0 self.gameTask.won = 0 self.resultcounter = 0 #Zeahler der die Nummern der Kills im Result aktualisiert self.resultcounterleft = 0 #Zeahler der die Nummern der geflohenen Gegner im Result aktualisiert self.introcounter = 0 self.ldata = [] self.readytospawn = False self.musicplayed = False self.musicplayed2 = False self.resultplayed = False #2D Kamera erstellen lens = OrthographicLens() lens.setFilmSize(350, 250) base.cam.node().setLens(lens)