def setup(self): self.tex1 = MovieTexture('videos/saturn5_apollo_launch.mp4') assert self.tex1.read('videos/saturn5_apollo_launch.mp4') self.tex2 = MovieTexture('videos/boards_eye_view.mp4') assert self.tex2.read('videos/boards_eye_view.mp4') self.cm1 = CardMaker('saturn') self.cm1.setFrameFullscreenQuad() self.cm1.setUvRange(self.tex1) self.card1 = NodePath(self.cm1.generate()) self.card1.reparentTo(self.path) self.card1.setPos(0,0,10) self.card1.setP(50) self.cm2 = CardMaker('board') self.cm2.setFrameFullscreenQuad() self.cm2.setUvRange(self.tex2) self.card2 = NodePath(self.cm2.generate()) self.card2.reparentTo(self.path) self.card2.setPos(0,0,-10) self.card2.setP(-50) self.card1.setTexture(self.tex1) self.card1.setTexScale(TextureStage.getDefault(), self.tex1.getTexScale()) self.card2.setTexture(self.tex2) self.card2.setTexScale(TextureStage.getDefault(), self.tex2.getTexScale()) self.card1.setScale(10) self.card2.setScale(10)
def loadPrisonCrater(): ## Sky color base.win.setClearColor(Vec4(.46,.824,.904,1)) ## Load Ground sand = loader.loadModel("data/models/sand.bam") sand.reparentTo(render) sand.setTexScale(TextureStage.getDefault(),5000,5000) craterwalls = loader.loadModel("data/models/craterwalls.bam") craterwalls.reparentTo(render) craterwalls.setTexScale(TextureStage.getDefault(),500,50) ## World Effects fog = Fog("Fog") fog.setColor(255,215,143) fog.setExpDensity(.0000001) render.setFog(fog) alight = render.attachNewNode(AmbientLight("Abient")) alight.node().setColor(Vec4(.9,.9,.9,1)) render.setLight(alight) sun = DirectionalLight('Sun') sun.setColor(Vec4(1,1,1,1)) sunNP = render.attachNewNode(sun) sunNP.setPos(0,0,4000) sunNP.setHpr(0,-90,0) render.setLight(sunNP)
def __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 changeDKFrame(self, frame): dk = self.scene.find("hammer1") #remember that the name is wrong here if( frame == 1): dk.setTexOffset(TextureStage.getDefault() , 0.140867 - 0.0446603 ,0.0 ) if( frame == 2): dk.setTexOffset(TextureStage.getDefault() , 0.0431023 - 0.0446603 , 0.806672 - 0.703844 ) if( frame == 3): dk.setTexOffset(TextureStage.getDefault() , 0 ,0.0 ) """
def update_key_map(control_name, control_state, entity, walking): key_map[control_name] = control_state if walking: entity.find('**/+SequenceNode').node().loop(True, 0, 9) else: entity.find('**/+SequenceNode').node().loop(True, 10, 19) if control_name == "left": entity.setTexScale(TextureStage.getDefault(), -1, 1) elif control_name == "right": entity.setTexScale(TextureStage.getDefault(), 1, 1)
def patchInvertDDSV(np,tex,debug=False): from panda3d.core import Texture from panda3d.core import TextureStage cmpr = tex.getCompression() if cmpr == Texture.CMDxt1 or cmpr == Texture.CMDxt5: scale2d = np.getTexScale( TextureStage.getDefault() ) scale2d[1] = -scale2d[1] np.setTexScale( TextureStage.getDefault(), scale2d ) else: if debug: print( " NOT INVERTING.. type was " + str(tex.getCompression()))
def patchInvertDDSV(np, tex, debug=False): from panda3d.core import Texture from panda3d.core import TextureStage cmpr = tex.getCompression() if cmpr == Texture.CMDxt1 or cmpr == Texture.CMDxt5: scale2d = np.getTexScale(TextureStage.getDefault()) scale2d[1] = -scale2d[1] np.setTexScale(TextureStage.getDefault(), scale2d) else: if debug: print(" NOT INVERTING.. type was " + str(tex.getCompression()))
def flipTexture(self): """ Sets the texture coordinates of the texture to the current frame""" sU = self.offsetX * self.repeatX sV = self.offsetY * self.repeatY oU = 0 + self.frames[self.currentFrame].col * self.uSize oV = 1 - self.frames[self.currentFrame].row * self.vSize - self.offsetY if self.flip['x']: sU *= -1 oU = self.uSize + self.frames[self.currentFrame].col * self.uSize if self.flip['y']: sV *= -1 oV = 1 - self.frames[self.currentFrame].row * self.vSize self.node.setTexScale(TextureStage.getDefault(), sU, sV) self.node.setTexOffset(TextureStage.getDefault(), oU, oV)
def texture_offset(self, value): if self.model and self.texture: self.model.setTexOffset(TextureStage.getDefault(), value[0], value[1]) self.texture = self.texture self.set_shader_input('texture_offset', value) self._texture_offset = value
def __init__(self, shared, checker_size=10.0, vel=0.0, c_high=255, c_low=0, opto_intensities=(4050, 0), switch_schedule=(10.0, 50.0)): StimulusBase.__init__(self, shared) # Parameters: self.param_checker_size = checker_size self.param_vel = vel self.param_c_high = c_high self.param_c_low = c_low self.opto_intensities = opto_intensities self.opto_switch_schedule = switch_schedule # Set up texture: shape_horizontal = int(self.calibrated_length / self.param_checker_size) shape_vertical = int(shape_horizontal / self.getAspectRatio()) self.texture_checkers = create_checker_texture(self.param_c_low, self.param_c_high, (shape_vertical, shape_horizontal)) self.image_checkers = OnscreenImage(self.texture_checkers, pos=(0, 0, 0), scale=(self.getAspectRatio(), 1.0, 1.0), hpr=(0, 0, 0)) self.image_checkers.setTexOffset(TextureStage.getDefault(), 0.0, 0.0) # Set up opto logic: self.opto_toggle = False self.last_checkpoint = 0.0 self.shared.opto_intensity.value = self.opto_intensities[1]
def create_geom(self, loader): """Creates self.geom_node from self.terrain_map.""" # geom_builder = GeomBuilder('floor') map_size = len(self.terrain_map) unit_size = map_params.unit_size start_pos = -map_size*unit_size/2 # colors = map_params.colors # geom_builder.add_rect( # colors.floor, # start_pos, start_pos, 0, # -start_pos, -start_pos, 0 # ) card_maker = CardMaker("cm") card_maker.setFrame( Point3(-start_pos, -start_pos, 0), Point3(+start_pos, -start_pos, 0), Point3(+start_pos, +start_pos, 0), Point3(-start_pos, +start_pos, 0) ) card_maker.setColor(map_params.colors.floor) floor_node = NodePath(card_maker.generate()) floor_node.reparentTo(self.geom_node) # floor_node.setHpr(0, 90, 0) # floor_node.setPos(0, 0, 0) tex = loader.loadTexture('models/floor.png') floor_node.setTexture(tex, 1) floor_node.setTexScale(TextureStage.getDefault(), map_size, map_size) def get(i, j): return isinstance(self.get_tile(i, j), Wall) wall_count = 0 for i in range(map_size-1): for j in range(map_size-1): if any([get(i, j), get(i+1, j), get(i+1, j+1), get(i, j+1)]): wall_count += 1 def callback(): self.geom_node.clearModelNodes() self.geom_node.flattenStrong() threads = Threads(wall_count, callback) for i in range(map_size-1): for j in range(map_size-1): current_position = ( start_pos+i*unit_size, start_pos+j*unit_size, 0 ) render_wall( current_position, [get(i, j), get(i+1, j), get(i+1, j+1), get(i, j+1)], ((i+j) & 1)+1, self.geom_node, loader, threads )
def update_anims(self, event): '''Meant to run as taskmanager routine. Update entity's animation's frame each self.animations_speed seconds''' #safety check to dont do anything if custom anim isnt set or entity is #already dead. #Will maybe remove death statement later (coz gibs), idk if self.dead or not self.current_animation: return event.cont #ensuring that whatever below only runs if enough time has passed dt = globalClock.get_dt() self.animations_timer -= dt if self.animations_timer > 0: return event.cont #log.debug("Updating anims") #resetting anims timer, so countdown above will start again self.animations_timer = self.animations_speed if self.current_frame < self.animations[self.current_animation][1]: self.current_frame += 1 else: self.current_frame = self.animations[self.current_animation][0] self.object.set_tex_offset(TextureStage.getDefault(), *self.sprites[self.current_frame]) return event.cont
def __init__(self): ShowBase.__init__(self) props = WindowProperties( ) props.setTitle( 'Differentiable Physics Engine' ) self.win.requestProperties( props ) self.t = 0 self.starttime = time.time() #self.setFrameRateMeter(True) cour = self.loader.loadFont('cmtt12.egg') self.textObject = OnscreenText(font= cour, text = 'abcdefghijklmnopqrstuvwxyz', pos=(0, -0.045), parent = self.a2dTopCenter, bg=(0,0,0,1), fg =(1,1,1,1), scale = 0.07, mayChange=True) cm = CardMaker("ground") cm.setFrame(-2000, 2000, -2000, 2000) cm.setUvRange(Point2(-2000/5,-2000/5),Point2(2000/5,2000/5)) tmp = self.render.attachNewNode(cm.generate()) tmp.reparentTo(self.render) tmp.setPos(0, 0, 0) tmp.lookAt((0, 0, -2)) tmp.setColor(1.0,1.0,1.0,1) tmp.setTexScale(TextureStage.getDefault(), 1, 1) tex = self.loader.loadTexture('textures/grid2.png') tex.setWrapU(Texture.WMRepeat) tex.setWrapV(Texture.WMRepeat) tmp.setTexture(tex,1) self.setBackgroundColor(0.0, 191.0/255.0, 1.0, 1.0) #color of the sky ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) ambientLightNP = self.render.attachNewNode(ambientLight) self.render.setLight(ambientLightNP) # Directional light 01 directionalLight = DirectionalLight('directionalLight') directionalLight.setColor(Vec4(0.8, 0.8, 0.8, 1)) directionalLightNP = self.render.attachNewNode(directionalLight) # This light is facing backwards, towards the camera. directionalLightNP.setHpr(-60, -50, 0) directionalLightNP.node().setScene(self.render) directionalLightNP.node().setShadowCaster(True) directionalLightNP.node().getLens().setFov(40) directionalLightNP.node().getLens().setNearFar(10, 100) self.render.setLight(directionalLightNP) # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") # Load the environment model. self.objects = dict() self.names = [] data = pickle.load(open("../PhysXVids/state-dump-exp15.pkl","rb")) self.json = json.loads(data["json"]) # json.loads(data["json"]) self.states = data["states"] self.load_robot_model() self.dt = self.json["integration_parameters"]["time_step"] self.setupKeys() self.robot_id = 0
def playVideo(self, video): # check if it is loadable try: # load the video texture self.tex = MovieTexture("MovieTexture") #print video self.tex.read(video) # Set up a fullscreen card to set the video texture on it. cm = CardMaker("Movie Card") cm.setFrameFullscreenQuad() cm.setUvRange(self.tex) self.card = NodePath(cm.generate()) self.card.reparentTo(base.render2d) self.card.setTexture(self.tex) self.card.setTexScale(TextureStage.getDefault(), self.tex.getTexScale()) # load the video self.sound = loader.loadSfx(video) # Synchronize the video to the sound. self.tex.synchronizeTo(self.sound) # play the video and audio self.sound.play() # start the task which checks if the video is finished taskMgr.add(self.isVideoFinish, "task_isVideoFinised") except: logging.error("Failed to load video: %s %s", video, sys.exc_info()) self.stopVideo() base.messenger.send(self.vidFinEvt)
def __init__( self, emitter, # the node which is emitting texture, # particle's image rate=.001, # the emission rate gravity=-9.81, # z-component of the gravity force vel=1.0, # length of emission vector partDuration=1.0 # single particle's duration ): self.__emitter = emitter self.__texture = texture # let's compute the total number of particles self.__numPart = int(round(partDuration * 1 / rate)) self.__rate = rate self.__gravity = gravity self.__vel = vel self.__partDuration = partDuration self.__nodepath = render.attachNewNode(self.__node()) self.__nodepath.setTransparency(True) # particles have alpha self.__nodepath.setBin("fixed", 0) # render it at the end self.__setTextures() self.__setShader() self.__nodepath.setRenderModeThickness(10) # we want sprite particles self.__nodepath.setTexGen(TextureStage.getDefault(), TexGenAttrib.MPointSprite) self.__nodepath.setDepthWrite(False) # don't sort the particles self.__upd_tsk = taskMgr.add(self.__update, "update")
def apply(self, instance): if self.texture is None: self.texture = loader.loadTexture(self.file) instance.setTexGen(TextureStage.getDefault(), TexGenAttrib.MPointSprite) instance.setTransparency(TransparencyAttrib.MAlpha) instance.setTexture(self.texture, 1)
def create_floor(self): '''Generate flat floor of size, provided to class''' #todo: add fallback values in case size hasnt been specified log.debug(f"Generating the floor") #initializing new cardmaker object #which is essentially our go-to way to create flat models floor = CardMaker('floor') #setting up card size floor.set_frame(*self.map_size) #attaching card to render and creating it's object #I honestly dont understand the difference between #this and card.reparent_to(render) #but both add object to scene graph, making it visible floor_object = render.attach_new_node(floor.generate()) floor_object.set_texture(self.texture) #determining how often do we need to repeat our texture texture_x = self.texture.get_orig_file_x_size() texture_y = self.texture.get_orig_file_y_size() repeats_x = ceil(self.size_x / texture_x) repeats_y = ceil(self.size_y / texture_y) #repeating texture to avoid stretching when possible floor_object.set_tex_scale(TextureStage.getDefault(), repeats_x, repeats_y) #arranging card's angle floor_object.look_at((0, 0, -1)) floor_object.set_pos(0, 0, FLOOR_LAYER)
def enterShow(self, ts=0): self.darkenInterior() self.cr.playGame.hood.loader.interiorMusic.stop() videoFile = CinemaGlobals.Cinemas[self.cinemaIndex][0] audioFile = CinemaGlobals.Cinemas[self.cinemaIndex][1] self.movieTex = MovieTexture(self.uniqueName("movieTex")) self.movieTex.read(videoFile) card = CardMaker(self.uniqueName('movieCard')) card.setFrame(-1.5, 1.5, -1, 1) self.movieCard = NodePath(card.generate()) self.movieCard.reparentTo(render) self.movieCard.setPos( self.interior.find('**/sign_origin;+s').getPos(render)) #self.movieCard.setX(self.movieCard, -0.05) self.movieCard.setHpr( self.interior.find('**/sign_origin;+s').getHpr(render)) self.movieCard.setDepthWrite(1, 1) self.movieCard.setTwoSided(True) self.movieCard.setTexture(self.movieTex) self.movieCard.setTexScale(TextureStage.getDefault(), self.movieTex.getTexScale()) self.movieCard.setScale(2.5) self.movieSound = base.loadSfx(audioFile) self.movieTex.synchronizeTo(self.movieSound) self.movieTrack = SoundInterval(self.movieSound, name=self.uniqueName('movieTrack')) self.movieTrack.setDoneEvent(self.movieTrack.getName()) self.acceptOnce(self.movieTrack.getDoneEvent(), self.fsm.request, ['off']) self.movieTrack.start(ts)
def __init__(self, base, obj, **kwargs): super(GalaxyView, self).__init__(base, obj, **kwargs) array = GeomVertexArrayFormat() array.addColumn(InternalName.make('vertex'), 3, Geom.NTFloat32, Geom.CPoint) array.addColumn(InternalName.make('color'), 4, Geom.NTFloat32, Geom.CColor) array.addColumn(InternalName.make('size'), 1, Geom.NTFloat32, Geom.COther) gmformat = GeomVertexFormat() gmformat.addArray(array) gmformat = GeomVertexFormat.registerFormat(gmformat) vdata = GeomVertexData('points', gmformat, Geom.UHDynamic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') size = GeomVertexWriter(vdata, 'size') self.node = NodePath('galaxy') self.node.reparentTo(self.base.render) self.node.setTransparency(TransparencyAttrib.MAlpha) lumsort = sorted([star.luminosity for star in self.obj.stars]) #highest_luminosity = lumsort[-1] median_luminosity = lumsort[len(lumsort) / 2] for star in self.obj.stars: vertex.addData3f(star.galpos.x, star.galpos.y, star.galpos.z) color.addData4f(star.red, star.green, star.blue, 1.0) #size.addData1f(min(100, max(5, 10-star.magnitude/2))) sizeval = 10 + log(star.luminosity) size.addData1f(min(30, max(10, sizeval))) prim = GeomPoints(Geom.UHStatic) prim.addConsecutiveVertices(0, len(self.obj.stars)) prim.closePrimitive() geom = Geom(vdata) geom.addPrimitive(prim) node = GeomNode('gnode') node.addGeom(geom) galaxy_node = self.node.attachNewNode(node) galaxy_node.setRenderModeThickness(1) ts = TextureStage.getDefault() #TextureStage('ts') #ts.setMode(TextureStage.MGlow) galaxy_node.setTexGen(ts, TexGenAttrib.MPointSprite) galaxy_node.setTexture( ts, self.base.loader.loadTexture('texture/flare.png')) #galaxy_node.setRenderModePerspective(True) galaxy_node.setBin("unsorted", 1) galaxy_node.setDepthWrite(0) galaxy_node.setTransparency(1) self.setup_glow_shader() """
def update(): vel = physics.getPhysicsObject().getVelocity() prevFrame = data.node().getPythonTag("subclass").frame if( vel.x < 0): data.node().getPythonTag("subclass").frame = (prevFrame - 1)%4 else: data.node().getPythonTag("subclass").frame = (prevFrame + 1)%4 visual.setTexOffset(TextureStage.getDefault() , self.barrels_frames[prevFrame] ,0.0 )
def apply(self, instance): if self.texture is None: if self.image is None: self.image = self.generate() self.texture = Texture() self.texture.load(self.image) instance.setTexGen(TextureStage.getDefault(), TexGenAttrib.MPointSprite) instance.setTransparency(TransparencyAttrib.MAlpha, 1) instance.setTexture(TextureStage('ts'), self.texture, 1)
def update_texture(self, task): self.plane.setTexOffset(TextureStage.getDefault(), self.tx, 0) self.texture_update += 1 if self.texture_update > 6: self.tx += self.tx_offset self.texture_update = 0 return task.cont
def createGround(self, terrainData): """Create ground using a heightmap""" # Create heightfield for physics heightRange = terrainData["heightRange"] # Image needs to have dimensions that are a power of 2 + 1 heightMap = PNMImage(self.basePath + terrainData["elevation"]) xdim = heightMap.getXSize() ydim = heightMap.getYSize() shape = BulletHeightfieldShape(heightMap, heightRange, ZUp) shape.setUseDiamondSubdivision(True) np = self.outsideWorldRender.attachNewNode(BulletRigidBodyNode("terrain")) np.node().addShape(shape) np.setPos(0, 0, 0) self.physicsWorld.attachRigidBody(np.node()) # Create graphical terrain from same height map terrain = GeoMipTerrain("terrain") terrain.setHeightfield(heightMap) terrain.setBlockSize(32) terrain.setBruteforce(True) rootNP = terrain.getRoot() rootNP.reparentTo(self.worldRender) rootNP.setSz(heightRange) offset = xdim / 2.0 - 0.5 rootNP.setPos(-offset, -offset, -heightRange / 2.0) terrain.generate() # Apply texture diffuse = self.loader.loadTexture(Filename(self.basePath + terrainData["texture"])) diffuse.setWrapU(Texture.WMRepeat) diffuse.setWrapV(Texture.WMRepeat) rootNP.setTexture(diffuse) textureSize = 6.0 ts = TextureStage.getDefault() rootNP.setTexScale(ts, xdim / textureSize, ydim / textureSize) # Create planes around area to prevent player flying off the edge # Levels can define barriers around them but it's probably a good # idea to leave this here just in case sides = ( (Vec3(1, 0, 0), -xdim / 2.0), (Vec3(-1, 0, 0), -xdim / 2.0), (Vec3(0, 1, 0), -ydim / 2.0), (Vec3(0, -1, 0), -ydim / 2.0), ) for sideNum, side in enumerate(sides): normal, offset = side sideShape = BulletPlaneShape(normal, offset) sideNode = BulletRigidBodyNode("side%d" % sideNum) sideNode.addShape(sideShape) self.physicsWorld.attachRigidBody(sideNode)
def _load_chairs(self): """Load and place chairs""" self.chairs = self.p_constants["NPHILOSOPHERS"] * [0] for i in xrange(self.p_constants["NPHILOSOPHERS"]): x, y, angle = self._get_chair_coord(i, 5.0) self.chairs[i] = self._load_model( "chair1", scale=[7, 7, 7], pos=[x, y - 1, 0], H=rad2deg(angle) + 15) self.chairs[i].setTexture(self.chair_tex) self.chairs[i].setTexScale( TextureStage.getDefault(), 0.005, 0.005)
def generate_sphere_map(self, size=512, name=f'sphere_map_{len(scene.entities)}'): from ursina import camera _name = 'textures/' + name + '.jpg' org_pos = camera.position camera.position = self.position base.saveSphereMap(_name, size=size) camera.position = org_pos print('saved sphere map:', name) self.model.setTexGen(TextureStage.getDefault(), TexGenAttrib.MEyeSphereMap) self.reflection_map = name
def _load_chairs(self): """Load and place chairs""" self.chairs = self.p_constants["NPHILOSOPHERS"] * [0] for i in xrange(self.p_constants["NPHILOSOPHERS"]): x, y, angle = self._get_chair_coord(i, 5.0) self.chairs[i] = self._load_model("chair1", scale=[7, 7, 7], pos=[x, y - 1, 0], H=rad2deg(angle) + 15) self.chairs[i].setTexture(self.chair_tex) self.chairs[i].setTexScale(TextureStage.getDefault(), 0.005, 0.005)
def init_ship(self, ship_model_path, player2=False): if player2 == True: pos = LPoint2(12, -8) category_bits = 0x0003 mask_bits = (0x0001 | 0x0002) else: pos = LPoint2(-12, 8) category_bits = 0x0002 mask_bits = (0x0001 | 0x0003) new_ship = loadObject(ship_model_path, scale=0.5) physic_debug, physic_body = new_physic_object(shape='box', scale=0.5, angular_dampning=5, linear_dampning=0.1, pos=pos, category_bits=category_bits, mask_bits=mask_bits) new_ship.reparentTo(render) new_ship.setTexRotate(TextureStage.getDefault(), 90) new_weapon = weapon() if player2 == True: shipname = "ship2" self.life_bar2 = loadObject(scale=0.5) self.life_bar2.setPos(-0.1, 0, 0.12) self.life_bar2.reparentTo(base.a2dBottomRight) self.life_bar2.setSz(0.005) self.energy_bar2 = loadObject(scale=0.5) self.energy_bar2.setPos(-0.1, 0, 0.215) self.energy_bar2.reparentTo(base.a2dBottomRight) self.energy_bar2.setSz(0.005) else: shipname = "ship" self.life_bar = loadObject(scale=0.5) self.life_bar.setPos(-0.1, 0, 0.12) self.life_bar.reparentTo(base.a2dBottomLeft) self.life_bar.setSz(0.005) self.energy_bar = loadObject(scale=0.5) self.energy_bar.setPos(-1, 0, 0.215) self.energy_bar.reparentTo(base.a2dBottomLeft) self.energy_bar.setSz(0.005) defines.ENTITIES[defines.ENTITY_ID] = { 'CATEGORY': shipname, 'E_FIELD_ENABLED': False, 'NODE': new_ship, 'PHYSIC_NODE': physic_debug, 'BODY': physic_body, 'SHIELD': 100.0, 'ENERGY': 100.0, 'WEAPON': new_weapon } defines.ENTITY_ID += 1
def updateBarrel(): vel = pBarrel.getPhysicsObject().getVelocity() frame = dNode.frame if( vel.x > 0 ): frame = (frame+1)%4 if( vel.x < 0): frame = (frame-1)%4 dNode.frame = frame vBarrel.setTexOffset( TextureStage.getDefault() , self.barrels_frames[frame] , 0 )
def prepare(self, curr_cond, stim_period=''): self.curr_cond = curr_cond if stim_period == '' else curr_cond[ stim_period] self.period = stim_period if not self.curr_cond: self.isrunning = False self.background_color = self.curr_cond['background_color'] # set background color self.set_background_color(*self.curr_cond['background_color']) # Set Ambient Light self.ambientLight.setColor(self.curr_cond['ambient_color']) # Set Directional Light self.lights = dict() self.lightsNP = dict() for idx, light_idx in enumerate(iterable(self.curr_cond['light_idx'])): self.lights[idx] = core.DirectionalLight('directionalLight_%d' % idx) self.lightsNP[idx] = self.render.attachNewNode(self.lights[idx]) self.render.setLight(self.lightsNP[idx]) self.lights[idx].setColor(tuple( self.curr_cond['light_color'][idx])) self.lightsNP[idx].setHpr(*self.curr_cond['light_dir'][idx]) # Set Object tasks self.objects = dict() for idx, obj in enumerate(iterable(self.curr_cond['obj_id'])): self.objects[idx] = Agent(self, self.get_cond('obj_', idx)) if 'movie_name' in self.curr_cond: self.movie = True loader = Loader(self) file_name = self.get_clip_info(self.curr_cond, 'file_name') self.mov_texture = loader.loadTexture(self.movie_path + file_name[0]) cm = CardMaker("card") tx_scale = self.mov_texture.getTexScale() cm.setFrame(-1, 1, -tx_scale[1] / tx_scale[0], tx_scale[1] / tx_scale[0]) self.movie_node = NodePath(cm.generate()) self.movie_node.setTexture(self.mov_texture, 1) self.movie_node.setPos(0, 100, 0) self.movie_node.setTexScale(TextureStage.getDefault(), self.mov_texture.getTexScale()) self.movie_node.setScale(48) self.movie_node.reparentTo(self.render) if not self.isrunning: self.timer.start() self.isrunning = True
def generate_cube_map(self, size=512, name=f'cube_map_{len(scene.entities)}'): from ursina import camera _name = 'textures/' + name org_pos = camera.position camera.position = self.position base.saveCubeMap(_name+'.jpg', size=size) camera.position = org_pos print('saved cube map:', name + '.jpg') self.model.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldCubeMap) self.reflection_map = _name + '#.jpg' self.model.setTexture(loader.loadCubeMap(_name + '#.jpg'), 1)
def createTile(self, x, y): # Set up the GeoMipTerrain terrain = GeoMipTerrain("terrain") terrain.setHeightfield("./height-map.png") # Set terrain properties terrain.setBlockSize(32) terrain.setNear(40) terrain.setFar(100) terrain.setFocalPoint(self.showBase.camera) #terrain.setAutoFlatten(GeoMipTerrain.AFMStrong) terrain.getRoot().setScale(1, 1, 1) terrain.getRoot().setPos(x * 128 - 64, y * 128 - 64, 0) terrain.getRoot().setTexture(TextureStage.getDefault(), self.showBase.loader.loadTexture("./grass-texture.png")) terrain.getRoot().setTexScale(TextureStage.getDefault(), 50) # Store the root NodePath for convenience root = terrain.getRoot() root.reparentTo(self.showBase.render) root.setSz(100) # Generate it. terrain.generate() return terrain
def loadBallModel(self): #loads the character, a ball model #ballModelStartPos = (-8, -8, 0.701) #THIS IS THE END ballModelStartPos = (8, 8, 13.301) #level 0 ballScale = 0.01 self.ballModel = loader.loadModel("/Users/jianwei/Documents/School/Freshman/Semester1/15-112/TERMPROJECT/Project/ball") self.ballModel.reparentTo(render) self.ballModel.setScale(ballScale) self.ballModel.setPos(ballModelStartPos) ### Setting ball texture ### texScale = 0.08 self.ballModel.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) self.ballModel.setTexProjector(TextureStage.getDefault(), render, self.ballModel) self.ballModel.setTexScale(TextureStage.getDefault(), texScale) tex = loader.load3DTexture('/Users/jianwei/Documents/School/Freshman/Semester1/15-112/TERMPROJECT/Project/ballTex/ballTex_#.png') self.ballModel.setTexture(tex)
def __init__(self, shared, lam=10.0, vel=10.0, c_high=255, c_low=0, color=(1.0, 1.0, 1.0)): StimulusBase.__init__(self, shared) # Parameters: self.param_lambda = lam # cm self.param_velocity = vel # cm/s self.param_c_high = c_high self.param_c_low = c_low self.param_color = np.array(color) # Set up simple image with grating: c1, c2 = self.param_color * self.param_c_low, self.param_color * self.param_c_high self.texture_grating = create_striped_texture(c1, c2, nearest=True) self.image_grating = OnscreenImage(self.texture_grating, pos=(0, 0, 0), scale=(self.getAspectRatio(), 1.0, 1.0), hpr=(0, 0, 0)) self.image_grating.setTexOffset(TextureStage.getDefault(), 0.0, 0.0) self.image_grating.setTexScale(TextureStage.getDefault(), self.calibrated_length / self.param_lambda)
def _load_bowls(self): """Load and place bowls""" self.bowls = [{} for x in xrange(self.p_constants["NPHILOSOPHERS"])] for i in xrange(self.p_constants["NPHILOSOPHERS"]): x, y, angle = self._get_chair_coord(i, 3.6) self.bowls[i]["bowl"] = self._load_model( "bowl", scale=[2, 2, 2], pos=[100, 100, 100], H=rad2deg(angle)) self.bowls[i]["pos"] = [x, y - 1, self.fork_height] self.bowls[i]["num_up"] = 0 self.bowls[i]["meals"] = 0 self.bowls[i]["bowl"].setTexture(self.bowl_tex) self.bowls[i]["bowl"].setTexScale( TextureStage.getDefault(), 0.005, 0.005)
def __init__(self): ShowBase.__init__(self) # self.wp = WindowProperties() self.wp.setSize(1280, 720) base.win.requestProperties(self.wp) self.fork_height = 2.3 self.frame_time = 0.0 self.textObject = OnscreenText(text='', pos=(-1.0, 0.9), scale=0.10, fg=(255, 255, 255, 200)) # create sockets, get h constants self.p_constants = get_constants() self.context, self.socket = self._create_socket_context() # Load textures self.bowl_tex = self.loader.loadTexture(ASSETS_DIR + "marble.jpg") self.wood_tex = self.loader.loadTexture(ASSETS_DIR + "derevo_mebel.jpg") self.chair_tex = self.loader.loadTexture(ASSETS_DIR + "02_1.bmp") self.black_tex = self.loader.loadTexture(ASSETS_DIR + "black.png") # Load models # Load environment (really just a plane) self.environ = self._load_model("house", scale=[25, 25, 25], pos=[0, 0, -10]) # Load the "table" self.table = self._load_model("round_table", scale=[27, 27, 14], pos=[0, 0, 0]) # Load and place forks, chairs self._load_forks() self._load_chairs() self._load_bowls() # Apply textures to models self.environ.setTexture(self.black_tex) self.table.setTexture(self.wood_tex) self.table.setTexScale(TextureStage.getDefault(), 0.005, 0.005) # Start sim self.rnum = 0 self.philos = subprocess.Popen("./philos", shell=True) # Tasks self.taskMgr.add(self.spin_camera, "spin_camera") self.taskMgr.add(self._comm, "comm")
def __init__(self): ShowBase.__init__(self) # self.wp = WindowProperties() self.wp.setSize(1280, 720) base.win.requestProperties(self.wp) self.fork_height = 2.3 self.frame_time = 0.0 self.textObject = OnscreenText(text='', pos=(-1.0, 0.9), scale = 0.10, fg=(255, 255, 255, 200)) # create sockets, get h constants self.p_constants = get_constants() self.context, self.socket = self._create_socket_context() # Load textures self.bowl_tex = self.loader.loadTexture( ASSETS_DIR + "marble.jpg") self.wood_tex = self.loader.loadTexture( ASSETS_DIR + "derevo_mebel.jpg") self.chair_tex = self.loader.loadTexture( ASSETS_DIR + "02_1.bmp") self.black_tex = self.loader.loadTexture(ASSETS_DIR + "black.png") # Load models # Load environment (really just a plane) self.environ = self._load_model( "house", scale=[25, 25, 25], pos=[0, 0, -10]) # Load the "table" self.table = self._load_model( "round_table", scale=[27, 27, 14], pos=[0, 0, 0]) # Load and place forks, chairs self._load_forks() self._load_chairs() self._load_bowls() # Apply textures to models self.environ.setTexture(self.black_tex) self.table.setTexture(self.wood_tex) self.table.setTexScale( TextureStage.getDefault(), 0.005, 0.005) # Start sim self.rnum = 0 self.philos = subprocess.Popen("./philos", shell=True) # Tasks self.taskMgr.add(self.spin_camera, "spin_camera") self.taskMgr.add(self._comm, "comm")
def _load_bowls(self): """Load and place bowls""" self.bowls = [{} for x in xrange(self.p_constants["NPHILOSOPHERS"])] for i in xrange(self.p_constants["NPHILOSOPHERS"]): x, y, angle = self._get_chair_coord(i, 3.6) self.bowls[i]["bowl"] = self._load_model("bowl", scale=[2, 2, 2], pos=[100, 100, 100], H=rad2deg(angle)) self.bowls[i]["pos"] = [x, y - 1, self.fork_height] self.bowls[i]["num_up"] = 0 self.bowls[i]["meals"] = 0 self.bowls[i]["bowl"].setTexture(self.bowl_tex) self.bowls[i]["bowl"].setTexScale(TextureStage.getDefault(), 0.005, 0.005)
def apply(self, shape, owner): if self.texture is None: if self.image is None: self.image = self.sprite.generate() texture = Texture() texture.load(self.image) self.texture = TransparentTexture(DirectTextureSource(texture), blend=TransparencyBlend.TB_PremultipliedAlpha) self.texture.set_tex_matrix(False) shape.instance.setTexGen(TextureStage.getDefault(), TexGenAttrib.MPointSprite) self.texture.apply(shape) shape.instance.set_depth_write(False) if self.background is not None: shape.instance.setBin('background', settings.deep_space_depth) owner.shader.apply(shape, self) shape.instance_ready = True
def updateBarrel(): vel = physics.getPhysicsObject().getVelocity() frame = dataNode.frame if (vel.x > 0): frame = (frame + 1) % 4 #vel.x = 5 if (vel.x < 0): frame = (frame - 1) % 4 #vel.x = -5 dataNode.frame = frame physics.getPhysicsObject().setVelocity(vel) visualFrame = self.barrels_frames[frame] visual.setTexOffset(TextureStage.getDefault(), visualFrame, 0.0)
def loadWallModel(self): #loads the wall model (the maze) wallScale = 0.3 wallModelName = self.randomWallModel() #randomly select a maze self.wallModel = loader.loadModel(wallModelName) self.wallModel.setScale(wallScale) self.wallModel.setPos(0, 0, 0) self.wallModel.setCollideMask(BitMask32.allOff()) self.wallModel.reparentTo(render) ### Setting Texture ### texScale = 0.08 self.wallModel.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldNormal) self.wallModel.setTexProjector(TextureStage.getDefault(), render, self.wallModel) self.wallModel.setTexScale(TextureStage.getDefault(), texScale) tex = loader.load3DTexture('/Users/jianwei/Documents/School/Freshman/Semester1/15-112/TERMPROJECT/Project/wallTex/wallTex_#.png') self.wallModel.setTexture(tex) #creating visual geometry collision self.wallModel.setCollideMask(BitMask32.bit(0))
def loadIcon(self, iconsFile, name): retVal = iconsFile.find(name) retVal.setBillboardAxis() retVal.reparentTo(self) dark = retVal.copyTo(NodePath()) dark.reparentTo(retVal) dark.setColor(0.5, 0.5, 0.5, 1) retVal.setEffect(DecalEffect.make()) retVal.setTransparency(TransparencyAttrib.MAlpha, 1) ll, ur = dark.getTightBounds() center = retVal.attachNewNode('center') center.setPos(0, 0, ll[2]) dark.wrtReparentTo(center) dark.setTexProjector(TextureStage.getDefault(), center, retVal) retVal.hide() return (retVal, center)
def init_ship(self, ship_model_path, player2=False): if player2 == True: pos = LPoint2(12,-8) category_bits = 0x0003 mask_bits = (0x0001 | 0x0002) else: pos = LPoint2(-12,8) category_bits = 0x0002 mask_bits = (0x0001 | 0x0003) new_ship = loadObject(ship_model_path, scale=0.5) physic_debug, physic_body = new_physic_object(shape='box', scale=0.5, angular_dampning=5, linear_dampning=0.1, pos=pos, category_bits=category_bits, mask_bits=mask_bits) new_ship.reparentTo(render) new_ship.setTexRotate(TextureStage.getDefault(), 90) new_weapon = weapon(); if player2 == True: shipname = "ship2" self.life_bar2 = loadObject(scale=0.5) self.life_bar2.setPos(-0.1,0, 0.12) self.life_bar2.reparentTo(base.a2dBottomRight) self.life_bar2.setSz(0.005) self.energy_bar2 = loadObject(scale=0.5) self.energy_bar2.setPos(-0.1,0, 0.215) self.energy_bar2.reparentTo(base.a2dBottomRight) self.energy_bar2.setSz(0.005) else: shipname = "ship" self.life_bar = loadObject(scale=0.5) self.life_bar.setPos(-0.1,0,0.12) self.life_bar.reparentTo(base.a2dBottomLeft) self.life_bar.setSz(0.005) self.energy_bar = loadObject(scale=0.5) self.energy_bar.setPos(-1,0,0.215) self.energy_bar.reparentTo(base.a2dBottomLeft) self.energy_bar.setSz(0.005) defines.ENTITIES[defines.ENTITY_ID] = {'CATEGORY':shipname,'E_FIELD_ENABLED': False, 'NODE':new_ship, 'PHYSIC_NODE':physic_debug, 'BODY':physic_body, 'SHIELD':100.0, 'ENERGY':100.0, 'WEAPON':new_weapon} defines.ENTITY_ID += 1
def createSky_(self,maxDistance=parameters["maxDistance"],loadNullSky=parameters["loadNullSky"],skyMapNull=parameters["skyMapNull"]): # self.skysphere = self.sb.loader.loadModel("models/solar_sky_sphere") # self.sky_tex = self.sb.loader.loadTexture("models/stars_1k_tex.jpg") # self.skysphere.setTexture(self.sky_tex, 1) # # self.skysphere.setEffect(CompassEffect.make(self.sb.render)) # self.skysphere.setScale(maxDistance) # bit less than "far" # self.skysphere.setZ(-3) # self.skysphere.reparentTo(self.sb.render) if loadNullSky: # if null, then create uniform back and sky # pass #todo. buttonify self.skysphere = self.sb.loader.loadModel(skyMapNull) self.skysphere.setEffect(CompassEffect.make(self.sb.render)) self.skysphere.setScale(maxDistance) # bit less than "far" self.skysphere.setZ(-3) # self.skysphere.setH(45) self.skysphere.reparentTo(self.sb.render) else: self.skysphere = self.sb.loader.loadModel(parameters['skyMap']) self.skysphere.setBin('background', 1) self.skysphere.setDepthWrite(0) self.skysphere.setPos(0,0,0) self.skysphere.setPos((513,513,0)) self.skysphere.setTexPos(TextureStage.getDefault(),(-513,-513,1000)) #don't change it here, do it in bam generator # self.skysphere.setTexHpr(TextureStage.getDefault(),(-513,-513,0)) self.skysphere.setScale(9000) # bit less than "far" self.skysphere.setEffect(CompassEffect.make(self.sb.render)) self.skysphere.reparentTo(self.sb.render)
def enterShow(self, ts = 0): self.darkenInterior() self.cr.playGame.hood.loader.interiorMusic.stop() videoFile = CinemaGlobals.Cinemas[self.cinemaIndex][0] audioFile = CinemaGlobals.Cinemas[self.cinemaIndex][1] self.movieTex = MovieTexture(self.uniqueName('movieTex')) self.movieTex.read(videoFile) card = CardMaker(self.uniqueName('movieCard')) card.setFrame(-1.5, 1.5, -1, 1) self.movieCard = NodePath(card.generate()) self.movieCard.reparentTo(render) self.movieCard.setPos(self.interior.find('**/sign_origin;+s').getPos(render)) self.movieCard.setHpr(self.interior.find('**/sign_origin;+s').getHpr(render)) self.movieCard.setDepthWrite(1, 1) self.movieCard.setTwoSided(True) self.movieCard.setTexture(self.movieTex) self.movieCard.setTexScale(TextureStage.getDefault(), self.movieTex.getTexScale()) self.movieCard.setScale(2.5) self.movieSound = base.loadSfx(audioFile) self.movieTex.synchronizeTo(self.movieSound) self.movieTrack = SoundInterval(self.movieSound, name=self.uniqueName('movieTrack')) self.movieTrack.setDoneEvent(self.movieTrack.getName()) self.acceptOnce(self.movieTrack.getDoneEvent(), self.fsm.request, ['off']) self.movieTrack.start(ts)
def __init__(self): ShowBase.__init__(self) self.cellmanager = CellManager(self) self.xray_mode = False self.show_model_bounds = False # Display instructions add_title("Panda3D Tutorial: Portal Culling") add_instructions(0.06, "[Esc]: Quit") add_instructions(0.12, "[W]: Move Forward") add_instructions(0.18, "[A]: Move Left") add_instructions(0.24, "[S]: Move Right") add_instructions(0.30, "[D]: Move Back") add_instructions(0.36, "Arrow Keys: Look Around") add_instructions(0.42, "[F]: Toggle Wireframe") add_instructions(0.48, "[X]: Toggle X-Ray Mode") add_instructions(0.54, "[B]: Toggle Bounding Volumes") # Setup controls self.keys = {} for key in ['arrow_left', 'arrow_right', 'arrow_up', 'arrow_down', 'a', 'd', 'w', 's']: self.keys[key] = 0 self.accept(key, self.push_key, [key, 1]) self.accept('shift-%s' % key, self.push_key, [key, 1]) self.accept('%s-up' % key, self.push_key, [key, 0]) self.accept('f', self.toggleWireframe) self.accept('x', self.toggle_xray_mode) self.accept('b', self.toggle_model_bounds) self.accept('escape', __import__('sys').exit, [0]) self.disableMouse() # Setup camera lens = PerspectiveLens() lens.setFov(60) lens.setNear(0.01) lens.setFar(1000.0) self.cam.node().setLens(lens) self.camera.setPos(-9, -0.5, 1) self.heading = -95.0 self.pitch = 0.0 # Load level geometry self.level_model = self.loader.loadModel('models/level') self.level_model.reparentTo(self.render) self.level_model.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) self.level_model.setTexProjector(TextureStage.getDefault(), self.render, self.level_model) self.level_model.setTexScale(TextureStage.getDefault(), 4) tex = self.loader.load3DTexture('models/tex_#.png') self.level_model.setTexture(tex) # Load cells self.cellmanager.load_cells_from_model('models/cells') # Load portals self.cellmanager.load_portals_from_model('models/portals') # Randomly spawn some models to test the portals self.models = [] for dummy in range(0, 500): pos = LPoint3((random.random() - 0.5) * 6, (random.random() - 0.5) * 6, random.random() * 7) cell = self.cellmanager.get_cell(pos) if cell is None: # skip if the random position is not over a cell continue dist = self.cellmanager.get_dist_to_cell(pos) if dist > 1.5: # skip if the random position is too far from ground continue box = self.loader.loadModel('box') box.setScale(random.random() * 0.2 + 0.1) box.setPos(pos) box.setHpr(random.random() * 360, random.random() * 360, random.random() * 360) box.reparentTo(cell.nodepath) self.models.append(box) self.taskMgr.add(self.update, 'main loop')
def main(): from direct.showbase.ShowBase import ShowBase from .util.util import startup_data, exit_cleanup, ui_text, console, frame_rate from .ui import CameraControl, Axis3d, Grid3d from .keys import AcceptKeys, callbacks base = ShowBase() base.disableMouse() base.setBackgroundColor(0,0,0) startup_data() frame_rate() uit = ui_text() con = console({}) ec = exit_cleanup() cc = CameraControl() ax = Axis3d() gd = Grid3d() ac = AcceptKeys() ### # XXX REAL CODE HERE ### size = 256 shift = .001 # .001 works with scale .499 and size 2 scale = 1/size - (1/ (size * 100)) #scale = 1 #shift = -size * .125 array = np.random.randint(0,255,(size,size,size)) #array = np.linspace(0,255,size**3).reshape(size,size,size) tex, memarray = make_texture3d(array) tex2 = Texture() tex2.setup2dTexture() # TODO how to read the matrix in?! geomNode = GeomNode('shader_test') geomNode.addGeom(make_cube(size,size,size)) nodePath = render.attachNewNode(geomNode) #embed() nodePath.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) nodePath.setTexProjector(TextureStage.getDefault(), render, nodePath) nodePath.setTexPos(TextureStage.getDefault(), shift, shift, shift) nodePath.setTexScale(TextureStage.getDefault(), scale) nodePath.setTexture(tex) #embed() #nodePath.setTexGen(TextureStage.getDefault(), 0, 0, 0) #bug? #""" #myShader = Shader.load(Shader.SL_GLSL, "my_vert.glsl", "my_frag.glsl")#, "my_geom.glsl") # wow, this actually... turns the box black or something, probably shound't attach the texture to the nodepath if we do it this way #nodePath.set_shader_input("my_param",(1,1,1)) #nodePath.set_shader_input('color.bgra', 10) # bad #myvec = Vec4(.2, 1.0, 1.0, .4) #embed() myShader = Shader.load(Shader.SL_GLSL, "simple_vert.glsl", "simple_frag.glsl") nodePath.set_shader(myShader) nodePath.set_shader_input('camera', camera) con.locals_['myShader'] = myShader con.locals_['nodePath'] = nodePath #nodePath.set_shader_input('textcoord', (1.0, .5)) #nodePath.set_shader_input("tex", tex2) #nodePath.set_shader_input("volume_tex", tex) #nodePath.set_shader_input("stepsize", .5) #""" base.run()
def __init__(self): self.base = ShowBase() self.thrust = 0.5 self.wind = 0.2 self.UP = Vec3(0, 0, 1) # might as well just make this a variable # set up camera self.base.disableMouse() self.base.camera.setPos(20, -20, 5) self.base.camera.lookAt(0, 0, 5) # Set up the collision traverser. If we bind it to base.cTrav, then Panda will handle # management of this traverser (for example, by calling traverse() automatically for us once per frame) self.base.cTrav = CollisionTraverser() # Now let's set up some collision bits for our masks self.ground_bit = 1 self.ball_bit = 2 self.base.setBackgroundColor(0.64, 0, 0) # First, we build a card to represent the ground cm = CardMaker('ground-card') cm.setFrame(-60, 60, -60, 60) card = self.base.render.attachNewNode(cm.generate()) card.lookAt(0, 0, -1) # align upright #tex = loader.loadTexture('maps/envir-ground.jpg') tex = loader.loadTexture('models/textures/rock12.bmp') card.setTexture(tex) # Then we build a collisionNode which has a plane solid which will be the ground's collision # representation groundColNode = card.attachNewNode(CollisionNode('ground-cnode')) groundColPlane = CollisionPlane(Plane(Vec3(0, -1, 0), Point3(0, 0, 0))) groundColNode.node().addSolid(groundColPlane) # Now, set the ground to the ground mask groundColNode.setCollideMask(BitMask32().bit(self.ground_bit)) # Why aren't we adding a collider? There is no need to tell the collision traverser about this # collisionNode, as it will automatically be an Into object during traversal. # enable forces self.base.enableParticles() node = NodePath("PhysicsNode") node.reparentTo(self.base.render) # may want to have force dependent on mass eventually, # but at the moment assume all balls same weight self.force_mag = 200 # gravity gravity_fn = ForceNode('world-forces') gravity_fnp = self.base.render.attachNewNode(gravity_fn) gravity_force = LinearVectorForce(0.0, 0.0, -9.81) gravity_fn.addForce(gravity_force) self.base.physicsMgr.addLinearForce(gravity_force) # wind wind_fn = ForceNode('world-forces') wind_fnp = self.base.render.attachNewNode(wind_fn) wind_force = LinearVectorForce(1.0, 0.5, 0.0) wind_fn.addForce(wind_force) self.base.physicsMgr.addLinearForce(wind_force) # spurt out of fountain, bounce self.spurt = ForceNode("spurt") spurt_np = self.base.render.attachNewNode(self.spurt) # create a list for our ball actors, not sure if I need this, but seems likely self.ball_actors = [] # make a teapot teapot = loader.loadModel('teapot.egg') tex = loader.loadTexture('maps/color-grid.rgb') #teapot.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) teapot.setTexture(tex) teapot.reparentTo(self.base.render) teapot.setPos(-5, 10, 10) # create the first ball: #ball = self.create_a_ball() #self.enliven_ball(ball) smiley = loader.loadModel('smiley.egg') lerper = NodePath('lerper') smiley.setTexProjector(TextureStage.getDefault(), NodePath(), lerper) smiley.reparentTo(self.base.render) smiley.setPos(5, 10, 10) i = lerper.posInterval(5, VBase3(0, 1, 0)) i.loop() # Tell the messenger system we're listening for smiley-into-ground messages and invoke our callback self.base.accept('ball_cnode-into-ground-cnode', self.ground_callback) ball_fountain = taskMgr.doMethodLater(.5, self.spurt_balls, 'tickTask')
def __init__(self): ShowBase.__init__(self) self.xray_mode = False self.show_model_bounds = False # Display instructions add_title("Panda3D Tutorial: Occluder Culling") add_instructions(0.06, "[Esc]: Quit") add_instructions(0.12, "[W]: Move Forward") add_instructions(0.18, "[A]: Move Left") add_instructions(0.24, "[S]: Move Right") add_instructions(0.30, "[D]: Move Back") add_instructions(0.36, "Arrow Keys: Look Around") add_instructions(0.42, "[F]: Toggle Wireframe") add_instructions(0.48, "[X]: Toggle X-Ray Mode") add_instructions(0.54, "[B]: Toggle Bounding Volumes") # Setup controls self.keys = {} for key in ["arrow_left", "arrow_right", "arrow_up", "arrow_down", "a", "d", "w", "s"]: self.keys[key] = 0 self.accept(key, self.push_key, [key, 1]) self.accept("shift-%s" % key, self.push_key, [key, 1]) self.accept("%s-up" % key, self.push_key, [key, 0]) self.accept("f", self.toggleWireframe) self.accept("x", self.toggle_xray_mode) self.accept("b", self.toggle_model_bounds) self.accept("escape", __import__("sys").exit, [0]) self.disableMouse() # Setup camera self.lens = PerspectiveLens() self.lens.setFov(60) self.lens.setNear(0.01) self.lens.setFar(1000.0) self.cam.node().setLens(self.lens) self.camera.setPos(-9, -0.5, 1) self.heading = -95.0 self.pitch = 0.0 # Load level geometry self.level_model = self.loader.loadModel("models/level") self.level_model.reparentTo(self.render) self.level_model.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) self.level_model.setTexProjector(TextureStage.getDefault(), self.render, self.level_model) self.level_model.setTexScale(TextureStage.getDefault(), 4) tex = self.loader.load3DTexture("models/tex_#.png") self.level_model.setTexture(tex) # Load occluders occluder_model = self.loader.loadModel("models/occluders") occluder_nodepaths = occluder_model.findAllMatches("**/+OccluderNode") for occluder_nodepath in occluder_nodepaths: self.render.setOccluder(occluder_nodepath) occluder_nodepath.node().setDoubleSided(True) # Randomly spawn some models to test the occluders self.models = [] box_model = self.loader.loadModel("box") for dummy in range(0, 500): pos = LPoint3((random.random() - 0.5) * 9, (random.random() - 0.5) * 9, random.random() * 8) box = box_model.copy_to(self.render) box.setScale(random.random() * 0.2 + 0.1) box.setPos(pos) box.setHpr(random.random() * 360, random.random() * 360, random.random() * 360) box.reparentTo(self.render) self.models.append(box) self.taskMgr.add(self.update, "main loop")
def __init__(self, image_path, name=None,\ rows=1, cols=1, scale=1.0,\ twoSided=True, alpha=TRANS_ALPHA,\ repeatX=1, repeatY=1,\ anchorX=ALIGN_LEFT, 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. """ 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() self.frames = [] for rowIdx in range(self.rows): for colIdx in range(self.cols): self.frames.append(Sprite2d.Cell(colIdx, rowIdx)) # 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 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.card = self.node.attachNewNode(card.generate()) # 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)
def __init__(self, name, bodyDB, isAtmo=False): '''We pass the name to the BaseObject, bodyDB will have vital info for us!''' NodePath.__init__(self, name) # Becuase the C++ Nodepath functins will not return any of these additions, we need a way to call our python extensions when using the C++ functions # Panda provides such a mechanism using the set/getPythonTag function. NodePath.setPythonTag(self, 'subclass', self) self.reparentTo(render) self.setPos(0, 0, 0) self.cubemap = False # Set up grpahic components self.mesh = loader.loadModel("planet_sphere") self.mesh.setShaderAuto() self.atmo = None if '#' in bodyDB['texture']: self.cubemap = True if self.cubemap: self.mesh.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) self.mesh.setTexProjector(TextureStage.getDefault(), render, self.mesh) self.mesh.setTexScale(TextureStage.getDefault(), 1, 1, -1) self.mesh.setTexHpr(TextureStage.getDefault(), 90, -18, 90) texture = loader.loadCubeMap(bodyDB['texture']) else: texture = loader.loadTexture(bodyDB['texture']) texture.setMinfilter(Texture.FTLinearMipmapLinear) self.mesh.setTexture(texture, 1) if "spec" in bodyDB: sts = TextureStage('spec texture stage') sts.setMode(TextureStage.MGloss) stexture = loader.loadTexture(bodyDB['spec']) self.mesh.setTexture(sts, stexture) if "glow" in bodyDB: gts = TextureStage('glow texture stage') gts.setMode(TextureStage.MGlow) gtexture = loader.loadTexture(bodyDB['glow']) self.mesh.setTexture(gts, gtexture) self.mesh.reparentTo(render) #Atmo! if isAtmo: #self.atmo = loader.loadModel("planet_sphere") self.atmo = loader.loadModel("solar_sky_sphere") self.atmo.reparentTo(render) self.atmo.setScale(1.025) outerRadius = self.atmo.getScale().getX() scale = 1/(outerRadius - self.mesh.getScale().getX()) self.atmo.setShaderInput("fOuterRadius", outerRadius) self.atmo.setShaderInput("fInnerRadius", self.mesh.getScale().getX()) self.atmo.setShaderInput("fOuterRadius2", outerRadius * outerRadius) self.atmo.setShaderInput("fInnerRadius2", self.mesh.getScale().getX() * self.mesh.getScale().getX()) self.atmo.setShaderInput("fKr4PI", 0.000055 * 4 * 3.14159) self.atmo.setShaderInput("fKm4PI", 0.000015 * 4 * 3.14159) self.atmo.setShaderInput("fScale", scale) self.atmo.setShaderInput("fScaleDepth", 0.5) self.atmo.setShaderInput("fScaleOverScaleDepth", scale/0.5) # Currently hardcoded in shader self.atmo.setShaderInput("fSamples", 10.0) self.atmo.setShaderInput("nSamples", 10) # These do sunsets and sky colors # Brightness of sun ESun = 15 # Reyleight Scattering (Main sky colors) self.atmo.setShaderInput("fKrESun", 0.000055 * ESun) # Mie Scattering -- Haze and sun halos self.atmo.setShaderInput("fKmESun", 0.000015 * ESun) # Color of sun self.atmo.setShaderInput("v3InvWavelength", 1.0 / math.pow(0.650, 4), 1.0 / math.pow(0.570, 4), 1.0 / math.pow(0.465, 4)) self.atmo.setShaderInput("v3CameraPos", base.camera.getPos().getX(), base.camera.getPos().getY(), base.camera.getPos().getZ()) # Light vector from center of planet. #lightv = light.getPos() lightv = base.bodies[0].mesh.getPos() lightdir = lightv / lightv.length() self.atmo.setShaderInput("v3LightPos", lightdir[0], lightdir[1], lightdir[2]) self.atmo.setShaderInput("fCameraHeight", base.camera.getPos().length()) self.atmo.setShaderInput("fCameraHeight2", base.camera.getPos().length()*base.camera.getPos().length()) self.atmo.setShaderInput("g", 0.90) self.atmo.setShaderInput("g2", 0.81) self.atmo.setShaderInput("float", 2) # All black #atmoShader = Shader.load(Shader.SLGLSL, "atmovertexshader.glsl", "atmofragmentshader.glsl") # None visible #atmoShader = Shader.load(Shader.SLGLSL, "SkyFromSpace.vert", "SkyFromSpace.frag") atmoShader = Shader.load("atmo.cg") self.atmo.setShader(atmoShader) # Initiate visual self.updateVisual(Task) taskMgr.add(self.updateVisual, 'planetRendering') self.setupRotation()