def unload(self): self.notify.info("unload()") if hasattr(self, 'loader'): self.loader.exit() self.loader.unload() del self.loader del self.parentFSM del self.fsm self.dnaStore.reset_nodes() self.dnaStore.reset_hood_nodes() self.dnaStore.reset_place_nodes() self.dnaStore.reset_hood() self.dnaStore.reset_fonts() self.dnaStore.reset_DNA_vis_groups() self.dnaStore.reset_textures() self.dnaStore.reset_block_numbers() self.dnaStore.reset_block_zones() self.dnaStore.reset_suit_points() del self.dnaStore self.deleteCurrentSky() self.stopSuitEffect(0) self.ignoreAll() ModelPool.garbageCollect() TexturePool.garbageCollect() StateData.unload(self)
def unload(self): self.ignoreCollisions() self.removeCollisions() self.removeObject() self.removeNode() ModelPool.garbageCollect() TexturePool.garbageCollect()
def apply(self, nodePath): texture = self.get_texture() if not texture: return #if 'palette' in texture.name and not getattr(texture, 'edited', False): # texture.name = texture.name.replace('palette', 'palette_converted') if texture.alpha_name: #if 'palette' in texture.alpha_name and not getattr(texture, 'edited', False): # texture.alpha_name = texture.alpha_name.replace('palette', 'palette_converted') tex = TexturePool.load_texture(texture.name, texture.alpha_name) else: tex = TexturePool.load_texture(texture.name) if not tex: print('Texture missing!', texture.name, texture.alpha_name) return #texture.edited = True tex.set_wrap_u(texture.wrap_u) tex.set_wrap_v(texture.wrap_v) tex.set_minfilter(texture.minfilter) tex.set_magfilter(texture.magfilter) tex.set_anisotropic_degree(texture.anisotropic_degree) nodePath.setTexture(tex, 0)
def removeEverything(self): for task in self.taskMgr.getTasks(): if task.getName() not in ['dataLoop', 'igLoop']: task.remove() camera.reparentTo(render) for tex in render.findAllTextures(): tex.releaseAll() for tex in aspect2d.findAllTextures(): tex.releaseAll() for tex in render2d.findAllTextures(): tex.releaseAll() for tex in hidden.findAllTextures(): tex.releaseAll() for node in render.findAllMatches("**;+s"): node.removeNode() for node in aspect2d.findAllMatches("**;+s"): node.removeNode() for node in render2d.findAllMatches("**;+s"): node.removeNode() for node in hidden.findAllMatches("**;+s"): node.removeNode() TexturePool.garbageCollect() ModelPool.garbageCollect() RenderState.garbageCollect() RenderState.clearCache() RenderState.clearMungerCache() self.win.getGsg().getPreparedObjects().releaseAll() self.graphicsEngine.renderFrame()
def reloadTexture(self): TexturePool.releaseAllTextures() tex = loader.loadTexture('custom.png') tex.setMinfilter(Texture.FTLinearMipmapLinear) tex.setMagfilter(Texture.FTLinear) self.legs.find('**/' + self.shoesOptions[self.shoesChoice]).setTexture( tex, 1)
def changeMap(self, newMap="map.png"): # self.frameMap["image"] = newMap # self.frameMap.setImage() self.frameMap.clearTexture() TexturePool.releaseTexture(self.tex) self.tex = loader.loadTexture( Filename.fromOsSpecific(os.path.join(self.path, newMap))) self.frameMap["frameTexture"] = self.tex
def enterAvChoose(self, newToonSlot=None): ModelPool.garbageCollect() TexturePool.garbageCollect() self.avChooser.load() self.avChooser.enter(newToonSlot) if newToonSlot is None: self.playTheme() self.accept("enterMakeAToon", self.__handleMakeAToonReq) self.accept("avChooseDone", self.__handleAvChooseDone)
def enterAvChoose(self): ModelPool.garbageCollect() TexturePool.garbageCollect() self.avChooser.load() self.avChooser.enter() if not self.music: self.music = base.loadMusic(CIGlobals.getThemeSong()) base.playMusic(self.music, volume=0.75, looping=1) self.accept('enterMakeAToon', self.__handleMakeAToonReq) self.accept('avChooseDone', self.__handleAvChooseDone)
def _update_stats(self, task=None): """ Updates the stats overlay """ clock = Globals.clock self._debug_lines[0].text = "{:3.0f} fps | {:3.1f} ms | {:3.1f} ms max".format( clock.get_average_frame_rate(), 1000.0 / max(0.001, clock.get_average_frame_rate()), clock.get_max_frame_duration() * 1000.0) text = "{:4d} render states | {:4d} transforms" text += " | {:4d} commands | {:4d} lights | {:5d} shadow sources " text += "| {:3.1f}% atlas usage" self._debug_lines[1].text = text.format( RenderState.get_num_states(), TransformState.get_num_states(), self._pipeline.light_mgr.cmd_queue.num_processed_commands, self._pipeline.light_mgr.num_lights, self._pipeline.light_mgr.num_shadow_sources, self._pipeline.light_mgr.shadow_atlas_coverage) text = "Pipeline: {:3.0f} MiB VRAM | {:5d} images | {:5d} textures | " text += "{:5d} render targets | {:3d} plugins" tex_memory, tex_count = self._buffer_viewer.stage_information self._debug_lines[2].text = text.format( tex_memory / (1024**2), len(Image.REGISTERED_IMAGES), tex_count, RenderTarget.NUM_ALLOCATED_BUFFERS, len(self._pipeline.plugin_mgr.enabled_plugins)) text = "Scene: {:4.0f} MiB VRAM | {:3d} textures | {:4d} geoms " text += "| {:4d} nodes | {:7,.0f} vertices | {:5.0f} MiB vTX data " scene_tex_size = 0 for tex in TexturePool.find_all_textures(): scene_tex_size += tex.estimate_texture_memory() self._debug_lines[3].text = text.format( scene_tex_size / (1024**2), len(TexturePool.find_all_textures()), self._analyzer.get_num_geoms(), self._analyzer.get_num_nodes(), self._analyzer.get_num_vertices(), self._analyzer.get_vertex_data_size() / (1024**2), ) text = "{} ({:1.3f}) | {:3d} daytime settings | X {:3.1f} Y {:3.1f} Z {:3.1f}" self._debug_lines[4].text = text.format( self._pipeline.daytime_mgr.formatted_time, self._pipeline.daytime_mgr.time, len(self._pipeline.plugin_mgr.day_settings), Globals.base.camera.get_x(Globals.base.render), Globals.base.camera.get_y(Globals.base.render), Globals.base.camera.get_z(Globals.base.render),) if task: return task.again
def unload(self): Place.Place.unload(self) self.parentFSM.getStateNamed('cogdoInterior').removeChild(self.fsm) del self.parentFSM del self.fsm self.ignoreAll() ModelPool.garbageCollect() TexturePool.garbageCollect() self.townBattle.unload() self.townBattle.cleanup() del self.townBattle for i in xrange(1, 3): Suit.unloadSuits(i)
def doSceneCleanup(): from panda3d.core import ModelPool, TexturePool, RenderState, RenderAttrib, TransformState, GeomCacheManager ModelPool.garbageCollect() TexturePool.garbageCollect() RenderState.clearMungerCache() RenderState.clearCache() RenderState.garbageCollect() RenderAttrib.garbageCollect() TransformState.clearCache() TransformState.garbageCollect() GeomCacheManager.getGlobalPtr().flush() base.graphicsEngine.renderFrame()
def test(self): print "\n\nAdding children with attach_sprite" src1 = TexturePool.loadTexture("../Res/btn_left.png") src2 = TexturePool.loadTexture("../Res/btn_right.png") start = time.time() iterations = 100000 for i in xrange(iterations): sprite = self.attach_sprite(src1, i * 10.0, 0.0) # sprite.set_right(50) dur = (time.time() - start) * 1000.0 print iterations, "Sprites created in", round(dur, 2), "ms, that is", round(dur / iterations, 8), "ms per sprite" # self.ls() print "\n\nMoving children with set_left" start = time.time() iterations = self.get_child_count() for sprite in self.children(): sprite.set_left(10) dur = (time.time() - start) * 1000.0 print iterations, "Sprites moved in", round(dur, 2), "ms, that is", round(dur / iterations, 8), "ms per sprite" print "\n\nChanging sprite images with set_texture" start = time.time() iterations = self.get_child_count() for sprite in self.children(): sprite.set_texture(src2) dur = (time.time() - start) * 1000.0 print iterations, "Sprites changed in", round(dur, 2), "ms, that is", round(dur / iterations, 8), "ms per iteration" # self.ls() print "\n\nRemoving all childrens (child by child, with remove_child)" start = time.time() iterations = self.get_child_count() for sprite in self.children(): self.remove_child(sprite) dur = (time.time() - start) * 1000.0 print iterations, "Sprites removed in", round(dur, 2), "ms, that is", round(dur / iterations, 8), "ms per sprite" print "Sprites left: ", self.get_child_count() print "\n\nDone"
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 reloadTextures(textureName=''): vfs = VirtualFileSystem.getGlobalPtr() for file in glob.glob('resources/non-mf/phase_*/'): mount_point = '/' + str(os.path.split(file[:-1])[1]) vfs.mount(Filename(file), Filename(mount_point), 0) if textureName: pool = TexturePool.findAllTextures('*' + textureName + '*') else: pool = TexturePool.findAllTextures() for texture in pool: texture.reload() if textureName: return "Reloaded all textures matching '%s'" % textureName return 'Reloaded all of the textures!'
def __init__(self, filename): vfs = VirtualFileSystem.getGlobalPtr() #self.material = BSPMaterial.getFromFile(filename) self.material = TexturePool.loadTexture(filename) self.filename = filename if self.material: #.hasKeyvalue("$basetexture"): # baseTexturePath = self.material.getKeyvalue("$basetexture") if True: #vfs.exists(baseTexturePath): #imageData = bytes(VirtualFileSystem.getGlobalPtr().readFile(baseTexturePath, True)) pimage = PNMImage() self.material.store(pimage, 0, 0) ss = StringStream() pimage.write(ss, "tmp.png") imageData = bytes(ss) byteArray = QtCore.QByteArray.fromRawData(imageData) image = QtGui.QImage.fromData(byteArray) self.pixmap = QtGui.QPixmap.fromImage(image) self.icon = QtGui.QIcon(self.pixmap) self.size = LVector2i(pimage.getXSize(), pimage.getYSize()) print(pimage, self.size) else: self.size = LVector2i(64, 64) self.icon = None self.pixmap = None else: self.size = LVector2i(64, 64) self.icon = None self.pixmap = None
def __init__(self, verbose_name, source_path): self.name = verbose_name self.path = source_path self.tex = TexturePool.load_texture(source_path) self.w = self.tex.get_x_size() self.h = self.tex.get_y_size() self.area = self.w * self.h self.assigned_pos = None
def p_store_texture(p): filename = p[4] if len(p) == 7: filename = p[5] name = p[3] if len(p) == 7: name = p[4] p.parser.dnaStore.storeCatalogCode(p[3], name) texture = TexturePool.loadTexture(Filename(filename)) p.parser.dnaStore.storeTexture(name, texture)
def setBlurredHeightmap(self, hmap_path): assert(self._parent) self.blurred_heightmap_tex = TexturePool.loadTexture(Filename.fromOsSpecific(hmap_path)) self.blurred_heightmap_tex.setWrapU(SamplerState.WMClamp) self.blurred_heightmap_tex.setWrapV(SamplerState.WMClamp) self.blurred_heightmap_tex.setFormat(Texture.F_r16) self.blurred_heightmap_tex.setKeepRamImage(False) self.blurred_heightmap_tex.setMinfilter(SamplerState.FTLinearMipmapLinear) self.blurred_heightmap_tex.setMagfilter(SamplerState.FTLinear) self.blurred_heightmap_tex.setAnisotropicDegree(0) print "set blurred heightmap" self._element_node.setShaderInput("blurredHeightmap", self.blurred_heightmap_tex)
def unload(self): StateData.unload(self) if self.animatedFish: self.animatedFish.cleanup() self.animatedFish.removeNode() self.animatedFish = None self.parentFSMState.removeChild(self.fsm) del self.parentFSMState del self.animatedFish self.geom.removeNode() del self.geom del self.fsm del self.hood del self.playground del self.music del self.interiorMusic del self.battleMusic del self.bossBattleMusic del self.tournamentMusic self.ignoreAll() ModelPool.garbageCollect() TexturePool.garbageCollect() return
def loadTerrain(name, widthScale = 0.5, heightScale = 10.0): """load terrain stuff""" global app, terrain, terrainRootNetPos steerMgr = OSSteerManager.get_global_ptr() terrain = GeoMipTerrain("terrain") heightField = PNMImage(Filename(dataDir + "/heightfield.png")) terrain.set_heightfield(heightField) # sizing environmentWidthX = (heightField.get_x_size() - 1) * widthScale environmentWidthY = (heightField.get_y_size() - 1) * widthScale environmentWidth = (environmentWidthX + environmentWidthY) / 2.0 terrain.get_root().set_sx(widthScale) terrain.get_root().set_sy(widthScale) terrain.get_root().set_sz(heightScale) # set other terrain's properties blockSize, minimumLevel = (64, 0) nearPercent, farPercent = (0.1, 0.7) terrainLODmin = min(minimumLevel, terrain.get_max_level()) flattenMode = GeoMipTerrain.AFM_off terrain.set_block_size(blockSize) terrain.set_near(nearPercent * environmentWidth) terrain.set_far(farPercent * environmentWidth) terrain.set_min_level(terrainLODmin) terrain.set_auto_flatten(flattenMode) # terrain texturing textureStage0 = TextureStage("TextureStage0") textureImage = TexturePool.load_texture(Filename("terrain.png")) terrain.get_root().set_tex_scale(textureStage0, 1.0, 1.0) terrain.get_root().set_texture(textureStage0, textureImage, 1) # reparent this Terrain node path to the object node path terrain.get_root().reparent_to(steerMgr.get_reference_node_path()) terrain.get_root().set_collide_mask(mask) terrain.get_root().set_name(name) # brute force generation bruteForce = True terrain.set_bruteforce(bruteForce) # Generate the terrain terrain.generate() # check if terrain needs update or not if not bruteForce: # save the net pos of terrain root terrainRootNetPos = terrain.get_root().get_net_transform().get_pos() # Add a task to keep updating the terrain app.taskMgr.add(terrainUpdate, "terrainUpdate", appendTask=True) # return terrain.get_root()
def setHeightmap(self, hmap_path): assert (self._parent) self.heightmap_tex = TexturePool.loadTexture( Filename.fromOsSpecific(hmap_path)) # self.heightmap_tex = loader.loadTexture(hmap_path) self.heightmap_tex.setWrapU(SamplerState.WMClamp) self.heightmap_tex.setWrapV(SamplerState.WMClamp) self.heightmap_tex.setFormat(Texture.F_r16) self.heightmap_tex.setKeepRamImage(False) self.heightmap_tex.setMinfilter(SamplerState.FTLinearMipmapLinear) self.heightmap_tex.setMagfilter(SamplerState.FTLinear) self.heightmap_tex.setAnisotropicDegree(0) self._element_node.setShaderInput("heightmap", self.heightmap_tex)
def __init__(self, text): LUIObject.__init__(self, 50, 30) print "\nTest case 1: Setting & Getting size" print self.get_size() self.set_size(100, 200) print self.get_size() print "\nTest case 2: Using 'default:image'" self.imgMid = LUISprite(self, "btn_mid", "default") print "\nTest case 3: Attaching an arbitrary image" self.imgRight3 = LUISprite(self, "../Res/btn_mid.png", 32, 32) print "\nTest case 4: Attaching a texture object" self.imgRight4 = LUISprite(self, TexturePool.loadTexture("../Res/btn_right.png")) print "\nTest case 5: Attaching a non-existing image" self.imgRight5 = LUISprite(self, "Res/DoesNotExist.png") print "\nTest case 6: Attaching a sprite, but not storing a reference" LUISprite(self, "btn_right", "default") print "\nTest case 7: Attaching and instantly removing a sprite" tmp = LUISprite(self, "btn_right", "default") self.remove_child(tmp) print "\nTest case 8: Resizing widget" self.set_size(30, 40) print "\nTest case 9: Positioning widget" self.set_pos(50, 50) print "\nTesting if all pointers are still valid" for sprite in self.children: start = LTexCoord() end = LTexCoord() sprite.get_uv_range(start, end) sprite.print_vertices() print "Test passed."
def update(self): if self.memUsageText: memstr = str( round(MemoryMonitor.getEstimatedMemUsage() / 1024.0 / 1024.0, 2)) numTextureBytes = 0 renderTextures = Globals.render.findAllTextures() for tex in renderTextures: numTextureBytes += MemoryMonitor._calculateTexSize(tex) texstr = str(round(numTextureBytes / 1024.0 / 1024.0, 2)) otherTextures = TexturePool.findAllTextures() numOtherBytes = 0 for tex in otherTextures: if tex not in renderTextures: numOtherBytes += MemoryMonitor._calculateTexSize(tex) otherstr = str(round(numOtherBytes / 1024.0 / 1024.0, 2)) self.memUsageText.setText("VRAM Usage: " + memstr + " MB / Textures: " + texstr + " MB / Other: " + otherstr + " MB") if self.fpsText: clock = Globals.clock self.fpsText.setText( "Frame time over {:3.1f}s Avg: {:3.2f} Max: {:3.2f} Deviation: {:3.2f}" .format(clock.getAverageFrameRateInterval(), 1000.0 / clock.getAverageFrameRate(), clock.getMaxFrameDuration() * 1000.0, clock.calcFrameRateDeviation() * 1000.0)) if self.stateText: self.stateText.setText( "{:6d} Render States, {:6d} Transform States".format( RenderState.getNumStates(), TransformState.getNumStates())) if self.perfOverlay: self.perfOverlay.update()
def update(self): if self.memUsageText: memstr = str(round(MemoryMonitor.getEstimatedMemUsage() / 1024.0 / 1024.0, 2)) numTextureBytes = 0 renderTextures = Globals.render.findAllTextures() for tex in renderTextures: numTextureBytes += MemoryMonitor._calculateTexSize(tex) texstr = str(round(numTextureBytes / 1024.0 / 1024.0, 2)) otherTextures = TexturePool.findAllTextures() numOtherBytes = 0 for tex in otherTextures: if tex not in renderTextures: numOtherBytes += MemoryMonitor._calculateTexSize(tex) otherstr = str(round(numOtherBytes / 1024.0 / 1024.0, 2)) self.memUsageText.setText("VRAM Usage: " + memstr + " MB / Textures: " + texstr + " MB / Other: " + otherstr + " MB") if self.fpsText: clock = Globals.clock self.fpsText.setText("Frame time over {:3.1f}s Avg: {:3.2f} Max: {:3.2f} Deviation: {:3.2f}".format( clock.getAverageFrameRateInterval(), 1000.0 / clock.getAverageFrameRate(), clock.getMaxFrameDuration() * 1000.0, clock.calcFrameRateDeviation() * 1000.0 )) if self.stateText: self.stateText.setText("{:6d} Render States, {:6d} Transform States".format(RenderState.getNumStates(), TransformState.getNumStates())) if self.perfOverlay: self.perfOverlay.update()
def update_stats(self, task=None): """ Updates the stats overlay """ clock = Globals.clock self.debug_lines[0].text = "{:3.0f} fps | {:3.1f} ms | {:3.1f} ms max".format( clock.get_average_frame_rate(), 1000.0 / max(0.001, clock.get_average_frame_rate()), clock.get_max_frame_duration() * 1000.0) if not self.advanced_info: return task.again if task else None text = "{:4d} states | {:4d} transforms " text += "| {:4d} cmds | {:4d} lights | {:4d} shadows " text += "| {:5.1f}% atlas usage" self.debug_lines[1].text = text.format( RenderState.get_num_states(), TransformState.get_num_states(), self.pipeline.light_mgr.cmd_queue.num_processed_commands, self.pipeline.light_mgr.num_lights, self.pipeline.light_mgr.num_shadow_sources, self.pipeline.light_mgr.shadow_atlas_coverage) text = "Internal: {:3.0f} MB VRAM | {:5d} img | {:5d} tex | " text += "{:5d} fbos | {:3d} plugins | {:2d} views ({:2d} active)" tex_memory, tex_count = self.buffer_viewer.stage_information views, active_views = 0, 0 for target in RenderTarget.REGISTERED_TARGETS: if not target.create_default_region: num_regions = target.internal_buffer.get_num_display_regions() for i, region in enumerate(target.internal_buffer.get_display_regions()): # Skip overlay display region if i == 0 and num_regions > 1: continue views += 1 active_views += 1 if target.active and region.active else 0 self.debug_lines[2].text = text.format( tex_memory / (1024**2), len(Image.REGISTERED_IMAGES), tex_count, RenderTarget.NUM_ALLOCATED_BUFFERS, len(self.pipeline.plugin_mgr.enabled_plugins), views, active_views) text = "Scene: {:4.0f} MB VRAM | {:3d} tex | {:4d} geoms " text += "| {:4d} nodes | {:7,.0f} vertices" scene_tex_size = 0 for tex in TexturePool.find_all_textures(): scene_tex_size += tex.estimate_texture_memory() self.debug_lines[3].text = text.format( scene_tex_size / (1024**2), len(TexturePool.find_all_textures()), self.analyzer.get_num_geoms(), self.analyzer.get_num_nodes(), self.analyzer.get_num_vertices(), ) sun_vector = Vec3(0) if self.pipeline.plugin_mgr.is_plugin_enabled("scattering"): sun_vector = self.pipeline.plugin_mgr.instances["scattering"].sun_vector text = "Time: {} ({:1.3f}) | Sun {:0.2f} {:0.2f} {:0.2f}" text += " | X {:3.1f} Y {:3.1f} Z {:3.1f}" text += " | {:2d} tasks | scheduled: {:2d}" self.debug_lines[4].text = text.format( self.pipeline.daytime_mgr.formatted_time, self.pipeline.daytime_mgr.time, sun_vector.x, sun_vector.y, sun_vector.z, Globals.base.camera.get_x(Globals.base.render), Globals.base.camera.get_y(Globals.base.render), Globals.base.camera.get_z(Globals.base.render), self.pipeline.task_scheduler.num_tasks, self.pipeline.task_scheduler.num_scheduled_tasks,) text = "Scene shadows: " if "pssm" in self.pipeline.plugin_mgr.enabled_plugins: focus = self.pipeline.plugin_mgr.instances["pssm"].scene_shadow_stage.last_focus if focus is not None: text += "{:3.1f} {:3.1f} {:3.1f} r {:3.1f}".format( focus[0].x, focus[0].y, focus[0].z, focus[1]) else: text += "none" else: text += "inactive" text += " | HPR ({:3.1f}, {:3.1f}, {:3.1f}) | {:4d} x {:4d} pixels @ {:3.1f} %" text += " | {:3d} x {:3d} tiles" self.debug_lines[5].text = text.format( Globals.base.camera.get_h(Globals.base.render), Globals.base.camera.get_p(Globals.base.render), Globals.base.camera.get_r(Globals.base.render), Globals.native_resolution.x, Globals.native_resolution.y, self.pipeline.settings["pipeline.resolution_scale"] * 100.0, self.pipeline.light_mgr.num_tiles.x, self.pipeline.light_mgr.num_tiles.y,) if task: return task.again
def reloadTextures(self): pool = TexturePool.findAllTextures() for texture in pool: print("Reloading " + str(texture)) texture.reload()
def __init__(self, name, size=10000, resolution=1024): """Arguments: size -- Edge length of the water square. resolution -- Texture size of the rendered reflection buffer. """ # Uncomment to see the output of the refclection buffer. base.bufferViewer.toggleEnable() AssetBase.__init__(self) self.name = name self.cm = CardMaker("water surface") self.cm.setFrame(-0.5 * size, 0.5 * size, -0.5 * size, 0.5 * size) self.cm.setHasUvs(True) self.node = NodePath(self.cm.generate()) self.node.setP(self.node, -90) self.node.flattenLight() self.node.hide(BitMask32.bit(1)) # self.node.setTwoSided(True) self.node.setShaderOff() # size of one texture tile in meters self.tex_size = 100.0 diffuse = TexturePool.loadTexture("textures/water.diffuse.png") diffuse.setWrapU(Texture.WMRepeat) diffuse.setWrapV(Texture.WMRepeat) diffuse.setMinfilter(Texture.FTLinearMipmapLinear) diffuse.setMagfilter(Texture.FTLinearMipmapLinear) self.diffuse_stage = TextureStage("diffuse") self.diffuse_stage.setSort(2) self.node.setTexture(self.diffuse_stage, diffuse) self.node.setTexScale(self.diffuse_stage, size / self.tex_size, size / self.tex_size) # Reflection camera renders to 'buffer' which is projected onto the # water surface. buffer = base.win.makeTextureBuffer("water reflection", resolution, resolution) buffer.setClearColor(Vec4(0, 0, 0, 1)) self.refl_cam = base.makeCamera(buffer) self.refl_cam.reparentTo(self.node) self.refl_cam.node().setCameraMask(BitMask32.bit(1)) self.refl_cam.node().getLens().setFov(base.camLens.getFov()) self.refl_cam.node().getLens().setNearFar(1, 100000) plane = PlaneNode("water culling plane", Plane(Vec3(0, 0, 1), Point3(0, 0, 0))) cfa = CullFaceAttrib.makeReverse() cpa = ClipPlaneAttrib.make(PlaneNode.CEVisible, plane) rs = RenderState.make(cfa, cpa) self.refl_cam.node().setInitialState(rs) reflection = buffer.getTexture() reflection.setMinfilter(Texture.FTLinear) reflection.setMagfilter(Texture.FTLinear) self.refl_stage = TextureStage("reflection") self.refl_stage.setSort(1) self.node.projectTexture(self.refl_stage, reflection, base.cam) self.node.setTexture(self.refl_stage, reflection) # Blend between diffuse and reflection. self.diffuse_stage.setColor(VBase4(1, 1, 1, 0.2)) # opacity of 20% self.diffuse_stage.setCombineRgb( TextureStage.CMInterpolate, TextureStage.CSTexture, TextureStage.COSrcColor, TextureStage.CSPrevious, TextureStage.COSrcColor, TextureStage.CSConstant, TextureStage.COSrcAlpha, ) self.addTask(self.update, name="water update", sort=1, taskChain="world")
def __init__(self, name, size=10000, resolution=1024): """Arguments: size -- Edge length of the water square. resolution -- Texture size of the rendered reflection buffer. """ # Uncomment to see the output of the refclection buffer. base.bufferViewer.toggleEnable() AssetBase.__init__(self) self.name = name self.cm = CardMaker("water surface") self.cm.setFrame(-0.5 * size, 0.5 * size, -0.5 * size, 0.5 * size) self.cm.setHasUvs(True) self.node = NodePath(self.cm.generate()) self.node.setP(self.node, -90) self.node.flattenLight() self.node.hide(BitMask32.bit(1)) #self.node.setTwoSided(True) self.node.setShaderOff() # size of one texture tile in meters self.tex_size = 100.0 diffuse = TexturePool.loadTexture("textures/water.diffuse.png") diffuse.setWrapU(Texture.WMRepeat) diffuse.setWrapV(Texture.WMRepeat) diffuse.setMinfilter(Texture.FTLinearMipmapLinear) diffuse.setMagfilter(Texture.FTLinearMipmapLinear) self.diffuse_stage = TextureStage("diffuse") self.diffuse_stage.setSort(2) self.node.setTexture(self.diffuse_stage, diffuse) self.node.setTexScale(self.diffuse_stage, size / self.tex_size, size / self.tex_size) # Reflection camera renders to 'buffer' which is projected onto the # water surface. buffer = base.win.makeTextureBuffer("water reflection", resolution, resolution) buffer.setClearColor(Vec4(0, 0, 0, 1)) self.refl_cam = base.makeCamera(buffer) self.refl_cam.reparentTo(self.node) self.refl_cam.node().setCameraMask(BitMask32.bit(1)) self.refl_cam.node().getLens().setFov(base.camLens.getFov()) self.refl_cam.node().getLens().setNearFar(1, 100000) plane = PlaneNode("water culling plane", Plane(Vec3(0, 0, 1), Point3(0, 0, 0))) cfa = CullFaceAttrib.makeReverse() cpa = ClipPlaneAttrib.make(PlaneNode.CEVisible, plane) rs = RenderState.make(cfa, cpa) self.refl_cam.node().setInitialState(rs) reflection = buffer.getTexture() reflection.setMinfilter(Texture.FTLinear) reflection.setMagfilter(Texture.FTLinear) self.refl_stage = TextureStage("reflection") self.refl_stage.setSort(1) self.node.projectTexture(self.refl_stage, reflection, base.cam) self.node.setTexture(self.refl_stage, reflection) # Blend between diffuse and reflection. self.diffuse_stage.setColor(VBase4(1, 1, 1, 0.2)) # opacity of 20% self.diffuse_stage.setCombineRgb( TextureStage.CMInterpolate, TextureStage.CSTexture, TextureStage.COSrcColor, TextureStage.CSPrevious, TextureStage.COSrcColor, TextureStage.CSConstant, TextureStage.COSrcAlpha) self.addTask(self.update, name="water update", sort=1, taskChain="world")
def exit(self): self.fsm.requestFinalState() self.ignoreAll() ModelPool.garbageCollect() TexturePool.garbageCollect() StateData.exit(self)