def loadAndBuildLevel(self, safezoneId): levelNode = NodePath('level') frameModel = CogdoUtil.loadFlyingModel('level') startPlatformModel = CogdoUtil.loadFlyingModel('levelStart') endPlatformModel = CogdoUtil.loadFlyingModel('levelEnd') for fan in frameModel.findAllMatches('**/*wallFan'): fan.flattenStrong() frameModel.find('**/fogOpaque').setBin('background', 1) frameModel.find('**/ceiling').setBin('background', 2) frameModel.find('**/fogTranslucent_bm').setBin('fixed', 1) frameModel.find('**/wallR').setBin('opaque', 2) frameModel.find('**/wallL').setBin('opaque', 2) frameModel.find('**/fogTranslucent_top').setBin('fixed', 2) frameModel.getChildren().reparentTo(levelNode) levelNode.hide() self._level = CogdoFlyingLevel(self.parent_, levelNode, startPlatformModel, endPlatformModel, self.quadLengthUnits, self.quadVisibiltyAhead, self.quadVisibiltyBehind) if Globals.Dev.WantTempLevel: quads = Globals.Dev.DevQuadsOrder else: levelInfo = Globals.Level.DifficultyOrder[safezoneId] quads = [] for difficulty in levelInfo: quadList = Globals.Level.QuadsByDifficulty[difficulty] quads.append(quadList[self._rng.randint(0, len(quadList) - 1)]) for i in quads: filePath = CogdoUtil.getModelPath('quadrant%i' % i, 'flying') quadModel = loader.loadModel(filePath) for np in quadModel.findAllMatches('**/*lightCone*'): CogdoUtil.initializeLightCone(np, 'fixed', 3) self._level.appendQuadrant(quadModel) self._level.ready()
def appendWord(self,word,tm = None, fadein = 0, fadeinType = 0): if word == '\n': self.startLine() return textMaker = tm or self.textMaker if not self.lines: self.startLine() active_line = self.lines[-1] unicodeText = isinstance(word, types.UnicodeType) if unicodeText: textMaker.setWtext(word) else: textMaker.setText(word) width = textMaker.getWidth() height = textMaker.getHeight() node = textMaker.generate() textpath = NodePath('text_path') textpath.attachNewNode(node) if self.wordwrap: if active_line.getTotalWidth() + width > self.wordwrap: self.startLine() active_line = self.lines[-1] active_line.append(textpath, width, height,self.spacing, fadein = fadein, fadeinType = fadeinType) active_line.setPos(0,0,-(self.currentHeight + active_line.getLineHeight()) )
def __init__(self, moveTrack, tOffset, posScale = 1.0): NodePath.__init__(self) self.assign(hidden.attachNewNode(base.localAvatar.uniqueName('ring'))) self.setMoveTrack(moveTrack) self.setTOffset(tOffset) self.setPosScale(posScale) self.setT(0.0)
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)
class AssetBase(DirectObject): """Classes for assets are considered proxies - mostly for models in the scene graph. """ def __init__(self): """The constructor should only expect ultimately required parameters. """ # Path to the root node. self.node = NodePath("Asset Base") # Name of the particular asset. self.name = "(No name given)" # Path to the actually visible node (NodePath). Must be either the # same as self.node or a child of it. self.model = self.node def destroy(self): """Cleans up everyting this asset created and attached to the SG. Override to add more sophisticated cleanup functionality.""" self.node.removeNode() self.removeAllTasks() def __str__(self): return self.name def __repr__(self): return self.name
def __init__(self, x, y, z, direction, id): NodePath.__init__(self,loader.loadModel("../Models/missile")) self.reparentTo(render) self.setPos(x, y, z) self.direction = Vec3() self.direction.set(direction.getX(), direction.getY(), direction.getZ()) self.setH(Vec2.signedAngleDeg(Vec2(0,1), Vec2(direction.getX(),direction.getY()))) if self.direction.length() == 0: self.removeNode() return self.direction /= direction.length() min, max = self.getTightBounds() size = max - min maximum = -1 for i in size: if i > maximum: maximum = i self.cnode = CollisionNode('bullet') self.cnode.setTag( "id", str(id) ) self.cnode.addSolid(CollisionSphere(0, 0, 0, maximum + 0.3)) self.cnodePath = self.attachNewNode(self.cnode) self.cnodePath.show() base.cTrav.addCollider(self.cnodePath, base.event) taskMgr.add(self.updateBullet, "update Bullet") print radiansToDegrees(atan2(direction.getY(),direction.getX()))
def __init__(self): NodePath.__init__(self, 'ExperimentTelevision') FSM.__init__(self, 'ExperimentTelevision') self.model = loader.loadModel('phase_4/models/events/blimp_tv.bam') self.model.reparentTo(self) self.staticTex = loader.loadTexture('phase_4/maps/blimp_tv_map_01.png') self.staticTex.setMinfilter(Texture.FTLinearMipmapLinear) self.staticTex.setMagfilter(Texture.FTLinear) self.chairmanTex = loader.loadTexture('phase_4/maps/blimp_tv_map_CM.png') self.chairmanTex.setMinfilter(Texture.FTLinearMipmapLinear) self.chairmanTex.setMagfilter(Texture.FTLinear) self.bossbotScene = BossbotScene() self.lawbotScene = LawbotScene() self.cashbotScene = CashbotScene() self.sellbotScene = SellbotScene() self.buffer = base.win.makeTextureBuffer('television', 960, 540) self.buffer.setSort(-1) self.camera = base.makeCamera(self.buffer) self.track = None
class HandGUI(object, DirectObject): def __init__(self, hand): self.hand = hand self.nodepath = NodePath('handgui') self.nodepath.reparentTo(render) self.nodepath.setPos(0, 20, 0) # self.nodepath.setP(90) self.accept("update_handgui", self.update) def draw(self): # stuffandeer stuffandeer otus for card in self.hand: textn = TextNode(card.name) textn.setText(card.name) textnp = card.model.attachNewNode(textn) textnp.setScale(0.3) textnp.setPos(card.model, -2, 0, 1) textnp.setHpr(card.model, 0, -90, -90) textn.setAlign(TextNode.ACenter) def update(self): x = 0 for card in self.hand: card.model.reparentTo(self.nodepath) card.model.setPos(self.nodepath, x, 0, 0) card.model.setScale(3) x += 5 self.draw() def mouse_over(self, card): pass
def __initToBox__(self,name, size,mass = 0,add_visual = True): NodePath.__init__(self,BulletRigidBodyNode(name)) self.physics_world_ = None # size self.size_ = size # set collision shape collision_shape = BulletBoxShape(self.size_/2) collision_shape.setMargin(GameObject.DEFAULT_COLLISION_MARGIN) self.node().addShape(collision_shape) self.node().setMass(mass) self.setCollideMask(CollisionMasks.GAME_OBJECT_RIGID_BODY) # setting bounding volume min_point = LPoint3(-0.5*size.getX(),-0.5*size.getY(),-0.5*size.getZ()) max_point = LPoint3(0.5*size.getX(),0.5*size.getY(),0.5*size.getZ()) self.node().setBoundsType(BoundingVolume.BT_box) self.node().setBounds(BoundingBox(min_point ,max_point )) # Frame of reference self.reference_np_ = None # visual properties if add_visual: visual_np = GameObject.createSimpleBoxVisualNode(self,self.size_, self.getName() + '-visual') # setting ID GameObject.setObjectID(self, self.getName())
def __init__(self,*args): """ Creates an empty game object GameObject(string name) GameObject(BulletBodyNode bn) Inherits from panda3d.core.NodePath """ name = '' bn = None if len(args) > 0: if isinstance(args[0],str): name = args[0] NodePath.__init__(self,PandaNode(name)) elif isinstance(args[0], BulletBodyNode): bn = args[0] NodePath.__init__(self,bn) else: raise ValueError('Invalid argument for GameObject') # instantiating to a bullet rigid body self.physics_world_ = None self.size_ = self.__estimateSize__() GameObject.setObjectID(self, self.getName())
def _prepare_early_z(self, early_z=False): """ Prepares the earlyz stage """ if early_z: self._prepass_cam = Camera(Globals.base.camNode) self._prepass_cam.set_tag_state_key("EarlyZShader") self._prepass_cam.set_name("EarlyZCamera") self._prepass_cam_node = Globals.base.camera.attach_new_node( self._prepass_cam) Globals.render.set_tag("EarlyZShader", "Default") else: self._prepass_cam = None # modify default camera initial state initial = Globals.base.camNode.get_initial_state() initial_node = NodePath("IntialState") initial_node.set_state(initial) if early_z: initial_node.set_attrib( DepthWriteAttrib.make(DepthWriteAttrib.M_off)) initial_node.set_attrib( DepthTestAttrib.make(DepthTestAttrib.M_equal)) else: initial_node.set_attrib( DepthTestAttrib.make(DepthTestAttrib.M_less_equal)) Globals.base.camNode.set_initial_state(initial_node.get_state())
def make_level(render): cube = NodePath(makeCube(inverse=True, hide=set([5]))) for i in range(0,10): for j in range(0,10): c = render.attachNewNode("c") c.setPos((i-5)*3, (j-5)*3, -10 ) cube.instanceTo(c)
def __init__(self, game, id, x, y): NodePath.__init__(self, 'dropNode%s' % id) self.game = game self.id = id self.reparentTo(hidden) self.setPos(x, y, 0) shadow = loader.loadModel('phase_3/models/props/square_drop_shadow') shadow.setZ(0.2) shadow.setBin('ground', 10) shadow.setColor(1, 1, 1, 1) shadow.reparentTo(self) self.shadow = shadow drop = CogdoUtil.loadMazeModel('cabinetSmFalling') roll = random.randint(-15, 15) drop.setHpr(0, 0, roll) drop.setZ(Globals.DropHeight) self.collTube = CollisionTube(0, 0, 0, 0, 0, 4, Globals.DropCollisionRadius) self.collTube.setTangible(0) name = Globals.DropCollisionName self.collNode = CollisionNode(name) self.collNode.addSolid(self.collTube) self.collNodePath = drop.attachNewNode(self.collNode) self.collNodePath.hide() self.collNodePath.setTag('isFalling', str('True')) drop.reparentTo(self) self.drop = drop self._dropSfx = base.cogdoGameAudioMgr.createSfxIval('drop', volume=0.6)
def __init__(self, camera, id): self.audio3d = Audio3DManager(base.sfxManagerList[0], base.camera) #load the other keyValue texture keyTexRed = base.loader.loadTexture("resources/tex/keyValueRed.png") #Set model and projectile paths self.gunPath1 = NodePath("gun") self.gunPath1.reparentTo(base.camera) self.gunPath1.setPos(1.2 ,10,-3.5) self.gunModel1 = loader.loadModel("./resources/keyValue") self.gunModel1.setTexture(keyTexRed,1) self.gunModel1.reparentTo(self.gunPath1) self.gunModel1.setPos(camera,1.2,4.5,-1.7) self.gunModel1.setHpr(-90,0,0) self.gunPath2 = NodePath("gun") self.gunPath2.reparentTo(base.camera) self.gunPath2.setPos(-1.2,10,-3.5) self.gunModel2 = loader.loadModel("./resources/keyValue") self.gunModel2.reparentTo(self.gunPath2) self.gunModel2.setPos(camera,-1.2,4.5,-1.7) self.gunModel2.setHpr(-90,0,0) self.reticle = OnscreenImage("./resources/kvReticle.png") self.reticle.setTransparency(True) self.reticle.setScale(0) base.taskMgr.add(self.animate, "kvReticle")
def __init__(self,name,parent_np , physics_world, tr = TransformState.makeIdentity()): """ Sector(NodePath parent_np, TransformState tr = TransformState.makeIdentity() Creates a level Sector object which ensures that all objects in it only move in the x and z directions relative to the sector. The z and x vectors lie on the plane with +X pointing to the right and +Z pointing up. +Y is perpedicular to the plane into the screen from the user's perspective @param parent_np: NodePath to the parent of the sector, usually is the Level object that contains the sector. @param physics_world: The physics world @param tf: Transform of the sector relative to the parent_np NodePath """ NodePath.__init__(self,name) self.reparentTo(parent_np) self.setTransform(self,tr) self.physics_world_ = physics_world # creating 2d motion plane self.motion_plane_np_ = self.attachNewNode(BulletRigidBodyNode(self.getName() + '-motion-plane')) self.motion_plane_np_.node().setMass(0) self.motion_plane_np_.node().setIntoCollideMask(CollisionMasks.NO_COLLISION) self.motion_plane_np_.node().addShape(BulletPlaneShape(Vec3(0,1,0),0)) self.physics_world_.attach(self.motion_plane_np_.node()) self.motion_plane_np_.reparentTo(parent_np) self.motion_plane_np_.setTransform(self,TransformState.makeIdentity()) # game objects self.object_constraints_dict_ = {} # stores tuples of the form (String,BulletConstraint) # sector transitions self.sector_transitions_ = [] self.destination_sector_dict_ = {}
def __init__(self): # Basics ShowBase.__init__(self) base.disableMouse() base.setFrameRateMeter(True) self.accept("escape", sys.exit) self.camera.set_pos(-10, -10, 10) self.camera.look_at(0, 0, 0) # A light plight = PointLight('plight') plight.setColor(VBase4(0.5, 0.5, 0.5, 1)) plnp = render.attachNewNode(plight) plnp.setPos(10, 10, 10) render.setLight(plnp) # Create the geometry self.sidelength = 30 self.map_a = self.create_map(self.sidelength) self.map_b = self.map_a geom = self.create_geom(self.sidelength) np = NodePath(geom) np.reparent_to(self.render) # Start the task to interpolate the geometry each frame self.last_time = 0.0 self.need_to_swap_maps = True self.taskMgr.add(self.swap_maps, 'swap_geometry', sort = 5) self.taskMgr.add(self.interpolate_maps, 'interpolate_geometry', sort = 10)
def __build_Model(self, planet, model_type, rec): model_np = NodePath("model_{}".format(rec)) # Basic terrain model. ter_model, pts = self.__get_Sphere_Model(model_type, rec, planet.radius, "terrain") ter_model.NP.reparentTo(model_np) # Map planet topography. if "height_map" in planet.__dict__ and model_type in ("mid", "high"): self.__map_Topography(planet, ter_model, pts) # Map planet colours for low type models only. if model_type == "low" and "colour_map" in planet.__dict__: self.__map_Colours(planet, ter_model, rec, pts) # Atmosphere. if "atmos_ceiling" in planet.__dict__: a_radius = planet.radius + planet.atmos_ceiling am_type = model_type if model_type != "high" else "mid" atmos_model, a_pts = self.__get_Sphere_Model(am_type, min(rec,7), a_radius, "atmos") atmos_model.NP.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise)) atmos_model.NP.setAttrib(TransparencyAttrib.make(TransparencyAttrib.MAlpha)) atmos_model.NP.reparentTo(model_np) model_np.attachNewNode("planet_label") return model_np
def __init__(self, scale=1, value=0, r=10, g=0, b=0): NodePath.__init__(self, 'healthbar') self.value = value self.scale = scale self.range = 1.0 self.buff = 0 cmbg = CardMaker('bg') cmbg.setFrame(- scale, scale, -0.1 * scale, 0.1 * scale) self.bg = self.attachNewNode(cmbg.generate()) self.bg.setColor(0.2, 0.2, 0.2, 1) self.bg.setPos(0,0,5.8) cmfg = CardMaker('fg') cmfg.setFrame(- scale, scale, -0.1 * scale, 0.1 * scale) self.fg = self.bg.attachNewNode(cmfg.generate()) self.fg.setColor(r, g, b, 1) self.fg.setPos(0,-0.1,0) self.fg.setBillboardPointWorld() self.bg.setBillboardPointWorld() self.fg.clearShader() self.bg.clearShader() self.setValue(0)
def __init__(self, parent=None): NodePath.__init__(self, self.__class__.__name__) if not parent: self.reparentTo(aspect2d) # @UndefinedVariable else: self.reparentTo(parent) self._itemlist = []
def _optimize(self): lightCones = NodePath('lightCones') for np in self._platformsRoot.findAllMatches('**/*lightCone*'): np.wrtReparentTo(lightCones) lightCones.reparentTo(self._model) node = self._model.find('**/ducts') if not node.isEmpty(): node.flattenStrong() for np in node.getChildren(): np.wrtReparentTo(self._model) node = self._model.find('**/nests') if not node.isEmpty(): for np in node.getChildren(): np.flattenStrong() np.wrtReparentTo(self._model) for np in self._model.findAllMatches('**/*LayerStack*'): np.wrtReparentTo(self._model) for np in self._model.find('**/static').getChildren(): np.wrtReparentTo(self._model) self._model.flattenMedium()
def _constrain_axis(self, body): """ Apply existing axis constraints to a body.""" # Set displacements. for axis, (f, d) in enumerate(zip(self.axis_constraint_fac, self.axis_constraint_disp)): if not f and not isnan(d): nodep = NodePath(body) pos = nodep.getPos() pos[axis] = d nodep.setPos(pos) try: # Linear and angular factors of 0 mean forces in the # corresponding axis are scaled to 0. body.setLinearFactor(self.axis_constraint_fac) # Angular factors restrict rotation about an axis, so the # following logic selects the appropriate axes to # constrain. s = sum(self.axis_constraint_fac) if s == 3.: v = self.axis_constraint_fac elif s == 2.: v = -self.axis_constraint_fac + 1 else: v = Vec3.zero() body.setAngularFactor(v) except AttributeError: # The body was not a rigid body (it didn't have # setLinearFactor method). pass
def add_ghostnode(node): """ Adds a child ghostnode to a node as a workaround for the ghost-static node collision detection problem.""" name = "%s-ghost" % node.getName() ghost = NodePath(BulletGhostNode(name)) ghost.reparentTo(node) return ghost
def make_fov(sweep=90, steps=16, scale=100): z = 1 + random.uniform(-0.01, 0.01) data = EggData() vp = EggVertexPool('fan') data.addChild(vp) poly = EggPolygon() data.addChild(poly) v = EggVertex() v.setPos(Point3D(0, 0, z)) poly.addVertex(vp.addVertex(v)) rads = deg2Rad(sweep) for i in range(steps + 1): a = rads * i / steps y = math.sin(a) x = math.cos(a) v = EggVertex() v.setPos(Point3D(x*scale, y*scale, z)) poly.addVertex(vp.addVertex(v)) node = loadEggData(data) np = NodePath(node) np.setH(sweep/2) return np
def create_object(self): from panda3d.core import Filename, NodePath, BitMask32 from direct.actor.Actor import Actor from panda3d.bullet import BulletRigidBodyNode, BulletCapsuleShape from game_system.resources import ResourceManager f = Filename.fromOsSpecific(ResourceManager.get_absolute_path(ResourceManager["TestAI"]["lp_char_bs.egg"])) model = Actor(f) bullet_node = BulletRigidBodyNode("TestAIBulletNode") bullet_nodepath = NodePath(bullet_node) bullet_node.set_angular_factor((0, 0, 1)) shape = BulletCapsuleShape(0.3, 1.4, 2) bullet_node.addShape(shape) bullet_node.setMass(1.0) model.reparentTo(bullet_nodepath) model.set_hpr(180, 0, 0) model.set_pos(0, 0, -1) bullet_nodepath.set_collide_mask(BitMask32.bit(0)) bullet_nodepath.set_python_tag("actor", model) return bullet_nodepath
def __build_Star_Sphere(self, bg_stars): from panda3d.core import GeomVertexWriter, GeomVertexFormat, GeomVertexData from panda3d.core import Geom, GeomNode, GeomPoints, AmbientLight self.star_sphere_np.removeNode() # Fill GeomVertexData. vformat = GeomVertexFormat.getV3c4() vdata = GeomVertexData("Data", vformat, Geom.UHStatic) vertices = GeomVertexWriter(vdata, "vertex") colours = GeomVertexWriter(vdata, "color") for coords in bg_stars: x, y, z = coords vertices.addData3f(x, y, z) colours.addData4f(1, 1, 1, 1) # Render bg stars. bg_stars = GeomPoints(Geom.UHStatic) bg_stars.addNextVertices(_env.STAR_COUNT) bg_stars_geom = Geom(vdata) bg_stars_geom.addPrimitive(bg_stars) star_sphere = GeomNode("star_sphere") star_sphere.addGeom(bg_stars_geom) star_sphere_np = NodePath(star_sphere) star_sphere_np.reparentTo(self.NP) return star_sphere_np
class _Camera_: key_map = {} mouse_map = {} # Public. def set_focus(self, obj): if self.FOCUS and obj is self.FOCUS: return self.FOCUS = obj self.focus_pos.set(0, obj.radius*12, 0) obj_state = self.env.client.SIM.get_object_state(obj.name, ["sys_pos"]) obj.sys_pos = LVector3d(*obj_state['sys_pos']) self.sys_pos = obj.sys_pos - self.focus_pos # Setup. def __init__(self, env): self.env = env self.cam_node = Camera(self.__class__.__name__.lower()) self.cam_node.setScene(env.NP) self.NP = NodePath(self.cam_node) self.NP.reparentTo(env.NP) self.LENS = self.cam_node.getLens() self.LENS.setFar(_cam.FAR) self.LENS.setFov(base.camLens.getFov()) self.FOCUS = None self.focus_pos = LVector3d(0,0,0) self.sys_pos = LVector3d(0,0,0)
def shoot(self, rangeVector): if not self.gag: return rangeNode = NodePath('Shoot Range') rangeNode.reparentTo(self.turret.getCannon()) rangeNode.setScale(render, 1) rangeNode.setPos(rangeVector) rangeNode.setHpr(90, -90, 90) self.gag.setScale(self.gag.getScale(render)) self.gag.setScale(self.gag.getScale(render)) self.gag.setPos(self.gag.getPos(render)) self.gag.reparentTo(render) self.gag.setHpr(rangeNode.getHpr(render)) base.audio3d.attachSoundToObject(self.gagClass.woosh, self.gag) self.gagClass.woosh.play() self.track = ProjectileInterval(self.gag, startPos=self.gag.getPos(render), endPos=rangeNode.getPos(render), gravityMult=self.gravityMult, duration=self.duration, name=self.trackName) self.track.setDoneEvent(self.track.getName()) self.acceptOnce(self.track.getDoneEvent(), self.cleanup) self.track.start() fireSfx = base.audio3d.loadSfx('phase_4/audio/sfx/MG_cannon_fire_alt.mp3') base.audio3d.attachSoundToObject(fireSfx, self.turret.getCannon()) fireSfx.play() if self.turret.isLocal(): self.buildCollisions() self.acceptOnce(self.eventName, self.handleCollision)
class Lobby: cmd_map = {'exit':"escape"} # Public. def to_pre_view(self, sys_name=""): if sys_name: self.client.init_system(sys_name) self.client.switch_display(self.client.PRE_VIEW) # Setup. def __init__(self, client): self.client = client self.NP = NodePath("lobby") self.NP.reparentTo(render) self.GUI = Lobby_Win(ctrl=self) self.GUI.render() self.CAMERA = Dummy_Camera(self) def _main_loop_(self, ue, dt): self.GUI._main_loop_(ue, dt) self._handle_user_events_(ue, dt) def _handle_user_events_(self, ue, dt): cmds = ue.get_cmds(self) if "exit" in cmds: print("exit") self.client._alive = False
def makeRenderState(material = None, diffuseTexture=None, normalTexture=None, glowTexture=None): n = NodePath("n") if not material: material = makeMaterial((0,0,0,1), (1,1,1,1), (0.01,0.01,0.01,1), 1, (1,1,1,1)) n.setMaterial(material) if diffuseTexture: tsDiffuse = TextureStage('diffuse') tsDiffuse.setMode(TextureStage.MModulate) n.setTexture(tsDiffuse, diffuseTexture) if glowTexture: tsGlow = TextureStage('glow') tsGlow.setMode(TextureStage.MGlow) n.setTexture(tsGlow, glowTexture) if normalTexture: tsNormal = TextureStage('normal') tsNormal.setMode(TextureStage.MNormal) n.setTexture(tsNormal, normalTexture) # weird bugs :| #n.setTransparency(True) #n.setColorOff() return n.getState()
def __init__(self, N, sourceTex, normalizationFactor): """ Creates a new fft instance. The source texture has to specified from the begining, as the shaderAttributes are pregenerated for performance reasons """ DebugObject.__init__(self, "GPU-FFT") self.size = N self.log2Size = int(math.log(N, 2)) self.normalizationFactor = normalizationFactor # Create a ping and a pong texture, because we can't write to the # same texture while reading to it (that would lead to unexpected # behaviour, we could solve that by using an appropriate thread size, # but it works fine so far) self.pingTexture = Texture("FFTPing") self.pingTexture.setup2dTexture( self.size, self.size, Texture.TFloat, Texture.FRgba32) self.pongTexture = Texture("FFTPong") self.pongTexture.setup2dTexture( self.size, self.size, Texture.TFloat, Texture.FRgba32) self.sourceTex = sourceTex for tex in [self.pingTexture, self.pongTexture, sourceTex]: tex.setMinfilter(Texture.FTNearest) tex.setMagfilter(Texture.FTNearest) tex.setWrapU(Texture.WMClamp) tex.setWrapV(Texture.WMClamp) # Pregenerate weights & indices for the shaders self._computeWeighting() # Pre generate the shaders, we have 2 passes: Horizontal and Vertical # which both execute log2(N) times with varying radii self.horizontalFFTShader = BetterShader.loadCompute( "Shader/Water/HorizontalFFT.compute") self.horizontalFFT = NodePath("HorizontalFFT") self.horizontalFFT.setShader(self.horizontalFFTShader) self.horizontalFFT.setShaderInput( "precomputedWeights", self.weightsLookupTex) self.horizontalFFT.setShaderInput("N", LVecBase2i(self.size)) self.verticalFFTShader = BetterShader.loadCompute( "Shader/Water/VerticalFFT.compute") self.verticalFFT = NodePath("VerticalFFT") self.verticalFFT.setShader(self.verticalFFTShader) self.verticalFFT.setShaderInput( "precomputedWeights", self.weightsLookupTex) self.verticalFFT.setShaderInput("N", LVecBase2i(self.size)) # Create a texture where the result is stored self.resultTexture = Texture("Result") self.resultTexture.setup2dTexture( self.size, self.size, Texture.TFloat, Texture.FRgba16) self.resultTexture.setMinfilter(Texture.FTLinear) self.resultTexture.setMagfilter(Texture.FTLinear) # Prepare the shader attributes, so we don't have to regenerate them # every frame -> That is VERY slow (3ms per fft instance) self._prepareAttributes()
def load(self): self.notify.debug('load') DistributedMinigame.DistributedMinigame.load(self) self.music = base.loader.loadMusic('phase_4/audio/bgm/MG_IceGame.ogg') self.gameBoard = loader.loadModel('phase_4/models/minigames/ice_game_icerink') background = loader.loadModel('phase_4/models/minigames/ice_game_2d') background.reparentTo(self.gameBoard) self.gameBoard.setPosHpr(0, 0, 0, 0, 0, 0) self.gameBoard.setScale(1.0) self.setupSimulation() index = 0 for avId in self.avIdList: self.setupTire(avId, index) self.setupForceArrow(avId) index += 1 for index in xrange(len(self.avIdList), 4): self.setupTire(-index, index) self.setupForceArrow(-index) self.showForceArrows(realPlayersOnly=True) self.westWallModel = NodePath() if not self.westWallModel.isEmpty(): self.westWallModel.reparentTo(self.gameBoard) self.westWallModel.setPos(IceGameGlobals.MinWall[0], IceGameGlobals.MinWall[1], 0) self.westWallModel.setScale(4) self.eastWallModel = NodePath() if not self.eastWallModel.isEmpty(): self.eastWallModel.reparentTo(self.gameBoard) self.eastWallModel.setPos(IceGameGlobals.MaxWall[0], IceGameGlobals.MaxWall[1], 0) self.eastWallModel.setScale(4) self.eastWallModel.setH(180) self.arrowKeys = ArrowKeys.ArrowKeys() self.target = loader.loadModel('phase_3/models/misc/sphere') self.target.setScale(0.01) self.target.reparentTo(self.gameBoard) self.target.setPos(0, 0, 0) self.scoreCircle = loader.loadModel('phase_4/models/minigames/ice_game_score_circle') self.scoreCircle.setScale(0.01) self.scoreCircle.reparentTo(self.gameBoard) self.scoreCircle.setZ(IceGameGlobals.TireRadius / 2.0) self.scoreCircle.setAlphaScale(0.5) self.scoreCircle.setTransparency(1) self.scoreCircle.hide() self.treasureModel = loader.loadModel('phase_4/models/minigames/ice_game_barrel') self.penaltyModel = loader.loadModel('phase_4/models/minigames/ice_game_tnt2') self.penaltyModel.setScale(0.75, 0.75, 0.7) szId = self.getSafezoneId() obstacles = IceGameGlobals.Obstacles[szId] index = 0 cubicObstacle = IceGameGlobals.ObstacleShapes[szId] for pos in obstacles: newPos = Point3(pos[0], pos[1], IceGameGlobals.TireRadius) newObstacle = self.createObstacle(newPos, index, cubicObstacle) self.obstacles.append(newObstacle) index += 1 self.countSound = loader.loadSfx('phase_3.5/audio/sfx/tick_counter.ogg') self.treasureGrabSound = loader.loadSfx('phase_4/audio/sfx/MG_sfx_vine_game_bananas.ogg') self.penaltyGrabSound = loader.loadSfx('phase_4/audio/sfx/MG_cannon_fire_alt.ogg') self.tireSounds = [] for tireIndex in xrange(4): tireHit = loader.loadSfx('phase_4/audio/sfx/Golf_Hit_Barrier_1.ogg') wallHit = loader.loadSfx('phase_4/audio/sfx/MG_maze_pickup.ogg') obstacleHit = loader.loadSfx('phase_4/audio/sfx/Golf_Hit_Barrier_2.ogg') self.tireSounds.append({'tireHit': tireHit, 'wallHit': wallHit, 'obstacleHit': obstacleHit}) self.arrowRotateSound = loader.loadSfx('phase_4/audio/sfx/MG_sfx_ice_force_rotate.ogg') self.arrowUpSound = loader.loadSfx('phase_4/audio/sfx/MG_sfx_ice_force_increase_3sec.ogg') self.arrowDownSound = loader.loadSfx('phase_4/audio/sfx/MG_sfx_ice_force_decrease_3sec.ogg') self.scoreCircleSound = loader.loadSfx('phase_4/audio/sfx/MG_sfx_ice_scoring_1.ogg')
class PartyCogActivityLocalPlayer(PartyCogActivityPlayer): def __init__(self, activity, position, team, exitActivityCallback=None): PartyCogActivityPlayer.__init__(self, activity, base.localAvatar, position, team) self.input = PartyCogActivityInput(exitActivityCallback) self.gui = PartyCogActivityGui() self.throwPiePrevTime = 0 self.lastMoved = 0 if base.localAvatar: self.prevPos = base.localAvatar.getPos() self.cameraManager = None self.control = None self.consecutiveShortThrows = 0 return def destroy(self): if self.enabled: self.disable() if self.cameraManager is not None: self.cameraManager.setEnabled(False) self.cameraManager.destroy() del self.cameraManager del self.gui del self.input if self.control is not None: self.control.destroy() del self.control PartyCogActivityPlayer.destroy(self) return def _initOrthoWalk(self): orthoDrive = OrthoDrive(9.778, customCollisionCallback=self.activity.view. checkOrthoDriveCollision) self.orthoWalk = OrthoWalk(orthoDrive, broadcast=True) def _destroyOrthoWalk(self): self.orthoWalk.stop() self.orthoWalk.destroy() del self.orthoWalk def getPieThrowingPower(self, time): elapsed = max(time - self.input.throwPiePressedStartTime, 0.0) w = 1.0 / PartyGlobals.CogActivityPowerMeterTime * 2.0 * math.pi power = int(round(-math.cos(w * elapsed) * 50.0 + 50.0)) return power def isShortThrow(self, time): elapsed = max(time - self.input.throwPiePressedStartTime, 0.0) return elapsed <= PartyGlobals.CogActivityShortThrowTime def checkForThrowSpam(self, time): if self.isShortThrow(time): self.consecutiveShortThrows += 1 else: self.consecutiveShortThrows = 0 return self.consecutiveShortThrows >= PartyGlobals.CogActivityShortThrowSpam def _startUpdateTask(self): task = Task(self._updateTask) task.lastPositionBroadcastTime = 0.0 self.throwPiePrevTime = 0 taskMgr.add(task, UPDATE_TASK_NAME) def _stopUpdateTask(self): taskMgr.remove(UPDATE_TASK_NAME) def _updateTask(self, task): self._update() if base.localAvatar.getPos() != self.prevPos: self.prevPos = base.localAvatar.getPos() self.lastMoved = self.activity.getCurrentActivityTime() if max(self.activity.getCurrentActivityTime() - self.lastMoved, 0) > PartyGlobals.ToonMoveIdleThreshold: self.gui.showMoveControls() if max(self.activity.getCurrentActivityTime() - self.throwPiePrevTime, 0) > PartyGlobals.ToonAttackIdleThreshold: self.gui.showAttackControls() if self.input.throwPieWasReleased: if self.checkForThrowSpam(globalClock.getFrameTime()): self.gui.showSpamWarning() self.input.throwPieWasReleased = False self.throwPie(self.getPieThrowingPower(globalClock.getFrameTime())) return Task.cont def throwPie(self, piePower): if not self.activity.isState('Active'): return if self.activity.getCurrentActivityTime( ) - self.throwPiePrevTime > THROW_PIE_LIMIT_TIME: self.throwPiePrevTime = self.activity.getCurrentActivityTime() self.activity.b_pieThrow(self.toon, piePower) def _update(self): self.control.update() def getLookat(self, whosLooking, refNode=None): if refNode is None: refNode = render dist = 5.0 oldParent = self.tempNP.getParent() self.tempNP.reparentTo(whosLooking) self.tempNP.setPos(0.0, dist, 0.0) pos = self.tempNP.getPos(refNode) self.tempNP.reparentTo(oldParent) return pos def entersActivity(self): base.cr.playGame.getPlace().setState('activity') PartyCogActivityPlayer.entersActivity(self) self.gui.disableToontownHUD() self.cameraManager = CameraManager(camera) self.tempNP = NodePath('temp') self.lookAtMyTeam() self.control = StrafingControl(self) def exitsActivity(self): PartyCogActivityPlayer.exitsActivity(self) self.gui.enableToontownHUD() self.cameraManager.setEnabled(False) self.tempNP.removeNode() self.tempNP = None if not aspect2d.find('**/JellybeanRewardGui*'): base.cr.playGame.getPlace().setState('walk') else: self.toon.startPosHprBroadcast() return def getRunToStartPositionIval(self): targetH = self.locator.getH() travelVec = self.position - self.toon.getPos(self.activity.root) duration = travelVec.length() / 9.778 startH = 0.0 if travelVec.getY() < 0.0: startH = 180.0 return Sequence( Func(self.toon.startPosHprBroadcast, 0.1), Func(self.toon.b_setAnimState, 'run'), Parallel( self.toon.hprInterval(0.5, VBase3(startH, 0.0, 0.0), other=self.activity.root), self.toon.posInterval(duration, self.position, other=self.activity.root)), Func(self.toon.b_setAnimState, 'neutral'), self.toon.hprInterval(0.25, VBase3(targetH, 0.0, 0.0), other=self.activity.root), Func(self.toon.stopPosHprBroadcast)) def enable(self): if self.enabled: return PartyCogActivityPlayer.enable(self) self.toon.b_setAnimState('Happy') self._initOrthoWalk() self.orthoWalk.start() self.orthoWalking = True self.input.enable() self.gui.disableToontownHUD() self.gui.load() self.gui.setScore(0) self.gui.showScore() self.gui.setTeam(self.team) self.gui.startTrackingCogs(self.activity.view.cogManager.cogs) self.control.enable() self._startUpdateTask() def disable(self): if not self.enabled: return self._stopUpdateTask() self.toon.b_setAnimState('neutral') PartyCogActivityPlayer.disable(self) self.orthoWalking = False self.orthoWalk.stop() self._destroyOrthoWalk() self.input.disable() self._aimMode = False self.cameraManager.setEnabled(False) self.gui.hide() self.gui.stopTrackingCogs() self.gui.unload() def updateScore(self): self.gui.setScore(self.score) def b_updateToonPosition(self): self.updateToonPosition() self.d_updateToonPosition() def d_updateToonPosition(self): self.toon.d_setPos(self.toon.getX(), self.toon.getY(), self.toon.getZ()) self.toon.d_setH(self.toon.getH()) def lookAtArena(self): self.cameraManager.setEnabled(True) self.cameraManager.setTargetPos( self.activity.view.arena.find( '**/conclusionCamPos_locator').getPos(render)) self.cameraManager.setTargetLookAtPos( self.activity.view.arena.find( '**/conclusionCamAim_locator').getPos(render)) def lookAtMyTeam(self): activityView = self.activity.view arena = activityView.arena pos = activityView.teamCamPosLocators[self.team].getPos() aim = activityView.teamCamAimLocators[self.team].getPos() camera.wrtReparentTo(arena) self.cameraManager.setPos(camera.getPos(render)) self.tempNP.reparentTo(arena) self.tempNP.setPos(arena, pos) self.cameraManager.setTargetPos(self.tempNP.getPos(render)) self.cameraManager.setLookAtPos(self.getLookat(camera)) self.tempNP.reparentTo(arena) self.tempNP.setPos(arena, aim) self.cameraManager.setTargetLookAtPos(self.tempNP.getPos(render)) self.cameraManager.setEnabled(True) camera.setP(0.0) camera.setR(0.0)
class BaseEntity(BulletRigidBodyNode): """ """ # Default entity model (overwritten by subclasses) MODEL = "models/teapot" # Field of view; how many degrees to the side the entity can see FOV = 180 VIEW_DISTANCE = 1 def __init__(self): self.ID = id(self) self.NAME = f"{type(self).__name__}_{self.ID}" super().__init__(self.NAME) # List of tasks to register to the Panda task manager self.tasks = (self.act, ) self.nodePath = NodePath(self) self.nodePath.setTag('clickable', '1') self.actor = Actor(self.MODEL) self.actor.reparent_to(self.nodePath) self.setMass(1.0) # Set up actor position, hitbox, and other size-dependent properties self.setScale(1) self.nodePath.setPos(random.uniform(100, 400), random.uniform(0, 100), random.uniform(0, 150)) def onCollision(self, event): # print(event) pass def act(self, task): """Main logic loop for the entity, overridden in subclasses""" return task.cont def setScale(self, scale=1): """Resizes the entity and its hitbox to the desired scale """ self.actor.setScale(scale) # Calculate model's size pt1, pt2 = self.actor.getTightBounds() self.width = pt2.getX() - pt1.getX() self.depth = pt2.getY() - pt1.getY() self.height = pt2.getZ() - pt1.getZ() # Reassign all size-dependent fields self.actor.setZ(-self.height / 2) if self.getNumShapes() > 0: self.removeShape(self.getShape(0)) self.addShape( BulletBoxShape((self.width / 2, self.depth / 2, self.height / 2))) self.generateViewRays() def generateViewRays(self, numPoints=100): """https://youtu.be/bqtqltqcQhw?t=333 """ FIBONACCI = (1 + 5**0.5) / 2 # Calculate length of collision lines based on # entity's size and view distance size = self.VIEW_DISTANCE * 1000 * self.actor.getScale()[0] ls = LineSegs() ls.setThickness(1) pointsColor = 0 # Attach collision node that will hold all collision lines self.sightRayNP = self.nodePath.attachNewNode( CollisionNode(f"{self.NAME}_collisionRays")) self.sightRayNP.node().set_into_collide_mask(0) self.sightRayNP.setPos(self.sightRayNP, 0, -self.depth / 2, self.height / 2) self.sightRayNP.setHpr(0, 90, 0) for i in range(numPoints): inclination = math.acos(1 - 2 * (i / (numPoints - 1))) azimuth = 2 * math.pi * FIBONACCI * i if (inclination / math.pi) > (self.FOV / 360): break x = math.sin(inclination) * math.cos(azimuth) * size y = math.sin(inclination) * math.sin(azimuth) * size z = math.cos(inclination) * size self.drawPoint(ls, x, y, z, (pointsColor, 0, 0, 1)) pointsColor += 1 / numPoints pointsNP = self.nodePath.attachNewNode(ls.create()) pointsNP.setPos(pointsNP, 0, -self.depth / 2, self.height / 2) pointsNP.setHpr(0, 90, 0) def drawPoint(self, ls, x, y, z, color): """Draws a point at the specified coordinates relative to the entity, using the given LineSegs object, useful for debugging """ ls.setColor(color) ls.moveTo(x, y, z) ls.drawTo(x + 1, y, z) ls.drawTo(x - 1, y, z) ls.moveTo(x, y, z) ls.drawTo(x, y + 1, z) ls.drawTo(x, y - 1, z) ls.moveTo(x, y, z) ls.drawTo(x, y, z + 1) ls.drawTo(x, y, z - 1)
def createTire(self, tireIndex): if tireIndex < 0 or tireIndex >= len(self.tireMasks): self.notify.error('invalid tireIndex %s' % tireIndex) self.notify.debug('create tireindex %s' % tireIndex) zOffset = 0 body = OdeBody(self.world) mass = OdeMass() mass.setSphere(self.tireDensity, IceGameGlobals.TireRadius) body.setMass(mass) body.setPosition(IceGameGlobals.StartingPositions[tireIndex][0], IceGameGlobals.StartingPositions[tireIndex][1], IceGameGlobals.StartingPositions[tireIndex][2]) body.setAutoDisableDefaults() geom = OdeSphereGeom(self.space, IceGameGlobals.TireRadius) self.space.setSurfaceType(geom, self.tireSurfaceType) self.space.setCollideId(geom, self.tireCollideIds[tireIndex]) self.massList.append(mass) self.geomList.append(geom) geom.setCollideBits(self.allTiresMask | self.wallMask | self.floorMask | self.obstacleMask) geom.setCategoryBits(self.tireMasks[tireIndex]) geom.setBody(body) if self.notify.getDebug(): self.notify.debug('tire geom id') geom.write() self.notify.debug(' -') if self.canRender: testTire = render.attachNewNode('tire holder %d' % tireIndex) smileyModel = NodePath() if not smileyModel.isEmpty(): smileyModel.setScale(IceGameGlobals.TireRadius) smileyModel.reparentTo(testTire) smileyModel.setAlphaScale(0.5) smileyModel.setTransparency(1) testTire.setPos(IceGameGlobals.StartingPositions[tireIndex]) tireModel = loader.loadModel( 'phase_4/models/minigames/ice_game_tire') tireHeight = 1 tireModel.setZ(-IceGameGlobals.TireRadius + 0.01) tireModel.reparentTo(testTire) self.odePandaRelationList.append((testTire, body)) else: testTire = None self.bodyList.append((None, body)) return (testTire, body, geom)
def gen_dashframe(pos=np.array([0, 0, 0]), rotmat=np.eye(3), length=.1, thickness=.005, lsolid=None, lspace=None, rgbmatrix=None, alpha=None, plotname="dashframe"): """ gen an axis for attaching :param pos: :param rotmat: :param length: :param thickness: :param lsolid: length of the solid section, 1*thickness by default :param lspace: length of the empty section, 1.5*thickness by default :param rgbmatrix: each column indicates the color of each base :param plotname: :return: author: weiwei date: 20200630osaka """ endx = pos + rotmat[:, 0] * length endy = pos + rotmat[:, 1] * length endz = pos + rotmat[:, 2] * length if rgbmatrix is None: rgbx = np.array([1, 0, 0]) rgby = np.array([0, 1, 0]) rgbz = np.array([0, 0, 1]) else: rgbx = rgbmatrix[:, 0] rgby = rgbmatrix[:, 1] rgbz = rgbmatrix[:, 2] if alpha is None: alphax = alphay = alphaz = 1 elif isinstance(alpha, np.ndarray): alphax = alpha[0] alphay = alpha[1] alphaz = alpha[2] else: alphax = alphay = alphaz = alpha # TODO 20201202 change it to StaticGeometricModelCollection frame_nodepath = NodePath(plotname) arrowx_trm = trihelper.gen_dasharrow(spos=pos, epos=endx, thickness=thickness, lsolid=lsolid, lspace=lspace) arrowx_nodepath = da.trimesh_to_nodepath(arrowx_trm) arrowx_nodepath.setTransparency(TransparencyAttrib.MDual) arrowx_nodepath.setColor(rgbx[0], rgbx[1], rgbx[2], alphax) arrowy_trm = trihelper.gen_dasharrow(spos=pos, epos=endy, thickness=thickness, lsolid=lsolid, lspace=lspace) arrowy_nodepath = da.trimesh_to_nodepath(arrowy_trm) arrowy_nodepath.setTransparency(TransparencyAttrib.MDual) arrowy_nodepath.setColor(rgby[0], rgby[1], rgby[2], alphay) arrowz_trm = trihelper.gen_dasharrow(spos=pos, epos=endz, thickness=thickness, lsolid=lsolid, lspace=lspace) arrowz_nodepath = da.trimesh_to_nodepath(arrowz_trm) arrowz_nodepath.setTransparency(TransparencyAttrib.MDual) arrowz_nodepath.setColor(rgbz[0], rgbz[1], rgbz[2], alphaz) arrowx_nodepath.reparentTo(frame_nodepath) arrowy_nodepath.reparentTo(frame_nodepath) arrowz_nodepath.reparentTo(frame_nodepath) frame_sgm = StaticGeometricModel(frame_nodepath) return frame_sgm
class WaterManager: """ Simple wrapper around WaterDisplacement which combines 3 displacement maps into one, and also generates a normal map """ def __init__(self, water_options): self.options = water_options self.options.size = 512 self.options.wind_dir.normalize() self.options.wave_amplitude *= 1e-7 self.displacement_tex = Texture("Displacement") self.displacement_tex.setup_2d_texture( self.options.size, self.options.size, Texture.TFloat, Texture.FRgba16) self.normal_tex = Texture("Normal") self.normal_tex.setup_2d_texture( self.options.size, self.options.size, Texture.TFloat, Texture.FRgba16) self.combine_shader = Shader.load_compute(Shader.SLGLSL, "/$$rp/rpcore/water/shader/combine.compute") self.pta_time = PTAFloat.emptyArray(1) # Create a gaussian random texture, as shaders aren't well suited # for that setRandomSeed(523) self.random_storage = PNMImage(self.options.size, self.options.size, 4) self.random_storage.setMaxval((2 ** 16) - 1) for x in range(self.options.size): for y in range(self.options.size): rand1 = self._get_gaussian_random() / 10.0 + 0.5 rand2 = self._get_gaussian_random() / 10.0 + 0.5 self.random_storage.setXel(x, y, float(rand1), float(rand2), 0) self.random_storage.setAlpha(x, y, 1.0) self.random_storage_tex = Texture("RandomStorage") self.random_storage_tex.load(self.random_storage) self.random_storage_tex.set_format(Texture.FRgba16) self.random_storage_tex.set_minfilter(Texture.FTNearest) self.random_storage_tex.set_magfilter(Texture.FTNearest) # Create the texture wwhere the intial height (H0 + Omega0) is stored. self.tex_initial_height = Texture("InitialHeight") self.tex_initial_height.setup_2d_texture( self.options.size, self.options.size, Texture.TFloat, Texture.FRgba16) self.tex_initial_height.set_minfilter(Texture.FTNearest) self.tex_initial_height.set_magfilter(Texture.FTNearest) # Create the shader which populates the initial height texture self.shader_initial_height = Shader.load_compute(Shader.SLGLSL, "/$$rp/rpcore/water/shader/initial_height.compute") self.node_initial_height = NodePath("initialHeight") self.node_initial_height.set_shader(self.shader_initial_height) self.node_initial_height.set_shader_input("dest", self.tex_initial_height) self.node_initial_height.set_shader_input( "N", LVecBase2i(self.options.size)) self.node_initial_height.set_shader_input( "patchLength", self.options.patch_length) self.node_initial_height.set_shader_input("windDir", self.options.wind_dir) self.node_initial_height.set_shader_input( "windSpeed", self.options.wind_speed) self.node_initial_height.set_shader_input( "waveAmplitude", self.options.wave_amplitude) self.node_initial_height.set_shader_input( "windDependency", self.options.wind_dependency) self.node_initial_height.set_shader_input( "randomTex", self.random_storage_tex) self.attr_initial_height = self.node_initial_height.get_attrib(ShaderAttrib) self.height_textures = [] for i in range(3): tex = Texture("Height") tex.setup_2d_texture(self.options.size, self.options.size, Texture.TFloat, Texture.FRgba16) tex.set_minfilter(Texture.FTNearest) tex.set_magfilter(Texture.FTNearest) tex.set_wrap_u(Texture.WMClamp) tex.set_wrap_v(Texture.WMClamp) self.height_textures.append(tex) # Also create the shader which updates the spectrum self.shader_update = Shader.load_compute(Shader.SLGLSL, "/$$rp/rpcore/water/shader/update.compute") self.node_update = NodePath("update") self.node_update.set_shader(self.shader_update) self.node_update.set_shader_input("outH0x", self.height_textures[0]) self.node_update.set_shader_input("outH0y", self.height_textures[1]) self.node_update.set_shader_input("outH0z", self.height_textures[2]) self.node_update.set_shader_input("initialHeight", self.tex_initial_height) self.node_update.set_shader_input("N", LVecBase2i(self.options.size)) self.node_update.set_shader_input("time", self.pta_time) self.attr_update = self.node_update.get_attrib(ShaderAttrib) # Create 3 FFTs self.fftX = GPUFFT(self.options.size, self.height_textures[0], self.options.normalization_factor) self.fftY = GPUFFT(self.options.size, self.height_textures[1], self.options.normalization_factor) self.fftZ = GPUFFT(self.options.size, self.height_textures[2], self.options.normalization_factor) self.combine_node = NodePath("Combine") self.combine_node.set_shader(self.combine_shader) self.combine_node.set_shader_input( "displacementX", self.fftX.get_result_texture()) self.combine_node.set_shader_input( "displacementY", self.fftY.get_result_texture()) self.combine_node.set_shader_input( "displacementZ", self.fftZ.get_result_texture()) self.combine_node.set_shader_input("normalDest", self.normal_tex) self.combine_node.set_shader_input( "displacementDest", self.displacement_tex) self.combine_node.set_shader_input( "N", LVecBase2i(self.options.size)) self.combine_node.set_shader_input( "choppyScale", self.options.choppy_scale) self.combine_node.set_shader_input( "gridLength", self.options.patch_length) # Store only the shader attrib as this is way faster self.attr_combine = self.combine_node.get_attrib(ShaderAttrib) def _get_gaussian_random(self): """ Returns a gaussian random number """ u1 = generateRandom() u2 = generateRandom() if u1 < 1e-6: u1 = 1e-6 return sqrt(-2 * log(u1)) * cos(2 * pi * u2) def setup(self): """ Setups the manager """ Globals.base.graphicsEngine.dispatch_compute( (self.options.size // 16, self.options.size // 16, 1), self.attr_initial_height, Globals.base.win.get_gsg()) def get_displacement_texture(self): """ Returns the displacement texture, storing the 3D Displacement in the RGB channels """ return self.displacement_tex def get_normal_texture(self): """ Returns the normal texture, storing the normal in world space in the RGB channels """ return self.normal_tex def update(self): """ Updates the displacement / normal map """ self.pta_time[0] = 1 + Globals.clock.get_frame_time() * self.options.time_scale Globals.base.graphicsEngine.dispatch_compute( (self.options.size // 16, self.options.size // 16, 1), self.attr_update, Globals.base.win.get_gsg()) self.fftX.execute() self.fftY.execute() self.fftZ.execute() # Execute the shader which combines the 3 displacement maps into # 1 displacement texture and 1 normal texture. We could use dFdx in # the fragment shader, however that gives no accurate results as # dFdx returns the same value for a 2x2 pixel block Globals.base.graphicsEngine.dispatch_compute( (self.options.size // 16, self.options.size // 16, 1), self.attr_combine, Globals.base.win.get_gsg())
def renderQuadInto(self, name="filter-stage", mul=1, div=1, align=1, depthtex=None, colortex=None, auxtex0=None, auxtex1=None, size=None, addToList=True, fullscreen=True): """ Creates an offscreen buffer for an intermediate computation. Installs a quad into the buffer. Returns the fullscreen quad. The size of the buffer is initially equal to the size of the main window. The parameters 'mul', 'div', and 'align' can be used to adjust that size. """ texgroup = (depthtex, colortex, auxtex0, auxtex1) if not size: winx, winy = self.getScaledSize(mul, div, align) else: winx, winy = size depthbits = bool(depthtex != None) buffer = self.createBuffer(name, winx, winy, texgroup, depthbits) if (buffer == None): return None cm = CardMaker("filter-stage-quad") if fullscreen: cm.setFrameFullscreenQuad() else: cm.setFrame(-1, 1, -1, 1) quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) 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) dr = buffer.makeDisplayRegion((0, 1, 0, 1)) dr.disableClears() dr.setCamera(quadcam) dr.setActive(True) dr.setScissorEnabled(False) # This clear stage is important if the buffer is padded, so that # any pixels accidentally sampled in the padded region won't # be reading from unititialised memory. buffer.setClearColor((0, 0, 0, 1)) buffer.setClearColorActive(False) if addToList: self.buffers.append(buffer) self.sizes.append((mul, div, align)) self.forceSizes.append((size is not None)) return quad else: return [quad, buffer]
def buildCabinet(base, cabpos=np.array([773.5, -55.17, 1035]), cabrotangle=0, isrendercoord=False): __this_dir, _ = os.path.split(__file__) cabinet = NodePath("cabinet") #build the cabinet #the middle board, 3 pieces middleboardpath = os.path.join(__this_dir, "objects", "middleboard.stl") middleboard0 = cm.CollisionModel(middleboardpath, radius=3, betransparency=True) middleboard0.setColor(1, 0, 0, 1) temprotmiddleboard = rm.rodrigues([0, 0, 1], 90) rotmiddleboardmat4 = middleboard0.getMat() rotmiddleboardnp4 = base.pg.mat4ToNp(rotmiddleboardmat4) rotmiddleboardnp4[:3, :3] = np.dot(temprotmiddleboard, rotmiddleboardnp4[:3, :3]) rotmiddleboardmat4 = base.pg.np4ToMat4(rotmiddleboardnp4) middleboard0.setMat(rotmiddleboardmat4) # temprotsmallboard = np.dot() middleboard1 = copy.deepcopy(middleboard0) middleboard1.setPos(0, 0, 288.5) middleboard2 = copy.deepcopy(middleboard0) temprotmiddleboard = rm.rodrigues([1, 0, 0], 180) rotmiddleboardnp4[:3, :3] = np.dot(temprotmiddleboard, rotmiddleboardnp4[:3, :3]) rotmiddleboardnp4[:3, 3] = np.array([0, 0, 587]) middleboard2.sethomomat(rotmiddleboardnp4) # middleboard2.setPos(0,0,577) middleboard0.setColor(.4, .4, .4, .7) #this 0 doesn't need to setpos middleboard0.reparentTo(cabinet) middleboard1.setColor(.4, .4, .4, .7) middleboard1.reparentTo(cabinet) middleboard2.setColor(.4, .4, .4, .7) middleboard2.reparentTo(cabinet) largeboardpath = os.path.join(__this_dir, "objects", "largeboard.stl") largeboard0 = cm.CollisionModel(largeboardpath, radius=3, betransparency=True) largeboard1 = copy.deepcopy(largeboard0) largecompundrot0 = np.dot(rm.rodrigues([0, 1, 0], -90), rm.rodrigues([1, 0, 0], 90)) largecompundrot1 = np.dot(rm.rodrigues([-1, 0, 0], 180), largecompundrot0) largeboard0.sethomomat( rm.homobuild(np.array([0, 195, 293.5]), largecompundrot0)) largeboard1.sethomomat( rm.homobuild(np.array([0, -195, 293.5]), largecompundrot1)) largeboard0.setColor(.4, .4, .4, .7) largeboard0.reparentTo(cabinet) largeboard1.setColor(.4, .4, .4, .7) largeboard1.reparentTo(cabinet) # the small board, 2 pieces smallboardpath = os.path.join(__this_dir, "objects", "smallboard.stl") smallboard0 = cm.CollisionModel(smallboardpath, radius=3, betransparency=True) smallboard1 = copy.deepcopy(smallboard0) smallcompundrot = np.dot(rm.rodrigues([0, 1, 0], 90), rm.rodrigues([0, 0, 1], -90)) smallboard0.sethomomat( rm.homobuild(np.array([-142.5, 0, 149.25]), smallcompundrot)) smallboard1.sethomomat( rm.homobuild(np.array([-142.5, 0, 587 - 149.25]), smallcompundrot)) smallboard0.setColor(.4, .4, .4, .7) smallboard0.reparentTo(cabinet) smallboard1.setColor(.4, .4, .4, .7) smallboard1.reparentTo(cabinet) if isrendercoord == True: middleboard0.showLocalFrame() middleboard1.showLocalFrame() middleboard2.showLocalFrame() largeboard0.showLocalFrame() largeboard1.showLocalFrame() smallboard0.showLocalFrame() smallboard1.showLocalFrame() #rotate the cabinet cabinetassemblypos = cabpos # on the edge is 773, a bit outside is 814 cabinetassemblyrot = rm.rodrigues([0, 0, 1], cabrotangle) cabinet.setMat( base.pg.np4ToMat4(rm.homobuild(cabinetassemblypos, cabinetassemblyrot))) return cabinet
class Simulation(ShowBase): scale = 1 height = 500 lateralError = 200 dt = 0.1 steps = 0 #Test Controllers fuelPID = PID(10, 0.5, 10, 0, 100) heightPID = PID(0.08, 0, 0.3, 0.1, 1) pitchPID = PID(10, 0, 1000, -10, 10) rollPID = PID(10, 0, 1000, -10, 10) XPID = PID(0.2, 0, 0.8, -10, 10) YPID = PID(0.2, 0, 0.8, -10, 10) vulcain = NeuralNetwork() tau = 0.5 Valves=[] CONTROL = False EMPTY = False LANDED = False DONE = False gimbalX = 0 gimbalY = 0 targetAlt = 250 R = RE(200 * 9.806, 250 * 9.806, 7607000 / 9 * scale, 0.4) throttle = 0.0 fuelMass_full = 417000 * scale fuelMass_init = 0.10 radius = 1.8542 * scale length = 47 * scale Cd = 1.5 def __init__(self, VISUALIZE=False): self.VISUALIZE = VISUALIZE if VISUALIZE is True: ShowBase.__init__(self) self.setBackgroundColor(0.2, 0.2, 0.2, 1) self.setFrameRateMeter(True) self.render.setShaderAuto() self.cam.setPos(-120 * self.scale, -120 * self.scale, 120 * self.scale) self.cam.lookAt(0, 0, 10 * self.scale) alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = self.render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, -1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = self.render.attachNewNode(dlight) self.render.clearLight() self.render.setLight(alightNP) self.render.setLight(dlightNP) self.accept('escape', self.doExit) self.accept('r', self.doReset) self.accept('f1', self.toggleWireframe) self.accept('f2', self.toggleTexture) self.accept('f3', self.toggleDebug) self.accept('f5', self.doScreenshot) inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('left', 'a') inputState.watchWithModifiers('reverse', 's') inputState.watchWithModifiers('right', 'd') inputState.watchWithModifiers('turnLeft', 'q') inputState.watchWithModifiers('turnRight', 'e') self.ostData = OnscreenText(text='ready', pos=(-1.3, 0.9), scale=0.07, fg=Vec4(1, 1, 1, 1), align=TextNode.ALeft) self.fuelMass = self.fuelMass_full * self.fuelMass_init self.vulcain.load_existing_model(path="../LandingRockets/",model_name="140k_samples_1024neurons_3layers_l2-0.000001") # Physics self.setup() # _____HANDLER_____ def doExit(self): self.cleanup() sys.exit(1) def doReset(self): self.cleanup() self.setup() def toggleWireframe(self): ...#self.toggleWireframe() def toggleTexture(self): ...#self.toggleTexture() def toggleDebug(self): if self.debugNP.isHidden(): self.debugNP.show() else: self.debugNP.hide() def doScreenshot(self): self.screenshot('Bullet') # ____TASK___ def processInput(self): throttleChange = 0.0 if inputState.isSet('forward'): self.gimbalY = 10 if inputState.isSet('reverse'): self.gimbalY = -10 if inputState.isSet('left'): self.gimbalX = 10 if inputState.isSet('right'): self.gimbalX = -10 if inputState.isSet('turnLeft'): throttleChange = -1.0 if inputState.isSet('turnRight'): throttleChange = 1.0 self.throttle += throttleChange / 100.0 self.throttle = min(max(self.throttle, 0), 1) def processContacts(self): result = self.world.contactTestPair(self.rocketNP.node(), self.groundNP.node()) #print(result.getNumContacts()) if result.getNumContacts() != 0: self.LANDED = True #self.DONE = True def update(self,task): #self.control(0.1,0.1,0.1) #self.processInput() #self.processContacts() # self.terrain.update() return task.cont def cleanup(self): self.world.removeRigidBody(self.groundNP.node()) self.world.removeRigidBody(self.rocketNP.node()) self.world = None self.debugNP = None self.groundNP = None self.rocketNP = None self.worldNP.removeNode() self.LANDED = False self.EMPTY = False self.DONE = False self.steps = 0 self.fuelMass = self.fuelMass_full*self.fuelMass_init def setup(self): #self.targetAlt = r.randrange(100,300) self.Valves = np.array([0.15,0.2,0.15]) self.EngObs = self.vulcain.predict_data_point(np.array(self.Valves).reshape(1,-1)) if self.VISUALIZE is True: self.worldNP = self.render.attachNewNode('World') else: self.root = NodePath(PandaNode("world root")) self.worldNP = self.root.attachNewNode('World') self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.80665)) # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.node().showWireframe(True) self.debugNP.node().showConstraints(True) self.debugNP.node().showBoundingBoxes(False) self.debugNP.node().showNormals(True) self.debugNP.show() self.world.setDebugNode(self.debugNP.node()) # self.debugNP.showTightBounds() # self.debugNP.showBounds() # Ground (static) shape = BulletPlaneShape(Vec3(0, 0, 1), 1) self.groundNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground')) self.groundNP.node().addShape(shape) self.groundNP.setPos(0, 0, 0) self.groundNP.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.groundNP.node()) # Rocket shape = BulletCylinderShape(self.radius, self.length, ZUp) self.rocketNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Cylinder')) self.rocketNP.node().setMass(27200 * self.scale) self.rocketNP.node().addShape(shape) #self.rocketNP.setPos(20,20,250) self.rocketNP.setPos(r.randrange(-200,200), 20, r.randrange(300, 500)) #self.rocketNP.setPos(r.randrange(-self.lateralError, self.lateralError, 1), r.randrange(-self.lateralError, self.lateralError, 1), self.height) # self.rocketNP.setPos(0, 0, self.length*10) self.rocketNP.setCollideMask(BitMask32.allOn()) # self.rocketNP.node().setCollisionResponse(0) self.rocketNP.node().notifyCollisions(True) self.world.attachRigidBody(self.rocketNP.node()) for i in range(4): leg = BulletCylinderShape(0.1 * self.radius, 0.5 * self.length, XUp) self.rocketNP.node().addShape(leg, TransformState.makePosHpr( Vec3(6 * self.radius * math.cos(i * math.pi / 2), 6 * self.radius * math.sin(i * math.pi / 2), -0.6 * self.length), Vec3(i * 90, 0, 30))) shape = BulletConeShape(0.75 * self.radius, 0.5 * self.radius, ZUp) self.rocketNP.node().addShape(shape, TransformState.makePosHpr(Vec3(0, 0, -1 / 2 * self.length), Vec3(0, 0, 0))) # Fuel self.fuelRadius = 0.9 * self.radius shape = BulletCylinderShape(self.fuelRadius, 0.01 * self.length, ZUp) self.fuelNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Cone')) self.fuelNP.node().setMass(self.fuelMass_full * self.fuelMass_init) self.fuelNP.node().addShape(shape) self.fuelNP.setPos(0, 0, self.rocketNP.getPos().getZ() - self.length * 0.5 * (1 - self.fuelMass_init)) self.fuelNP.setCollideMask(BitMask32.allOn()) self.fuelNP.node().setCollisionResponse(0) self.world.attachRigidBody(self.fuelNP.node()) frameA = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 90)) frameB = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 90)) self.fuelSlider = BulletSliderConstraint(self.rocketNP.node(), self.fuelNP.node(), frameA, frameB, 1) self.fuelSlider.setTargetLinearMotorVelocity(0) self.fuelSlider.setDebugDrawSize(2.0) self.fuelSlider.set_lower_linear_limit(0) self.fuelSlider.set_upper_linear_limit(0) self.world.attachConstraint(self.fuelSlider) self.npThrustForce = LineNodePath(self.rocketNP, 'Thrust', thickness=4, colorVec=Vec4(1, 0.5, 0, 1)) self.npDragForce = LineNodePath(self.rocketNP, 'Drag', thickness=4, colorVec=Vec4(1, 0, 0, 1)) self.npLiftForce = LineNodePath(self.rocketNP, 'Lift', thickness=4, colorVec=Vec4(0, 0, 1, 1)) self.npFuelState = LineNodePath(self.fuelNP, 'Fuel', thickness=20, colorVec=Vec4(0, 1, 0, 1)) self.rocketCSLon = self.radius ** 2 * math.pi self.rocketCSLat = self.length * 2 * self.radius if self.VISUALIZE is True: self.terrain = loader.loadModel("../LZGrid2.egg") self.terrain.setScale(10) self.terrain.reparentTo(self.render) self.terrain.setColor(Vec4(0.1, 0.2, 0.1, 1)) self.toggleTexture() #self.fuelNP.setPos(0, 0, self.rocketNP.getPos().getZ() - self.length * 0.4 * (1 - self.fuelMass_init)) for i in range(5): self.world.doPhysics(self.dt, 5, 1.0 / 180.0) self.fuelSlider.set_lower_linear_limit(-self.length * 0.5 * (1 - self.fuelMass_init)) self.fuelSlider.set_upper_linear_limit(self.length * 0.5 * (1 - self.fuelMass_init)) for i in range(100): self.world.doPhysics(self.dt, 5, 1.0 / 180.0) self.rocketNP.node().applyForce(Vec3(0,0,300000), Vec3(0, 0, 0)) def updateRocket(self, mdot, dt): # Fuel Update self.fuelMass = self.fuelNP.node().getMass() - dt * mdot if self.fuelMass <= 0: self.EMPTY is True fuel_percent = self.fuelMass / self.fuelMass_full self.fuelNP.node().setMass(self.fuelMass) fuelHeight = self.length * fuel_percent I1 = 1 / 2 * self.fuelMass * self.fuelRadius ** 2 I2 = 1 / 4 * self.fuelMass * self.fuelRadius ** 2 + 1 / 12 * self.fuelMass * fuelHeight * fuelHeight self.fuelNP.node().setInertia(Vec3(I2, I2, I1)) # Shift fuel along slider constraint fuelTargetPos = 0.5 * (self.length - fuelHeight) fuelPos = self.fuelSlider.getLinearPos() self.fuelSlider.set_upper_linear_limit(fuelTargetPos) self.fuelSlider.set_lower_linear_limit(-fuelTargetPos) self.npFuelState.reset() self.npFuelState.drawArrow2d(Vec3(0, 0, -0.5 * fuelHeight), Vec3(0, 0, 0.5 * fuelHeight), 45, 2) self.npFuelState.create() def observe(self): pos = self.rocketNP.getPos() vel = self.rocketNP.node().getLinearVelocity() quat = self.rocketNP.getTransform().getQuat() Roll, Pitch, Yaw = quat.getHpr() rotVel = self.rocketNP.node().getAngularVelocity() return pos, vel, Roll, Pitch, Yaw, rotVel, self.fuelMass / self.fuelMass_full, self.EMPTY, self.DONE, self.LANDED, self.targetAlt, self.EngObs[0], self.Valves def control(self,ValveCommands,gimbalX): self.gimbalX = gimbalX self.gimbalY = 0 self.Valves = ValveCommands-(ValveCommands-self.Valves)*np.exp(-self.dt/self.tau) #self.Valves = ValveCommands self.EngObs = self.vulcain.predict_data_point(np.array(self.Valves).reshape(1,-1 )) #Brennkammerdruck, Gaskammertemp, H2Massenstrom, LOX MAssentrom, Schub #Bar,K,Kg/s,Kg/s,kN #self.dt = globalClock.getDt() pos = self.rocketNP.getPos() vel = self.rocketNP.node().getLinearVelocity() quat = self.rocketNP.getTransform().getQuat() Roll, Pitch, Yaw = quat.getHpr() rotVel = self.rocketNP.node().getAngularVelocity() # CHECK STATE if self.fuelMass <= 0: self.EMPTY = True #if pos.getZ() <= 36: # self.LANDED = True self.LANDED = False self.processContacts() P, T, rho = air_dens(pos[2]) rocketZWorld = quat.xform(Vec3(0, 0, 1)) AoA = math.acos(min(max(dot(norm(vel), norm(-rocketZWorld)), -1), 1)) dynPress = 0.5 * dot(vel, vel) * rho dragArea = self.rocketCSLon + (self.rocketCSLat - self.rocketCSLon) * math.sin(AoA) drag = norm(-vel) * dynPress * self.Cd * dragArea time = globalClock.getFrameTime() liftVec = norm(vel.project(rocketZWorld) - vel) if AoA > 0.5 * math.pi: liftVec = -liftVec lift = liftVec * (math.sin(AoA * 2) * self.rocketCSLat * dynPress) if self.CONTROL: self.throttle = self.heightPID.control(pos.getZ(), vel.getZ(), 33) pitchTgt = self.XPID.control(pos.getX(), vel.getX(), 0) self.gimbalX = -self.pitchPID.control(Yaw, rotVel.getY(), pitchTgt) rollTgt = self.YPID.control(pos.getY(), vel.getY(), 0) self.gimbalY = -self.rollPID.control(Pitch, rotVel.getX(), -rollTgt) self.thrust = self.EngObs[0][4]*1000 #print(self.EngObs) quat = self.rocketNP.getTransform().getQuat() quatGimbal = TransformState.makeHpr(Vec3(0, self.gimbalY, self.gimbalX)).getQuat() thrust = quatGimbal.xform(Vec3(0, 0, self.thrust)) thrustWorld = quat.xform(thrust) #print(thrustWorld) self.npDragForce.reset() self.npDragForce.drawArrow2d(Vec3(0, 0, 0), quat.conjugate().xform(drag) / 1000, 45, 2) self.npDragForce.create() self.npLiftForce.reset() self.npLiftForce.drawArrow2d(Vec3(0, 0, 0), quat.conjugate().xform(lift) / 1000, 45, 2) self.npLiftForce.create() self.npThrustForce.reset() if self.EMPTY is False & self.LANDED is False: self.npThrustForce.drawArrow2d(Vec3(0, 0, -0.5 * self.length), Vec3(0, 0, -0.5 * self.length) - thrust / 30000, 45, 2) self.npThrustForce.create() self.rocketNP.node().applyForce(drag, Vec3(0, 0, 0)) self.rocketNP.node().applyForce(lift, Vec3(0, 0, 0)) #print(self.EMPTY,self.LANDED) if self.EMPTY is False & self.LANDED is False: self.rocketNP.node().applyForce(thrustWorld, quat.xform(Vec3(0, 0, -1 / 2 * self.length))) self.updateRocket(self.EngObs[0][2]+self.EngObs[0][3], self.dt) self.rocketNP.node().setActive(True) self.fuelNP.node().setActive(True) self.processInput() self.world.doPhysics(self.dt) self.steps+=1 if self.steps > 1000: self.DONE = True telemetry = [] telemetry.append('Thrust: {}'.format(int(self.EngObs[0][4]))) telemetry.append('Fuel: {}%'.format(int(self.fuelMass / self.fuelMass_full * 100.0))) telemetry.append('Gimbal: {}'.format(int(self.gimbalX)) + ',{}'.format(int(self.gimbalY))) telemetry.append('AoA: {}'.format(int(AoA / math.pi * 180.0))) telemetry.append('\nPos: {},{}'.format(int(pos.getX()), int(pos.getY()))) telemetry.append('Height: {}'.format(int(pos.getZ()))) telemetry.append('RPY: {},{},{}'.format(int(Roll), int(Pitch), int(Yaw))) telemetry.append('Speed: {}'.format(int(np.linalg.norm(vel)))) telemetry.append('Vel: {},{},{}'.format(int(vel.getX()), int(vel.getY()), int(vel.getZ()))) telemetry.append('Rot: {},{},{}'.format(int(rotVel.getX()), int(rotVel.getY()), int(rotVel.getZ()))) telemetry.append('LANDED: {}'.format(self.LANDED)) telemetry.append('Time: {}'.format(self.steps*self.dt)) telemetry.append('TARGET: {}'.format(self.targetAlt)) #print(pos) if self.VISUALIZE is True: self.ostData.setText('\n'.join(telemetry)) self.cam.setPos(pos[0] - 120 * self.scale, pos[1] - 120 * self.scale, pos[2] + 80 * self.scale) self.cam.lookAt(pos[0], pos[1], pos[2]) self.taskMgr.step() """
def setup(self): #self.targetAlt = r.randrange(100,300) self.Valves = np.array([0.15,0.2,0.15]) self.EngObs = self.vulcain.predict_data_point(np.array(self.Valves).reshape(1,-1)) if self.VISUALIZE is True: self.worldNP = self.render.attachNewNode('World') else: self.root = NodePath(PandaNode("world root")) self.worldNP = self.root.attachNewNode('World') self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.80665)) # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.node().showWireframe(True) self.debugNP.node().showConstraints(True) self.debugNP.node().showBoundingBoxes(False) self.debugNP.node().showNormals(True) self.debugNP.show() self.world.setDebugNode(self.debugNP.node()) # self.debugNP.showTightBounds() # self.debugNP.showBounds() # Ground (static) shape = BulletPlaneShape(Vec3(0, 0, 1), 1) self.groundNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground')) self.groundNP.node().addShape(shape) self.groundNP.setPos(0, 0, 0) self.groundNP.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.groundNP.node()) # Rocket shape = BulletCylinderShape(self.radius, self.length, ZUp) self.rocketNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Cylinder')) self.rocketNP.node().setMass(27200 * self.scale) self.rocketNP.node().addShape(shape) #self.rocketNP.setPos(20,20,250) self.rocketNP.setPos(r.randrange(-200,200), 20, r.randrange(300, 500)) #self.rocketNP.setPos(r.randrange(-self.lateralError, self.lateralError, 1), r.randrange(-self.lateralError, self.lateralError, 1), self.height) # self.rocketNP.setPos(0, 0, self.length*10) self.rocketNP.setCollideMask(BitMask32.allOn()) # self.rocketNP.node().setCollisionResponse(0) self.rocketNP.node().notifyCollisions(True) self.world.attachRigidBody(self.rocketNP.node()) for i in range(4): leg = BulletCylinderShape(0.1 * self.radius, 0.5 * self.length, XUp) self.rocketNP.node().addShape(leg, TransformState.makePosHpr( Vec3(6 * self.radius * math.cos(i * math.pi / 2), 6 * self.radius * math.sin(i * math.pi / 2), -0.6 * self.length), Vec3(i * 90, 0, 30))) shape = BulletConeShape(0.75 * self.radius, 0.5 * self.radius, ZUp) self.rocketNP.node().addShape(shape, TransformState.makePosHpr(Vec3(0, 0, -1 / 2 * self.length), Vec3(0, 0, 0))) # Fuel self.fuelRadius = 0.9 * self.radius shape = BulletCylinderShape(self.fuelRadius, 0.01 * self.length, ZUp) self.fuelNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Cone')) self.fuelNP.node().setMass(self.fuelMass_full * self.fuelMass_init) self.fuelNP.node().addShape(shape) self.fuelNP.setPos(0, 0, self.rocketNP.getPos().getZ() - self.length * 0.5 * (1 - self.fuelMass_init)) self.fuelNP.setCollideMask(BitMask32.allOn()) self.fuelNP.node().setCollisionResponse(0) self.world.attachRigidBody(self.fuelNP.node()) frameA = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 90)) frameB = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 90)) self.fuelSlider = BulletSliderConstraint(self.rocketNP.node(), self.fuelNP.node(), frameA, frameB, 1) self.fuelSlider.setTargetLinearMotorVelocity(0) self.fuelSlider.setDebugDrawSize(2.0) self.fuelSlider.set_lower_linear_limit(0) self.fuelSlider.set_upper_linear_limit(0) self.world.attachConstraint(self.fuelSlider) self.npThrustForce = LineNodePath(self.rocketNP, 'Thrust', thickness=4, colorVec=Vec4(1, 0.5, 0, 1)) self.npDragForce = LineNodePath(self.rocketNP, 'Drag', thickness=4, colorVec=Vec4(1, 0, 0, 1)) self.npLiftForce = LineNodePath(self.rocketNP, 'Lift', thickness=4, colorVec=Vec4(0, 0, 1, 1)) self.npFuelState = LineNodePath(self.fuelNP, 'Fuel', thickness=20, colorVec=Vec4(0, 1, 0, 1)) self.rocketCSLon = self.radius ** 2 * math.pi self.rocketCSLat = self.length * 2 * self.radius if self.VISUALIZE is True: self.terrain = loader.loadModel("../LZGrid2.egg") self.terrain.setScale(10) self.terrain.reparentTo(self.render) self.terrain.setColor(Vec4(0.1, 0.2, 0.1, 1)) self.toggleTexture() #self.fuelNP.setPos(0, 0, self.rocketNP.getPos().getZ() - self.length * 0.4 * (1 - self.fuelMass_init)) for i in range(5): self.world.doPhysics(self.dt, 5, 1.0 / 180.0) self.fuelSlider.set_lower_linear_limit(-self.length * 0.5 * (1 - self.fuelMass_init)) self.fuelSlider.set_upper_linear_limit(self.length * 0.5 * (1 - self.fuelMass_init)) for i in range(100): self.world.doPhysics(self.dt, 5, 1.0 / 180.0) self.rocketNP.node().applyForce(Vec3(0,0,300000), Vec3(0, 0, 0))
def addToon(self, toon): marker = NodePath('toon_marker-%i' % toon.doId) marker.reparentTo(self) self._getToonMarker(toon).copyTo(marker) marker.setColor(toon.style.getHeadColor()) if toon.isLocal(): marker.setScale(Globals.Gui.LocalMarkerScale) marker.setBin('fixed', 10) else: marker.setScale(Globals.Gui.MarkerScale) marker.setBin('fixed', 5) marker.flattenStrong() self._toonMarkers[toon] = marker
class DistributedIceGame(DistributedMinigame.DistributedMinigame, DistributedIceWorld.DistributedIceWorld): notify = directNotify.newCategory('DistributedIceGame') MaxLocalForce = 100 MaxPhysicsForce = 25000 def __init__(self, cr): DistributedMinigame.DistributedMinigame.__init__(self, cr) DistributedIceWorld.DistributedIceWorld.__init__(self, cr) self.gameFSM = ClassicFSM.ClassicFSM('DistributedIceGame', [State.State('off', self.enterOff, self.exitOff, ['inputChoice']), State.State('inputChoice', self.enterInputChoice, self.exitInputChoice, ['waitServerChoices', 'moveTires', 'displayVotes', 'cleanup']), State.State('waitServerChoices', self.enterWaitServerChoices, self.exitWaitServerChoices, ['moveTires', 'cleanup']), State.State('moveTires', self.enterMoveTires, self.exitMoveTires, ['synch', 'cleanup']), State.State('synch', self.enterSynch, self.exitSynch, ['inputChoice', 'scoring', 'cleanup']), State.State('scoring', self.enterScoring, self.exitScoring, ['cleanup', 'finalResults', 'inputChoice']), State.State('finalResults', self.enterFinalResults, self.exitFinalResults, ['cleanup']), State.State('cleanup', self.enterCleanup, self.exitCleanup, [])], 'off', 'cleanup') self.addChildGameFSM(self.gameFSM) self.cameraThreeQuarterView = (0, -22, 45, 0, -62.89, 0) self.tireDict = {} self.forceArrowDict = {} self.canDrive = False self.timer = None self.timerStartTime = None self.curForce = 0 self.curHeading = 0 self.headingMomentum = 0.0 self.forceMomentum = 0.0 self.allTireInputs = None self.curRound = 0 self.curMatch = 0 self.controlKeyWarningLabel = DirectLabel(text=TTLocalizer.IceGameControlKeyWarning, text_fg=VBase4(1, 0, 0, 1), relief=None, pos=(0.0, 0, 0), scale=0.15) self.controlKeyWarningLabel.hide() self.waitingMoveLabel = DirectLabel(text=TTLocalizer.IceGameWaitingForPlayersToFinishMove, text_fg=VBase4(1, 1, 1, 1), relief=None, pos=(-0.6, 0, -0.75), scale=0.075) self.waitingMoveLabel.hide() self.waitingSyncLabel = DirectLabel(text=TTLocalizer.IceGameWaitingForAISync, text_fg=VBase4(1, 1, 1, 1), relief=None, pos=(-0.6, 0, -0.75), scale=0.075) self.waitingSyncLabel.hide() self.infoLabel = DirectLabel(text='', text_fg=VBase4(0, 0, 0, 1), relief=None, pos=(0.0, 0, 0.7), scale=0.075) self.updateInfoLabel() self.lastForceArrowUpdateTime = 0 self.sendForceArrowUpdateAsap = False self.treasures = [] self.penalties = [] self.obstacles = [] self.controlKeyPressed = False self.controlKeyWarningIval = None return def delete(self): DistributedIceWorld.DistributedIceWorld.delete(self) DistributedMinigame.DistributedMinigame.delete(self) if self.controlKeyWarningIval: self.controlKeyWarningIval.finish() self.controlKeyWarningIval = None self.controlKeyWarningLabel.destroy() del self.controlKeyWarningLabel self.waitingMoveLabel.destroy() del self.waitingMoveLabel self.waitingSyncLabel.destroy() del self.waitingSyncLabel self.infoLabel.destroy() del self.infoLabel for treasure in self.treasures: treasure.destroy() del self.treasures for penalty in self.penalties: penalty.destroy() del self.penalties for obstacle in self.obstacles: obstacle.removeNode() del self.obstacles del self.gameFSM return def announceGenerate(self): DistributedMinigame.DistributedMinigame.announceGenerate(self) DistributedIceWorld.DistributedIceWorld.announceGenerate(self) self.debugTaskName = self.uniqueName('debugTask') def getTitle(self): return TTLocalizer.IceGameTitle def getInstructions(self): szId = self.getSafezoneId() numPenalties = IceGameGlobals.NumPenalties[szId] result = TTLocalizer.IceGameInstructions if numPenalties == 0: result = TTLocalizer.IceGameInstructionsNoTnt return result def getMaxDuration(self): return 0 def load(self): self.notify.debug('load') DistributedMinigame.DistributedMinigame.load(self) self.music = base.loader.loadMusic('phase_4/audio/bgm/MG_IceGame.ogg') self.gameBoard = loader.loadModel('phase_4/models/minigames/ice_game_icerink') background = loader.loadModel('phase_4/models/minigames/ice_game_2d') background.reparentTo(self.gameBoard) self.gameBoard.setPosHpr(0, 0, 0, 0, 0, 0) self.gameBoard.setScale(1.0) self.setupSimulation() index = 0 for avId in self.avIdList: self.setupTire(avId, index) self.setupForceArrow(avId) index += 1 for index in xrange(len(self.avIdList), 4): self.setupTire(-index, index) self.setupForceArrow(-index) self.showForceArrows(realPlayersOnly=True) self.westWallModel = NodePath() if not self.westWallModel.isEmpty(): self.westWallModel.reparentTo(self.gameBoard) self.westWallModel.setPos(IceGameGlobals.MinWall[0], IceGameGlobals.MinWall[1], 0) self.westWallModel.setScale(4) self.eastWallModel = NodePath() if not self.eastWallModel.isEmpty(): self.eastWallModel.reparentTo(self.gameBoard) self.eastWallModel.setPos(IceGameGlobals.MaxWall[0], IceGameGlobals.MaxWall[1], 0) self.eastWallModel.setScale(4) self.eastWallModel.setH(180) self.arrowKeys = ArrowKeys.ArrowKeys() self.target = loader.loadModel('phase_3/models/misc/sphere') self.target.setScale(0.01) self.target.reparentTo(self.gameBoard) self.target.setPos(0, 0, 0) self.scoreCircle = loader.loadModel('phase_4/models/minigames/ice_game_score_circle') self.scoreCircle.setScale(0.01) self.scoreCircle.reparentTo(self.gameBoard) self.scoreCircle.setZ(IceGameGlobals.TireRadius / 2.0) self.scoreCircle.setAlphaScale(0.5) self.scoreCircle.setTransparency(1) self.scoreCircle.hide() self.treasureModel = loader.loadModel('phase_4/models/minigames/ice_game_barrel') self.penaltyModel = loader.loadModel('phase_4/models/minigames/ice_game_tnt2') self.penaltyModel.setScale(0.75, 0.75, 0.7) szId = self.getSafezoneId() obstacles = IceGameGlobals.Obstacles[szId] index = 0 cubicObstacle = IceGameGlobals.ObstacleShapes[szId] for pos in obstacles: newPos = Point3(pos[0], pos[1], IceGameGlobals.TireRadius) newObstacle = self.createObstacle(newPos, index, cubicObstacle) self.obstacles.append(newObstacle) index += 1 self.countSound = loader.loadSfx('phase_3.5/audio/sfx/tick_counter.ogg') self.treasureGrabSound = loader.loadSfx('phase_4/audio/sfx/MG_sfx_vine_game_bananas.ogg') self.penaltyGrabSound = loader.loadSfx('phase_4/audio/sfx/MG_cannon_fire_alt.ogg') self.tireSounds = [] for tireIndex in xrange(4): tireHit = loader.loadSfx('phase_4/audio/sfx/Golf_Hit_Barrier_1.ogg') wallHit = loader.loadSfx('phase_4/audio/sfx/MG_maze_pickup.ogg') obstacleHit = loader.loadSfx('phase_4/audio/sfx/Golf_Hit_Barrier_2.ogg') self.tireSounds.append({'tireHit': tireHit, 'wallHit': wallHit, 'obstacleHit': obstacleHit}) self.arrowRotateSound = loader.loadSfx('phase_4/audio/sfx/MG_sfx_ice_force_rotate.ogg') self.arrowUpSound = loader.loadSfx('phase_4/audio/sfx/MG_sfx_ice_force_increase_3sec.ogg') self.arrowDownSound = loader.loadSfx('phase_4/audio/sfx/MG_sfx_ice_force_decrease_3sec.ogg') self.scoreCircleSound = loader.loadSfx('phase_4/audio/sfx/MG_sfx_ice_scoring_1.ogg') def unload(self): self.notify.debug('unload') DistributedMinigame.DistributedMinigame.unload(self) del self.music self.gameBoard.removeNode() del self.gameBoard for forceArrow in self.forceArrowDict.values(): forceArrow.removeNode() del self.forceArrowDict self.scoreCircle.removeNode() del self.scoreCircle del self.countSound def onstage(self): self.notify.debug('onstage') DistributedMinigame.DistributedMinigame.onstage(self) self.gameBoard.reparentTo(render) self.__placeToon(self.localAvId) self.moveCameraToTop() self.scorePanels = [] base.playMusic(self.music, looping=1, volume=0.8) def offstage(self): self.notify.debug('offstage') self.music.stop() self.gameBoard.hide() self.infoLabel.hide() for avId in self.tireDict: self.tireDict[avId]['tireNodePath'].hide() for panel in self.scorePanels: panel.cleanup() del self.scorePanels for obstacle in self.obstacles: obstacle.hide() for treasure in self.treasures: treasure.nodePath.hide() for penalty in self.penalties: penalty.nodePath.hide() for avId in self.avIdList: av = self.getAvatar(avId) if av: av.dropShadow.show() av.resetLOD() taskMgr.remove(self.uniqueName('aimtask')) self.arrowKeys.destroy() del self.arrowKeys DistributedMinigame.DistributedMinigame.offstage(self) def handleDisabledAvatar(self, avId): self.notify.debug('handleDisabledAvatar') self.notify.debug('avatar ' + str(avId) + ' disabled') DistributedMinigame.DistributedMinigame.handleDisabledAvatar(self, avId) def setGameReady(self): if not self.hasLocalToon: return self.notify.debug('setGameReady') if DistributedMinigame.DistributedMinigame.setGameReady(self): return for index in xrange(self.numPlayers): avId = self.avIdList[index] toon = self.getAvatar(avId) if toon: toon.reparentTo(render) self.__placeToon(avId) toon.forwardSpeed = 0 toon.rotateSpeed = False toon.dropShadow.hide() toon.setAnimState('Sit') if avId in self.tireDict: tireNp = self.tireDict[avId]['tireNodePath'] toon.reparentTo(tireNp) toon.setY(1.0) toon.setZ(-3) toon.startLookAround() def setGameStart(self, timestamp): if not self.hasLocalToon: return self.notify.debug('setGameStart') DistributedMinigame.DistributedMinigame.setGameStart(self, timestamp) for avId in self.remoteAvIdList: toon = self.getAvatar(avId) if toon: toon.stopLookAround() self.scores = [ 0] * self.numPlayers spacing = 0.4 for i in xrange(self.numPlayers): avId = self.avIdList[i] avName = self.getAvatarName(avId) scorePanel = MinigameAvatarScorePanel.MinigameAvatarScorePanel(avId, avName) scorePanel.setScale(0.9) scorePanel.setPos(-0.583 - spacing * (self.numPlayers - 1 - i), 0.0, -0.15) scorePanel.reparentTo(base.a2dTopRight) scorePanel.makeTransparent(0.75) self.scorePanels.append(scorePanel) self.arrowKeys.setPressHandlers([self.__upArrowPressed, self.__downArrowPressed, self.__leftArrowPressed, self.__rightArrowPressed, self.__controlPressed]) def isInPlayState(self): if not self.gameFSM.getCurrentState(): return False if not self.gameFSM.getCurrentState().getName() == 'play': return False return True def enterOff(self): self.notify.debug('enterOff') def exitOff(self): pass def enterInputChoice(self): self.notify.debug('enterInputChoice') self.forceLocalToonToTire() self.controlKeyPressed = False if self.curRound == 0: self.setupStartOfMatch() else: self.notify.debug('self.curRound = %s' % self.curRound) self.timer = ToontownTimer.ToontownTimer() self.timer.hide() if self.timerStartTime != None: self.startTimer() self.showForceArrows(realPlayersOnly=True) self.localForceArrow().setPosHpr(0, 0, -1.0, 0, 0, 0) self.localForceArrow().reparentTo(self.localTireNp()) self.localForceArrow().setY(IceGameGlobals.TireRadius) self.localTireNp().headsUp(self.target) self.notify.debug('self.localForceArrow() heading = %s' % self.localForceArrow().getH()) self.curHeading = self.localTireNp().getH() self.curForce = 25 self.updateLocalForceArrow() for avId in self.forceArrowDict: forceArrow = self.forceArrowDict[avId] forceArrow.setPosHpr(0, 0, -1.0, 0, 0, 0) tireNp = self.tireDict[avId]['tireNodePath'] forceArrow.reparentTo(tireNp) forceArrow.setY(IceGameGlobals.TireRadius) tireNp.headsUp(self.target) self.updateForceArrow(avId, tireNp.getH(), 25) taskMgr.add(self.__aimTask, self.uniqueName('aimtask')) if base.localAvatar.laffMeter: base.localAvatar.laffMeter.stop() self.sendForceArrowUpdateAsap = False return def exitInputChoice(self): if not self.controlKeyPressed: if self.controlKeyWarningIval: self.controlKeyWarningIval.finish() self.controlKeyWarningIval = None self.controlKeyWarningIval = Sequence(Func(self.controlKeyWarningLabel.show), self.controlKeyWarningLabel.colorScaleInterval(10, VBase4(1, 1, 1, 0), startColorScale=VBase4(1, 1, 1, 1)), Func(self.controlKeyWarningLabel.hide)) self.controlKeyWarningIval.start() if self.timer != None: self.timer.destroy() self.timer = None self.timerStartTime = None self.hideForceArrows() self.arrowRotateSound.stop() self.arrowUpSound.stop() self.arrowDownSound.stop() taskMgr.remove(self.uniqueName('aimtask')) return def enterWaitServerChoices(self): self.waitingMoveLabel.show() self.showForceArrows(True) def exitWaitServerChoices(self): self.waitingMoveLabel.hide() self.hideForceArrows() def enterMoveTires(self): for key in self.tireDict: body = self.tireDict[key]['tireBody'] body.setAngularVel(0, 0, 0) body.setLinearVel(0, 0, 0) for index in xrange(len(self.allTireInputs)): input = self.allTireInputs[index] avId = self.avIdList[index] body = self.getTireBody(avId) degs = input[1] + 90 tireNp = self.getTireNp(avId) tireH = tireNp.getH() self.notify.debug('tireH = %s' % tireH) radAngle = deg2Rad(degs) foo = NodePath('foo') dirVector = Vec3(math.cos(radAngle), math.sin(radAngle), 0) self.notify.debug('dirVector is now=%s' % dirVector) inputForce = input[0] inputForce /= self.MaxLocalForce inputForce *= self.MaxPhysicsForce force = dirVector * inputForce self.notify.debug('adding force %s to %d' % (force, avId)) body.addForce(force) self.enableAllTireBodies() self.totalPhysicsSteps = 0 self.startSim() taskMgr.add(self.__moveTiresTask, self.uniqueName('moveTiresTtask')) def exitMoveTires(self): self.forceLocalToonToTire() self.disableAllTireBodies() self.stopSim() self.notify.debug('total Physics steps = %d' % self.totalPhysicsSteps) taskMgr.remove(self.uniqueName('moveTiresTtask')) def enterSynch(self): self.waitingSyncLabel.show() def exitSynch(self): self.waitingSyncLabel.hide() def enterScoring(self): sortedByDistance = [] for avId in self.avIdList: np = self.getTireNp(avId) pos = np.getPos() pos.setZ(0) sortedByDistance.append((avId, pos.length())) def compareDistance(x, y): if x[1] - y[1] > 0: return 1 else: if x[1] - y[1] < 0: return -1 return 0 sortedByDistance.sort(cmp=compareDistance) self.scoreMovie = Sequence() curScale = 0.01 curTime = 0 self.scoreCircle.setScale(0.01) self.scoreCircle.show() self.notify.debug('newScores = %s' % self.newScores) circleStartTime = 0 for index in xrange(len(sortedByDistance)): distance = sortedByDistance[index][1] avId = sortedByDistance[index][0] scorePanelIndex = self.avIdList.index(avId) time = (distance - curScale) / IceGameGlobals.ExpandFeetPerSec if time < 0: time = 0.01 scaleXY = distance + IceGameGlobals.TireRadius self.notify.debug('circleStartTime = %s' % circleStartTime) self.scoreMovie.append(Parallel(LerpScaleInterval(self.scoreCircle, time, Point3(scaleXY, scaleXY, 1.0)), SoundInterval(self.scoreCircleSound, duration=time, startTime=circleStartTime))) circleStartTime += time startScore = self.scorePanels[scorePanelIndex].getScore() destScore = self.newScores[scorePanelIndex] self.notify.debug('for avId %d, startScore=%d, newScores=%d' % (avId, startScore, destScore)) def increaseScores(t, scorePanelIndex=scorePanelIndex, startScore=startScore, destScore=destScore): oldScore = self.scorePanels[scorePanelIndex].getScore() diff = destScore - startScore newScore = int(startScore + diff * t) if newScore > oldScore: base.playSfx(self.countSound) self.scorePanels[scorePanelIndex].setScore(newScore) self.scores[scorePanelIndex] = newScore duration = (destScore - startScore) * IceGameGlobals.ScoreCountUpRate tireNp = self.tireDict[avId]['tireNodePath'] self.scoreMovie.append(Parallel(LerpFunctionInterval(increaseScores, duration), Sequence(LerpColorScaleInterval(tireNp, duration / 6.0, VBase4(1, 0, 0, 1)), LerpColorScaleInterval(tireNp, duration / 6.0, VBase4(1, 1, 1, 1)), LerpColorScaleInterval(tireNp, duration / 6.0, VBase4(1, 0, 0, 1)), LerpColorScaleInterval(tireNp, duration / 6.0, VBase4(1, 1, 1, 1)), LerpColorScaleInterval(tireNp, duration / 6.0, VBase4(1, 0, 0, 1)), LerpColorScaleInterval(tireNp, duration / 6.0, VBase4(1, 1, 1, 1))))) curScale += distance self.scoreMovie.append(Func(self.sendUpdate, 'reportScoringMovieDone', [])) self.scoreMovie.start() def exitScoring(self): self.scoreMovie.finish() self.scoreMovie = None self.scoreCircle.hide() return def enterFinalResults(self): lerpTrack = Parallel() lerpDur = 0.5 tY = 0.6 bY = -0.05 lX = -0.5 cX = 0 rX = 0.5 scorePanelLocs = (((cX, bY),), ( ( lX, bY), (rX, bY)), ( ( cX, tY), (lX, bY), (rX, bY)), ( ( lX, tY), ( rX, tY), ( lX, bY), ( rX, bY))) scorePanelLocs = scorePanelLocs[(self.numPlayers - 1)] for i in xrange(self.numPlayers): panel = self.scorePanels[i] pos = scorePanelLocs[i] panel.wrtReparentTo(aspect2d) lerpTrack.append(Parallel(LerpPosInterval(panel, lerpDur, Point3(pos[0], 0, pos[1]), blendType='easeInOut'), LerpScaleInterval(panel, lerpDur, Vec3(panel.getScale()) * 2.0, blendType='easeInOut'))) self.showScoreTrack = Parallel(lerpTrack, Sequence(Wait(IceGameGlobals.ShowScoresDuration), Func(self.gameOver))) self.showScoreTrack.start() def exitFinalResults(self): self.showScoreTrack.pause() del self.showScoreTrack def enterCleanup(self): self.notify.debug('enterCleanup') if base.localAvatar.laffMeter: base.localAvatar.laffMeter.start() def exitCleanup(self): pass def __placeToon(self, avId): toon = self.getAvatar(avId) if toon: toon.setPos(0, 0, 0) toon.setHpr(0, 0, 0) def moveCameraToTop(self): camera.reparentTo(render) p = self.cameraThreeQuarterView camera.setPosHpr(p[0], p[1], p[2], p[3], p[4], p[5]) def setupTire(self, avId, index): tireNp, tireBody, tireOdeGeom = self.createTire(index) self.tireDict[avId] = {'tireNodePath': tireNp, 'tireBody': tireBody, 'tireOdeGeom': tireOdeGeom} if avId <= 0: tireBlocker = tireNp.find('**/tireblockermesh') if not tireBlocker.isEmpty(): tireBlocker.hide() if avId == self.localAvId: tireNp = self.tireDict[avId]['tireNodePath'] self.treasureSphereName = 'treasureCollider' self.treasureCollSphere = CollisionSphere(0, 0, 0, IceGameGlobals.TireRadius) self.treasureCollSphere.setTangible(0) self.treasureCollNode = CollisionNode(self.treasureSphereName) self.treasureCollNode.setFromCollideMask(ToontownGlobals.PieBitmask) self.treasureCollNode.addSolid(self.treasureCollSphere) self.treasureCollNodePath = tireNp.attachNewNode(self.treasureCollNode) self.treasureHandler = CollisionHandlerEvent() self.treasureHandler.addInPattern('%fn-intoTreasure') base.cTrav.addCollider(self.treasureCollNodePath, self.treasureHandler) eventName = '%s-intoTreasure' % self.treasureCollNodePath.getName() self.notify.debug('eventName = %s' % eventName) self.accept(eventName, self.toonHitSomething) def setupForceArrow(self, avId): arrow = loader.loadModel('phase_4/models/minigames/ice_game_arrow') priority = 0 if avId < 0: priority = -avId else: priority = self.avIdList.index(avId) if avId == self.localAvId: priority = 10 self.forceArrowDict[avId] = arrow def hideForceArrows(self): for forceArrow in self.forceArrowDict.values(): forceArrow.hide() def showForceArrows(self, realPlayersOnly=True): for avId in self.forceArrowDict: if realPlayersOnly: if avId > 0: self.forceArrowDict[avId].show() else: self.forceArrowDict[avId].hide() else: self.forceArrowDict[avId].show() def localForceArrow(self): if self.localAvId in self.forceArrowDict: return self.forceArrowDict[self.localAvId] else: return return def setChoices(self, input0, input1, input2, input3): pass def startDebugTask(self): taskMgr.add(self.debugTask, self.debugTaskName) def stopDebugTask(self): taskMgr.remove(self.debugTaskName) def debugTask(self, task): if self.canDrive and localAvatar.doId in self.tireDict: dt = globalClock.getDt() forceMove = 25000 forceMoveDt = forceMove tireBody = self.tireDict[localAvatar.doId]['tireBody'] if self.arrowKeys.upPressed() and not tireBody.isEnabled(): x = 0 y = 1 tireBody.enable() tireBody.addForce(Vec3(x * forceMoveDt, y * forceMoveDt, 0)) if self.arrowKeys.downPressed() and not tireBody.isEnabled(): x = 0 y = -1 tireBody.enable() tireBody.addForce(Vec3(x * forceMoveDt, y * forceMoveDt, 0)) if self.arrowKeys.leftPressed() and not tireBody.isEnabled(): x = -1 y = 0 tireBody.enable() tireBody.addForce(Vec3(x * forceMoveDt, y * forceMoveDt, 0)) if self.arrowKeys.rightPressed() and not tireBody.isEnabled(): x = 1 y = 0 tireBody.enable() tireBody.addForce(Vec3(x * forceMoveDt, y * forceMoveDt, 0)) return task.cont def __upArrowPressed(self): pass def __downArrowPressed(self): pass def __leftArrowPressed(self): pass def __rightArrowPressed(self): pass def __controlPressed(self): if self.gameFSM.getCurrentState().getName() == 'inputChoice': self.sendForceArrowUpdateAsap = True self.updateLocalForceArrow() self.controlKeyPressed = True self.sendUpdate('setAvatarChoice', [self.curForce, self.curHeading]) self.gameFSM.request('waitServerChoices') def startTimer(self): now = globalClock.getFrameTime() elapsed = now - self.timerStartTime self.timer.posInTopRightCorner() self.timer.setTime(IceGameGlobals.InputTimeout) self.timer.countdown(IceGameGlobals.InputTimeout - elapsed, self.handleChoiceTimeout) self.timer.show() def setTimerStartTime(self, timestamp): if not self.hasLocalToon: return else: self.timerStartTime = globalClockDelta.networkToLocalTime(timestamp) if self.timer != None: self.startTimer() return def handleChoiceTimeout(self): self.sendUpdate('setAvatarChoice', [0, 0]) self.gameFSM.request('waitServerChoices') def localTireNp(self): ret = None if self.localAvId in self.tireDict: ret = self.tireDict[self.localAvId]['tireNodePath'] return ret def localTireBody(self): ret = None if self.localAvId in self.tireDict: ret = self.tireDict[self.localAvId]['tireBody'] return ret def getTireBody(self, avId): ret = None if avId in self.tireDict: ret = self.tireDict[avId]['tireBody'] return ret def getTireNp(self, avId): ret = None if avId in self.tireDict: ret = self.tireDict[avId]['tireNodePath'] return ret def updateForceArrow(self, avId, curHeading, curForce): forceArrow = self.forceArrowDict[avId] tireNp = self.tireDict[avId]['tireNodePath'] tireNp.setH(curHeading) tireBody = self.tireDict[avId]['tireBody'] tireBody.setQuaternion(tireNp.getQuat()) self.notify.debug('curHeading = %s' % curHeading) yScale = curForce / 100.0 yScale *= 1 headY = yScale * 15 xScale = (yScale - 1) / 2.0 + 1.0 shaft = forceArrow.find('**/arrow_shaft') head = forceArrow.find('**/arrow_head') shaft.setScale(xScale, yScale, 1) head.setPos(0, headY, 0) head.setScale(xScale, xScale, 1) def updateLocalForceArrow(self): avId = self.localAvId self.b_setForceArrowInfo(avId, self.curHeading, self.curForce) def __aimTask(self, task): if not hasattr(self, 'arrowKeys'): return task.done dt = globalClock.getDt() headingMomentumChange = dt * 60.0 forceMomentumChange = dt * 160.0 arrowUpdate = False arrowRotating = False arrowUp = False arrowDown = False if self.arrowKeys.upPressed() and not self.arrowKeys.downPressed(): self.forceMomentum += forceMomentumChange if self.forceMomentum < 0: self.forceMomentum = 0 if self.forceMomentum > 50: self.forceMomentum = 50 oldForce = self.curForce self.curForce += self.forceMomentum * dt arrowUpdate = True if oldForce < self.MaxLocalForce: arrowUp = True elif self.arrowKeys.downPressed() and not self.arrowKeys.upPressed(): self.forceMomentum += forceMomentumChange if self.forceMomentum < 0: self.forceMomentum = 0 if self.forceMomentum > 50: self.forceMomentum = 50 oldForce = self.curForce self.curForce -= self.forceMomentum * dt arrowUpdate = True if oldForce > 0.01: arrowDown = True else: self.forceMomentum = 0 if self.arrowKeys.leftPressed() and not self.arrowKeys.rightPressed(): self.headingMomentum += headingMomentumChange if self.headingMomentum < 0: self.headingMomentum = 0 if self.headingMomentum > 50: self.headingMomentum = 50 self.curHeading += self.headingMomentum * dt arrowUpdate = True arrowRotating = True elif self.arrowKeys.rightPressed() and not self.arrowKeys.leftPressed(): self.headingMomentum += headingMomentumChange if self.headingMomentum < 0: self.headingMomentum = 0 if self.headingMomentum > 50: self.headingMomentum = 50 self.curHeading -= self.headingMomentum * dt arrowUpdate = True arrowRotating = True else: self.headingMomentum = 0 if arrowUpdate: self.normalizeHeadingAndForce() self.updateLocalForceArrow() if arrowRotating: if not self.arrowRotateSound.status() == self.arrowRotateSound.PLAYING: base.playSfx(self.arrowRotateSound, looping=True) else: self.arrowRotateSound.stop() if arrowUp: if not self.arrowUpSound.status() == self.arrowUpSound.PLAYING: base.playSfx(self.arrowUpSound, looping=False) else: self.arrowUpSound.stop() if arrowDown: if not self.arrowDownSound.status() == self.arrowDownSound.PLAYING: base.playSfx(self.arrowDownSound, looping=False) else: self.arrowDownSound.stop() return task.cont def normalizeHeadingAndForce(self): if self.curForce > self.MaxLocalForce: self.curForce = self.MaxLocalForce if self.curForce < 0.01: self.curForce = 0.01 def setTireInputs(self, tireInputs): if not self.hasLocalToon: return self.allTireInputs = tireInputs self.gameFSM.request('moveTires') def enableAllTireBodies(self): for avId in self.tireDict.keys(): self.tireDict[avId]['tireBody'].enable() def disableAllTireBodies(self): for avId in self.tireDict.keys(): self.tireDict[avId]['tireBody'].disable() def areAllTiresDisabled(self): for avId in self.tireDict.keys(): if self.tireDict[avId]['tireBody'].isEnabled(): return False return True def __moveTiresTask(self, task): if self.areAllTiresDisabled(): self.sendTirePositions() self.gameFSM.request('synch') return task.done return task.cont def sendTirePositions(self): tirePositions = [] for index in xrange(len(self.avIdList)): avId = self.avIdList[index] tire = self.getTireBody(avId) pos = Point3(tire.getPosition()) tirePositions.append([pos[0], pos[1], pos[2]]) for index in xrange(len(self.avIdList), 4): avId = -index tire = self.getTireBody(avId) pos = Point3(tire.getPosition()) tirePositions.append([pos[0], pos[1], pos[2]]) self.sendUpdate('endingPositions', [tirePositions]) def setFinalPositions(self, finalPos): if not self.hasLocalToon: return for index in xrange(len(self.avIdList)): avId = self.avIdList[index] tire = self.getTireBody(avId) np = self.getTireNp(avId) pos = finalPos[index] tire.setPosition(pos[0], pos[1], pos[2]) np.setPos(pos[0], pos[1], pos[2]) for index in xrange(len(self.avIdList), 4): avId = -index tire = self.getTireBody(avId) np = self.getTireNp(avId) pos = finalPos[index] tire.setPosition(pos[0], pos[1], pos[2]) np.setPos(pos[0], pos[1], pos[2]) def updateInfoLabel(self): self.infoLabel['text'] = TTLocalizer.IceGameInfo % {'curMatch': self.curMatch + 1, 'numMatch': IceGameGlobals.NumMatches, 'curRound': self.curRound + 1, 'numRound': IceGameGlobals.NumRounds} def setMatchAndRound(self, match, round): if not self.hasLocalToon: return self.curMatch = match self.curRound = round self.updateInfoLabel() def setScores(self, match, round, scores): if not self.hasLocalToon: return self.newMatch = match self.newRound = round self.newScores = scores def setNewState(self, state): if not self.hasLocalToon: return self.notify.debug('setNewState gameFSM=%s newState=%s' % (self.gameFSM, state)) self.gameFSM.request(state) def putAllTiresInStartingPositions(self): for index in xrange(len(self.avIdList)): avId = self.avIdList[index] np = self.tireDict[avId]['tireNodePath'] np.setPos(IceGameGlobals.StartingPositions[index]) self.notify.debug('avId=%s newPos=%s' % (avId, np.getPos)) np.setHpr(0, 0, 0) quat = np.getQuat() body = self.tireDict[avId]['tireBody'] body.setPosition(IceGameGlobals.StartingPositions[index]) body.setQuaternion(quat) for index in xrange(len(self.avIdList), 4): avId = -index np = self.tireDict[avId]['tireNodePath'] np.setPos(IceGameGlobals.StartingPositions[index]) self.notify.debug('avId=%s newPos=%s' % (avId, np.getPos)) np.setHpr(0, 0, 0) quat = np.getQuat() body = self.tireDict[avId]['tireBody'] body.setPosition(IceGameGlobals.StartingPositions[index]) body.setQuaternion(quat) def b_setForceArrowInfo(self, avId, force, heading): self.setForceArrowInfo(avId, force, heading) self.d_setForceArrowInfo(avId, force, heading) def d_setForceArrowInfo(self, avId, force, heading): sendIt = False curTime = self.getCurrentGameTime() if self.sendForceArrowUpdateAsap: sendIt = True elif curTime - self.lastForceArrowUpdateTime > 0.2: sendIt = True if sendIt: self.sendUpdate('setForceArrowInfo', [avId, force, heading]) self.sendForceArrowUpdateAsap = False self.lastForceArrowUpdateTime = self.getCurrentGameTime() def setForceArrowInfo(self, avId, force, heading): if not self.hasLocalToon: return self.updateForceArrow(avId, force, heading) def setupStartOfMatch(self): self.putAllTiresInStartingPositions() szId = self.getSafezoneId() self.numTreasures = IceGameGlobals.NumTreasures[szId] if self.treasures: for treasure in self.treasures: treasure.destroy() self.treasures = [] index = 0 treasureMargin = IceGameGlobals.TireRadius + 1.0 while len(self.treasures) < self.numTreasures: xPos = self.randomNumGen.randrange(IceGameGlobals.MinWall[0] + 5, IceGameGlobals.MaxWall[0] - 5) yPos = self.randomNumGen.randrange(IceGameGlobals.MinWall[1] + 5, IceGameGlobals.MaxWall[1] - 5) self.notify.debug('yPos=%s' % yPos) pos = Point3(xPos, yPos, IceGameGlobals.TireRadius) newTreasure = IceTreasure.IceTreasure(self.treasureModel, pos, index, self.doId, penalty=False) goodSpot = True for obstacle in self.obstacles: if newTreasure.nodePath.getDistance(obstacle) < treasureMargin: goodSpot = False break if goodSpot: for treasure in self.treasures: if newTreasure.nodePath.getDistance(treasure.nodePath) < treasureMargin: goodSpot = False break if goodSpot: self.treasures.append(newTreasure) index += 1 else: newTreasure.destroy() self.numPenalties = IceGameGlobals.NumPenalties[szId] if self.penalties: for penalty in self.penalties: penalty.destroy() self.penalties = [] index = 0 while len(self.penalties) < self.numPenalties: xPos = self.randomNumGen.randrange(IceGameGlobals.MinWall[0] + 5, IceGameGlobals.MaxWall[0] - 5) yPos = self.randomNumGen.randrange(IceGameGlobals.MinWall[1] + 5, IceGameGlobals.MaxWall[1] - 5) self.notify.debug('yPos=%s' % yPos) pos = Point3(xPos, yPos, IceGameGlobals.TireRadius) newPenalty = IceTreasure.IceTreasure(self.penaltyModel, pos, index, self.doId, penalty=True) goodSpot = True for obstacle in self.obstacles: if newPenalty.nodePath.getDistance(obstacle) < treasureMargin: goodSpot = False break if goodSpot: for treasure in self.treasures: if newPenalty.nodePath.getDistance(treasure.nodePath) < treasureMargin: goodSpot = False break if goodSpot: for penalty in self.penalties: if newPenalty.nodePath.getDistance(penalty.nodePath) < treasureMargin: goodSpot = False break if goodSpot: self.penalties.append(newPenalty) index += 1 else: newPenalty.destroy() def toonHitSomething(self, entry): self.notify.debug('---- treasure Enter ---- ') self.notify.debug('%s' % entry) name = entry.getIntoNodePath().getName() parts = name.split('-') if len(parts) < 3: self.notify.debug('collided with %s, but returning' % name) return if not int(parts[1]) == self.doId: self.notify.debug("collided with %s, but doId doesn't match" % name) return treasureNum = int(parts[2]) if 'penalty' in parts[0]: self.__penaltyGrabbed(treasureNum) else: self.__treasureGrabbed(treasureNum) def __treasureGrabbed(self, treasureNum): self.treasures[treasureNum].showGrab() self.treasureGrabSound.play() self.sendUpdate('claimTreasure', [treasureNum]) def setTreasureGrabbed(self, avId, treasureNum): if not self.hasLocalToon: return self.notify.debug('treasure %s grabbed by %s' % (treasureNum, avId)) if avId != self.localAvId: self.treasures[treasureNum].showGrab() i = self.avIdList.index(avId) self.scores[i] += 1 self.scorePanels[i].setScore(self.scores[i]) def __penaltyGrabbed(self, penaltyNum): self.penalties[penaltyNum].showGrab() self.sendUpdate('claimPenalty', [penaltyNum]) def setPenaltyGrabbed(self, avId, penaltyNum): if not self.hasLocalToon: return self.notify.debug('penalty %s grabbed by %s' % (penaltyNum, avId)) if avId != self.localAvId: self.penalties[penaltyNum].showGrab() i = self.avIdList.index(avId) self.scores[i] -= 1 self.scorePanels[i].setScore(self.scores[i]) def postStep(self): DistributedIceWorld.DistributedIceWorld.postStep(self) for entry in self.colEntries: c0, c1 = self.getOrderedContacts(entry) if c1 in self.tireCollideIds: tireIndex = self.tireCollideIds.index(c1) if c0 in self.tireCollideIds: self.tireSounds[tireIndex]['tireHit'].play() elif c0 == self.wallCollideId: self.tireSounds[tireIndex]['wallHit'].play() elif c0 == self.obstacleCollideId: self.tireSounds[tireIndex]['obstacleHit'].play() def forceLocalToonToTire(self): toon = localAvatar if toon and self.localAvId in self.tireDict: tireNp = self.tireDict[self.localAvId]['tireNodePath'] toon.reparentTo(tireNp) toon.setPosHpr(0, 0, 0, 0, 0, 0) toon.setY(1.0) toon.setZ(-3)
class MyApp(ShowBase): def __init__(self, screen_size=84): ShowBase.__init__(self) self.render.setShaderAuto() # Offscreen Buffer winprops = WindowProperties.size(screen_size, screen_size) fbprops = FrameBufferProperties() self.pipe = GraphicsPipeSelection.get_global_ptr().make_module_pipe( 'pandagl') self.imageBuffer = self.graphicsEngine.makeOutput( self.pipe, "image buffer", 1, fbprops, winprops, GraphicsPipe.BFRefuseWindow) # Camera self.camera = Camera('cam') self.cam = NodePath(self.camera) self.cam.reparentTo(self.render) self.cam.setPos(0, 0, 7) self.cam.lookAt(0, 0, 0) #Display Region self.dr = self.imageBuffer.makeDisplayRegion() self.dr.setCamera(self.cam) # Spotlight with shadows self.light = Spotlight('light') self.lightNP = self.render.attachNewNode(self.light) self.lightNP.setPos(0, 10, 10) self.lightNP.lookAt(0, 0, 0) self.lightNP.node().setShadowCaster(True, 1024, 1024) self.render.setLight(self.lightNP) # Block node = PandaNode('Block') block_np = self.render.attachNewNode(node) model = loader.loadModel('box.egg') model.reparentTo(block_np) self.start_time = time.time() def get_camera_image(self, requested_format=None): tex = self.dr.getScreenshot() data = tex.getRamImage() image = np.frombuffer(data, np.uint8) image.shape = (tex.getYSize(), tex.getXSize(), tex.getNumComponents()) return image def rotate_light(self): radius = 10 step = 0.1 t = time.time() - self.start_time angleDegrees = t * step angleRadians = angleDegrees * (np.pi / 180.0) self.lightNP.setPos(radius * np.sin(angleRadians), -radius * np.cos(angleRadians), 3) self.lightNP.lookAt(0, 0, 0) def step(self): self.rotate_light() self.graphicsEngine.renderFrame() image = self.get_camera_image() return image
def __init__(self): ShowBase.__init__(self) self.scene = self.loader.loadModel(models_dir + "hallway.bam") # Load the environment model self.scene.reparentTo(self.render) self.scene.setScale(1, 1, 1) self.scene.setPos(0, 0, 1) self.scene.setHpr(90, 0, 0) # Add an ambient light and set sky color sky_col = VBase3(135 / 255.0, 206 / 255.0, 235 / 255.0) self.set_background_color(sky_col) alight = AmbientLight("sky") alight.set_color(VBase4(sky_col * 0.04, 1)) alight_path = self.render.attachNewNode(alight) self.render.set_light(alight_path) # # 4 perpendicular lights (flood light) for light_no in range(4): d_light = DirectionalLight('directionalLight') d_light.setColor(Vec4(*([0.3] * 4))) d_light_NP = self.render.attachNewNode(d_light) d_light_NP.setHpr(-90 * light_no, 0, 0) self.render.setLight(d_light_NP) # # 1 directional light (Sun) sun_light = DirectionalLight('directionalLight') sun_light.setColor(Vec4(*([0.7] * 4))) # directional light is dim green sun_light.getLens().setFilmSize(Vec2(0.8, 0.8)) sun_light.getLens().setNearFar(-0.3, 12) sun_light.setShadowCaster(True, 2 ** 7, 2 ** 7) self.dlightNP = self.render.attachNewNode(sun_light) self.dlightNP.setHpr(0, -65, 0) # Turning shader and lights on self.render.setLight(self.dlightNP) # Load and transform the quadrotor actor. self.quad_model = self.loader.loadModel(models_dir + f'{quad_model_filename}.egg') self.prop_models = [] for prop_no in range(4): prop = self.loader.loadModel(models_dir + 'propeller.egg') x = 0 if prop_no % 2 == 1 else (-0.26 if prop_no == 0 else 0.26) y = 0 if prop_no % 2 == 0 else (-0.26 if prop_no == 3 else 0.26) prop.setPos(x, y, 0) prop.reparentTo(self.quad_model) self.prop_models.append(prop) self.prop_models = tuple(self.prop_models) # self.quad_model.reparentTo(self.scene) self.quad_model.setPos(0, 0, 2) self.quad_neutral_hpr = (90, 0, 0) self.quad_model.setHpr(*self.quad_neutral_hpr) # env cam self.cam_neutral_pos = (0, -4, 3) self.cam.reparentTo(self.scene) # self.cam_neutral_pos = (-4, 0, 1) # self.cam.reparentTo(self.quad_model) self.cam.setPos(*self.cam_neutral_pos) self.cam.lookAt(self.quad_model) self.enableParticles() node = NodePath("PhysicsNode") node.reparentTo(self.scene) self.actor_node = ActorNode("quadrotor-physics") # self.actor_node.getPhysicsObject().setMass(1) self.actor_node_physics = node.attachNewNode(self.actor_node) self.physicsMgr.attachPhysicalNode(self.actor_node) self.quad_model.reparentTo(self.actor_node_physics) # add gravity # gravity_force_node = ForceNode('world-forces') # gravityForce = LinearVectorForce(0, 0, -0.1) # gravity acceleration # gravity_force_node.addForce(gravityForce) # self.physicsMgr.addLinearForce(gravityForce) self.time = datetime.datetime.today().strftime('%Y-%m-%d-%H.%M.%S') self.simulation_folder = "\sims\\" + self.time + '\\' self.simulation_folder_path = ROOT_DIR + self.simulation_folder os.makedirs(self.simulation_folder_path) self.movements = '' self.taskMgr.add(self.camera_move, 'Camera Movement') self.taskMgr.add(self.quad_move, 'Quad Movement') self.taskMgr.add(self.rotate_propellers, 'Propellers Rotation') self.taskMgr.add(self.save_image, 'Screenshot Capture') # self.buffer: GraphicsBuffer = self.win.makeTextureBuffer(name='buffer', x_size=84, y_size=84, tex=None, to_ram=True) # self.buffer.setActive(1) self.images = [] self.image_index = 1
from panda3d.core import NodePath from panda3d.core import CardMaker from panda3d.core import Material from panda3d.core import PNMImage from panda3d.core import Texture from panda3d.core import TextureStage from panda3d.core import DirectionalLight from panda3d.core import AmbientLight cm = CardMaker('card') cm.set_frame(-31, 31, -31, 31) map_np = NodePath("map") card = map_np.attach_new_node(cm.generate()) card.set_p(-90) mat = Material() mat.set_base_color((1.0, 1.0, 1.0, 1)) mat.set_emission((1.0, 1.0, 1.0, 1)) mat.set_metallic(1.0) mat.set_roughness(1.0) card.set_material(mat) texture_size = 256 base_color_pnm = PNMImage(texture_size, texture_size) base_color_pnm.fill(0.72, 0.45, 0.2) # Copper base_color_tex = Texture("BaseColor") base_color_tex.load(base_color_pnm) ts = TextureStage('BaseColor') # a.k.a. Modulate ts.set_mode(TextureStage.M_modulate)
def __init__(self, toon, mg): self.mg = mg self.toon = toon self.splat = Actor(GagGlobals.SPLAT_MDL, {'chan': GagGlobals.SPLAT_CHAN}) self.splat.setScale(0.5) self.splat.setColor( VBase4(250.0 / 255.0, 241.0 / 255.0, 24.0 / 255.0, 1.0)) self.splat.setBillboardPointEye() self.gc = WholeCreamPie() self.gc.build() self.gag = self.gc.getGag() self.toon.play('toss', fromFrame=60, toFrame=85) self.gag.reparentTo(self.toon.find('**/def_joint_right_hold')) throwPath = NodePath('ThrowPath') throwPath.reparentTo(self.toon) throwPath.setScale(render, 1) throwPath.setPos(0, 150, -90) throwPath.setHpr(90, -90, 90) self.gag.wrtReparentTo(render) self.gag.setHpr(throwPath.getHpr(render)) self.track = ProjectileInterval( self.gag, startPos=self.toon.find('**/def_joint_right_hold').getPos(render), endPos=throwPath.getPos(render), gravityMult=0.9, duration=3) self.track.start() taskMgr.doMethodLater(3, self.__handleThrowTrackDone, 'handleThrowTrackDoneDGP-' + str(hash(self)))
class CosmoniumBase(ShowBase): def __init__(self): self.keystrokes = {} self.gui = None #TODO: Temporary for keystroke below self.observer = None #TODO: For window_event below self.wireframe = False self.wireframe_filled = False self.trigger_check_settings = True self.request_fullscreen = False self.init_lang() self.print_info() self.panda_config() ShowBase.__init__(self, windowType='none') if not self.app_config.test_start: create_main_window(self) check_opengl_config(self) self.create_additional_display_regions() self.cam.node().set_camera_mask(BaseObject.DefaultCameraMask) else: self.buttonThrowers = [NodePath('dummy')] self.camera = NodePath('dummy') self.cam = self.camera.attach_new_node('dummy') self.camLens = PerspectiveLens() settings.shader_version = 130 #TODO: should find a better way than patching classes... BaseObject.context = self YamlModuleParser.app = self BodyController.context = self self.setBackgroundColor(0, 0, 0, 1) self.disableMouse() self.render_textures = check_and_create_rendering_buffers(self) cache.init_cache() self.register_events() self.world = self.render.attachNewNode("world") self.annotation = self.render.attachNewNode("annotation") self.annotation.hide(BaseObject.AllCamerasMask) self.annotation.show(BaseObject.DefaultCameraMask) self.world.setShaderAuto() self.annotation.setShaderAuto() workers.asyncTextureLoader = workers.AsyncTextureLoader(self) workers.syncTextureLoader = workers.SyncTextureLoader() def load_lang(self, domain, locale_path): languages = None if sys.platform == 'darwin': #TODO: This is a workaround until either Panda3D provides the locale to use #or we switch to pyobjc. #This should be moved to its own module status, output = subprocess.getstatusoutput('defaults read -g AppleLocale') if status == 0: languages = [output] else: print("Could not retrieve default locale") elif sys.platform == 'win32': import ctypes import locale windll = ctypes.windll.kernel32 language = locale.windows_locale[ windll.GetUserDefaultUILanguage() ] if language is not None: languages = [language] else: print("Could not retrieve default locale") return gettext.translation(domain, locale_path, languages=languages, fallback=True) def init_lang(self): self.translation = self.load_lang('cosmonium', defaultDirContext.find_file('main', 'locale')) self.translation.install() def panda_config(self): data = [] request_opengl_config(data) self.app_panda_config(data) data.append("text-encoding utf8") data.append("paste-emit-keystrokes #f") #TODO: Still needed ? data.append("bounds-type box") data.append("screenshot-extension {}".format(settings.screenshot_format)) data.append("screenshot-filename %~p/{}".format(settings.screenshot_filename)) if settings.win_fullscreen and settings.win_fs_width != 0 and settings.win_fs_height != 0: self.request_fullscreen = True data.append("fullscreen %d" % settings.win_fullscreen) data.append("win-size %d %d" % (settings.win_fs_width, settings.win_fs_height)) else: data.append("win-size %d %d" % (settings.win_width, settings.win_height)) data.append("lens-far-limit %g" % settings.lens_far_limit) loadPrcFileData("", '\n'.join(data)) if settings.prc_file is not None: config_file = settings.prc_file if not os.path.isabs(config_file): config_file = os.path.join(settings.config_dir, config_file) filename = Filename.from_os_specific(config_file) if filename.exists(): print("Loading panda config", filename) loadPrcFile(filename) else: print("Panda config file", filename) def app_panda_config(self, data): pass def print_info(self): print("Python version:", platform.python_version()) print("Panda version: %s (%s) by %s (%s)" % (PandaSystem.getVersionString(), PandaSystem.getGitCommit(), PandaSystem.getDistributor(), PandaSystem.getBuildDate())) print("Panda Systems:") for system in PandaSystem.get_global_ptr().get_systems(): print("\t", system) print("Data type:", "double" if settings.use_double else 'float') def create_additional_display_regions(self): pass def keystroke_event(self, keyname): #TODO: Should be better isolated if self.gui is not None and self.gui.popup_menu: return callback_data = self.keystrokes.get(keyname, None) if callback_data is not None: (method, extraArgs) = callback_data method(*extraArgs) def accept(self, event, method, extraArgs=[], direct=False): if len(event) == 1 and not direct: self.keystrokes[event] = [method, extraArgs] else: ShowBase.accept(self, event, method, extraArgs=extraArgs) def ignore(self, event): if len(event) == 1: if event in self.keystrokes: del self.keystrokes[event] else: ShowBase.ignore(self, event) def register_events(self): if not self.app_config.test_start: self.buttonThrowers[0].node().setKeystrokeEvent('keystroke') self.accept(self.win.getWindowEvent(), self.window_event) self.accept('keystroke', self.keystroke_event) self.accept('panic-deactivate-gsg', self.gsg_failure) def gsg_failure(self, event): print("Internal error detected, see output.log for more details") self.userExit() def get_fullscreen_sizes(self): info = self.pipe.getDisplayInformation() resolutions = [] for idx in range(info.getTotalDisplayModes()): width = info.getDisplayModeWidth(idx) height = info.getDisplayModeHeight(idx) bits = info.getDisplayModeBitsPerPixel(idx) resolutions.append([width, height]) resolutions.sort(key=lambda x: x[0], reverse=True) return resolutions def toggle_fullscreen(self): settings.win_fullscreen = not settings.win_fullscreen wp = WindowProperties(self.win.getProperties()) wp.setFullscreen(settings.win_fullscreen) if settings.win_fullscreen: if settings.win_fs_width != 0 and settings.win_fs_height != 0: win_fs_width = settings.win_fs_width win_fs_height = settings.win_fs_height else: win_fs_width = base.pipe.getDisplayWidth() win_fs_height = base.pipe.getDisplayHeight() wp.setSize(win_fs_width, win_fs_height) # Defer config saving in case the switch fails self.request_fullscreen = True else: wp.setSize(settings.win_width, settings.win_height) configParser.save() self.win.requestProperties(wp) def window_event(self, window): if self.win is None: return if self.win.is_closed(): self.userExit() wp = self.win.getProperties() width = wp.getXSize() height = wp.getYSize() if settings.win_fullscreen: # Only save config is the switch to FS is successful if wp.getFullscreen(): if self.request_fullscreen or width != settings.win_fs_width or height != settings.win_fs_height: settings.win_fs_width = width settings.win_fs_height = height configParser.save() if self.request_fullscreen: if self.gui is not None: self.gui.update_info("Press <Alt-Enter> to leave fullscreen mode", 0.5, 2.0) else: if self.gui is not None: self.gui.update_info("Could not switch to fullscreen mode", 0.5, 2.0) settings.win_fullscreen = False self.request_fullscreen = False else: if width != settings.win_width or height != settings.win_height: settings.win_width = width settings.win_height = height configParser.save() if self.observer is not None: self.observer.set_film_size(width, height) self.render.setShaderInput("near_plane_height", self.observer.height / self.observer.tan_fov2) self.render.setShaderInput("pixel_size", self.observer.pixel_size) if self.gui is not None: self.gui.update_size(width, height) if settings.color_picking and self.oid_texture is not None: self.oid_texture.clear() self.oid_texture.setup_2d_texture(width, height, Texture.T_unsigned_byte, Texture.F_rgba8) self.oid_texture.set_clear_color(LColor(0, 0, 0, 0)) def connect_pstats(self): PStatClient.connect() def toggle_wireframe(self): self.world.clear_render_mode() if self.wireframe_filled: self.wireframe_filled = False self.wireframe = False self.wireframe = not self.wireframe if self.wireframe: self.world.set_render_mode_wireframe() def toggle_filled_wireframe(self): self.world.clear_render_mode() if self.wireframe: self.wireframe = False self.wireframe_filled = False self.wireframe_filled = not self.wireframe_filled if self.wireframe_filled: self.world.set_render_mode_filled_wireframe(settings.wireframe_fill_color) def save_screenshot(self, filename=None): if filename is None: filename = self.screenshot(namePrefix=settings.screenshot_path) else: self.screenshot(namePrefix=filename, defaultFilename=False) if filename is not None: print("Saving screenshot into", filename) else: print("Could not save filename") if self.gui is not None: self.gui.update_info("Could not save filename", 1.0, 1.0)
class World(DirectObject): def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def __init__(self): base.win.setClearColor(Vec4(0, 0, 0, 1)) # Network Setup print "before" self.cManager = ConnectionManager(self) self.startConnection() print "after" # Set up the environment # self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.environ.setScale(100, 100, 1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # add spheres earth = Earth(self) sun = Sun(self) venus = Venus(self) controls = Control() chat = Chat(self) player = Ralph(self) # player = Panda(self) # player = Car(self) taskMgr.add(player.move, "moveTask") taskMgr.add(sun.rotatePlanets, "rotateSun", extraArgs=[self.player], appendTask=True) taskMgr.add(earth.rotatePlanets, "rotateEarth", extraArgs=[self.player], appendTask=True) taskMgr.add(venus.rotatePlanets, "rotateVenus", extraArgs=[self.player], appendTask=True) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def create_node(self): self.geom = GeomBuilder().add_dome(self.color, (0, 0, 0), self.radius, self.samples, self.planes).get_geom_node() return NodePath(self.geom)
def random_matrix_generator(): while 1: a = NodePath("") a.setHpr(360 * random(), 0, 0) a.setPos(15 * random() - 7.5, 15 * random() - 7.5, 0) yield dragonfly.scene.matrix(a, "NodePath")
def create_node(self): return NodePath( GeomBuilder('block').add_block(self.color, (0, 0, 0), self.size).get_geom_node())
def create_node(self): return NodePath( GeomBuilder('ramp').add_block( self.color, (0, 0, 0), (self.thickness, self.width, self.length)).get_geom_node())
def __init__(self, cr): DistributedNode.__init__(self, cr) NodePath.__init__(self, 'droppableCollectableObject') self.collSensorNodePath = None self.collRayNodePath = None
def create_node(self): rel_base = Point3(self.base - (self.midpoint - Point3(0, 0, 0))) rel_top = Point3(self.top - (self.midpoint - Point3(0, 0, 0))) self.geom = GeomBuilder().add_wedge(self.color, rel_base, rel_top, self.width).get_geom_node() return NodePath(self.geom)
class PandaVis(ShowBase): """Base class for all visualizations with panda3d""" def __init__(self, rendering: bool): """ Constructor :param rendering: boolean indicating whether to use RenderPipeline or default Panda3d as visualization-module. """ super().__init__(self) self.dir = Filename.fromOsSpecific( pyrado.PANDA_ASSETS_DIR).getFullpath() # Initialize RenderPipeline if rendering: sys.path.insert(0, pyrado.RENDER_PIPELINE_DIR) from rpcore import RenderPipeline self.render_pipeline = RenderPipeline() self.render_pipeline.pre_showbase_init() self.render_pipeline.set_loading_screen_image( osp.join(self.dir, "logo.png")) self.render_pipeline.settings["pipeline.display_debugger"] = False self.render_pipeline.create(self) self.render_pipeline.daytime_mgr.time = "17:00" else: self.render_pipeline = None # Activate antialiasing self.render.setAntialias(AntialiasAttrib.MAuto) # Set window properties self.windowProperties = WindowProperties() self.windowProperties.setForeground(True) self.windowProperties.setTitle("Experiment") # Set background color self.setBackgroundColor(1, 1, 1) # Configuration of the lighting self.directionalLight1 = DirectionalLight("directionalLight") self.directionalLightNP1 = self.render.attachNewNode( self.directionalLight1) self.directionalLightNP1.setHpr(0, -8, 0) self.render.setLight(self.directionalLightNP1) self.directionalLight2 = DirectionalLight("directionalLight") self.directionalLightNP2 = self.render.attachNewNode( self.directionalLight2) self.directionalLightNP2.setHpr(180, -20, 0) self.render.setLight(self.directionalLightNP2) self.ambientLight = AmbientLight("ambientLight") self.ambientLightNP = self.render.attachNewNode(self.ambientLight) self.ambientLight.setColor((0.1, 0.1, 0.1, 1)) self.render.setLight(self.ambientLightNP) # Create a text node displaying the physic parameters on the top left of the screen self.text = TextNode("parameters") self.textNodePath = aspect2d.attachNewNode(self.text) self.text.setTextColor(0, 0, 0, 1) # black self.textNodePath.setScale(0.07) self.textNodePath.setPos(-1.9, 0, 0.9) # Configure trace self.trace = LineSegs() self.trace.setThickness(3) self.trace.setColor(0.8, 0.8, 0.8) # light grey self.lines = self.render.attachNewNode("Lines") self.last_pos = None # Adds one instance of the update function to the task-manager, thus initializes the animation self.taskMgr.add(self.update, "update") def update(self, task: Task): """ Updates the visualization with every call. :param task: Needed by panda3d task manager. :return Task.cont: indicates that task should be called again next frame. """ return Task.cont def reset(self): """ Resets the the visualization to a certain state, so that in can be run again. Removes the trace. """ self.lines.getChildren().detach() self.last_pos = None def draw_trace(self, point): """ Draws a line from the last point to the current point :param point: Current position of pen. Needs 3 value vector. """ # Check if trace initialized if self.last_pos: # Set starting point of new line self.trace.moveTo(self.last_pos) # Draw line to that point self.trace.drawTo(point) # Save last position of pen self.last_pos = point # Show drawing self.trace_np = NodePath(self.trace.create()) self.trace_np.reparentTo(self.lines)
def __init__(self, water_options): self.options = water_options self.options.size = 512 self.options.wind_dir.normalize() self.options.wave_amplitude *= 1e-7 self.displacement_tex = Texture("Displacement") self.displacement_tex.setup_2d_texture( self.options.size, self.options.size, Texture.TFloat, Texture.FRgba16) self.normal_tex = Texture("Normal") self.normal_tex.setup_2d_texture( self.options.size, self.options.size, Texture.TFloat, Texture.FRgba16) self.combine_shader = Shader.load_compute(Shader.SLGLSL, "/$$rp/rpcore/water/shader/combine.compute") self.pta_time = PTAFloat.emptyArray(1) # Create a gaussian random texture, as shaders aren't well suited # for that setRandomSeed(523) self.random_storage = PNMImage(self.options.size, self.options.size, 4) self.random_storage.setMaxval((2 ** 16) - 1) for x in range(self.options.size): for y in range(self.options.size): rand1 = self._get_gaussian_random() / 10.0 + 0.5 rand2 = self._get_gaussian_random() / 10.0 + 0.5 self.random_storage.setXel(x, y, float(rand1), float(rand2), 0) self.random_storage.setAlpha(x, y, 1.0) self.random_storage_tex = Texture("RandomStorage") self.random_storage_tex.load(self.random_storage) self.random_storage_tex.set_format(Texture.FRgba16) self.random_storage_tex.set_minfilter(Texture.FTNearest) self.random_storage_tex.set_magfilter(Texture.FTNearest) # Create the texture wwhere the intial height (H0 + Omega0) is stored. self.tex_initial_height = Texture("InitialHeight") self.tex_initial_height.setup_2d_texture( self.options.size, self.options.size, Texture.TFloat, Texture.FRgba16) self.tex_initial_height.set_minfilter(Texture.FTNearest) self.tex_initial_height.set_magfilter(Texture.FTNearest) # Create the shader which populates the initial height texture self.shader_initial_height = Shader.load_compute(Shader.SLGLSL, "/$$rp/rpcore/water/shader/initial_height.compute") self.node_initial_height = NodePath("initialHeight") self.node_initial_height.set_shader(self.shader_initial_height) self.node_initial_height.set_shader_input("dest", self.tex_initial_height) self.node_initial_height.set_shader_input( "N", LVecBase2i(self.options.size)) self.node_initial_height.set_shader_input( "patchLength", self.options.patch_length) self.node_initial_height.set_shader_input("windDir", self.options.wind_dir) self.node_initial_height.set_shader_input( "windSpeed", self.options.wind_speed) self.node_initial_height.set_shader_input( "waveAmplitude", self.options.wave_amplitude) self.node_initial_height.set_shader_input( "windDependency", self.options.wind_dependency) self.node_initial_height.set_shader_input( "randomTex", self.random_storage_tex) self.attr_initial_height = self.node_initial_height.get_attrib(ShaderAttrib) self.height_textures = [] for i in range(3): tex = Texture("Height") tex.setup_2d_texture(self.options.size, self.options.size, Texture.TFloat, Texture.FRgba16) tex.set_minfilter(Texture.FTNearest) tex.set_magfilter(Texture.FTNearest) tex.set_wrap_u(Texture.WMClamp) tex.set_wrap_v(Texture.WMClamp) self.height_textures.append(tex) # Also create the shader which updates the spectrum self.shader_update = Shader.load_compute(Shader.SLGLSL, "/$$rp/rpcore/water/shader/update.compute") self.node_update = NodePath("update") self.node_update.set_shader(self.shader_update) self.node_update.set_shader_input("outH0x", self.height_textures[0]) self.node_update.set_shader_input("outH0y", self.height_textures[1]) self.node_update.set_shader_input("outH0z", self.height_textures[2]) self.node_update.set_shader_input("initialHeight", self.tex_initial_height) self.node_update.set_shader_input("N", LVecBase2i(self.options.size)) self.node_update.set_shader_input("time", self.pta_time) self.attr_update = self.node_update.get_attrib(ShaderAttrib) # Create 3 FFTs self.fftX = GPUFFT(self.options.size, self.height_textures[0], self.options.normalization_factor) self.fftY = GPUFFT(self.options.size, self.height_textures[1], self.options.normalization_factor) self.fftZ = GPUFFT(self.options.size, self.height_textures[2], self.options.normalization_factor) self.combine_node = NodePath("Combine") self.combine_node.set_shader(self.combine_shader) self.combine_node.set_shader_input( "displacementX", self.fftX.get_result_texture()) self.combine_node.set_shader_input( "displacementY", self.fftY.get_result_texture()) self.combine_node.set_shader_input( "displacementZ", self.fftZ.get_result_texture()) self.combine_node.set_shader_input("normalDest", self.normal_tex) self.combine_node.set_shader_input( "displacementDest", self.displacement_tex) self.combine_node.set_shader_input( "N", LVecBase2i(self.options.size)) self.combine_node.set_shader_input( "choppyScale", self.options.choppy_scale) self.combine_node.set_shader_input( "gridLength", self.options.patch_length) # Store only the shader attrib as this is way faster self.attr_combine = self.combine_node.get_attrib(ShaderAttrib)
class StaticGeometricModel(object): """ load an object as a static geometric model -> changing pos, rot, color, etc. are not allowed there is no extra elements for this model, thus is much faster author: weiwei date: 20190312 """ def __init__(self, initor=None, name="defaultname", btransparency=True, btwosided=False): """ :param initor: path type defined by os.path or trimesh or nodepath :param btransparency :param name """ if isinstance(initor, StaticGeometricModel): self._objpath = copy.deepcopy(initor.objpath) self._objtrm = copy.deepcopy(initor.objtrm) self._objpdnp = copy.deepcopy(initor.objpdnp) self._name = copy.deepcopy(initor.name) self._localframe = copy.deepcopy(initor.localframe) else: # make a grandma nodepath to separate decorations (-autoshader) and raw nodepath (+autoshader) self._name = name self._objpdnp = NodePath(name) if isinstance(initor, str): self._objpath = initor self._objtrm = da.trm.load(self._objpath) objpdnp_raw = da.trimesh_to_nodepath(self._objtrm, name='pdnp_raw') objpdnp_raw.reparentTo(self._objpdnp) elif isinstance(initor, da.trm.Trimesh): self._objpath = None self._objtrm = initor objpdnp_raw = da.trimesh_to_nodepath(self._objtrm) objpdnp_raw.reparentTo(self._objpdnp) elif isinstance(initor, o3d.geometry.PointCloud ): # TODO should pointcloud be pdnp or pdnp_raw self._objpath = None self._objtrm = da.trm.Trimesh(np.asarray(initor.points)) objpdnp_raw = da.nodepath_from_points(self._objtrm.vertices, name='pdnp_raw') objpdnp_raw.reparentTo(self._objpdnp) elif isinstance( initor, np.ndarray): # TODO should pointcloud be pdnp or pdnp_raw self._objpath = None if initor.shape[1] == 3: self._objtrm = da.trm.Trimesh(initor) objpdnp_raw = da.nodepath_from_points( self._objtrm.vertices) elif initor.shape[1] == 7: self._objtrm = da.trm.Trimesh(initor[:, :3]) objpdnp_raw = da.nodepath_from_points( self._objtrm.vertices, initor[:, 3:].tolist()) objpdnp_raw.setRenderMode(RenderModeAttrib.MPoint, 3) else: # TODO depth UV? raise NotImplementedError objpdnp_raw.reparentTo(self._objpdnp) elif isinstance(initor, o3d.geometry.TriangleMesh): self._objpath = None self._objtrm = da.trm.Trimesh( vertices=initor.vertices, faces=initor.triangles, face_normals=initor.triangle_normals) objpdnp_raw = da.trimesh_to_nodepath(self._objtrm, name='pdnp_raw') objpdnp_raw.reparentTo(self._objpdnp) elif isinstance(initor, NodePath): self._objpath = None self._objtrm = None # TODO nodepath to trimesh? objpdnp_raw = initor objpdnp_raw.reparentTo(self._objpdnp) else: self._objpath = None self._objtrm = None objpdnp_raw = NodePath("pdnp_raw") objpdnp_raw.reparentTo(self._objpdnp) if btransparency: self._objpdnp.setTransparency(TransparencyAttrib.MDual) if btwosided: self._objpdnp.getChild(0).setTwoSided(True) self._localframe = None @property def name(self): # read-only property return self._name @property def objpath(self): # read-only property return self._objpath @property def objpdnp(self): # read-only property return self._objpdnp @property def objpdnp_raw(self): # read-only property return self._objpdnp.getChild(0) @property def objtrm(self): # read-only property # 20210328 comment out, allow None # if self._objtrm is None: # raise ValueError("Only applicable to models with a trimesh!") return self._objtrm @property def localframe(self): # read-only property return self._localframe @property def volume(self): # read-only property if self._objtrm is None: raise ValueError("Only applicable to models with a trimesh!") return self._objtrm.volume def set_rgba(self, rgba): self._objpdnp.setColor(rgba[0], rgba[1], rgba[2], rgba[3]) def set_scale(self, scale=[1, 1, 1]): self._objpdnp.setScale(scale[0], scale[1], scale[2]) self._objtrm.apply_scale(scale) def set_vert_size(self, size=.005): self.objpdnp_raw.setRenderModeThickness(size * 1000) def get_rgba(self): return da.pdv4_to_npv4( self._objpdnp.getColor()) # panda3d.core.LColor -> LBase4F def clear_rgba(self): self._objpdnp.clearColor() def get_scale(self): return da.pdv3_to_npv3(self._objpdnp.getScale()) def attach_to(self, obj): if isinstance(obj, ShowBase): # for rendering to base.render self._objpdnp.reparentTo(obj.render) elif isinstance(obj, StaticGeometricModel ): # prepared for decorations like local frames self._objpdnp.reparentTo(obj.objpdnp) elif isinstance(obj, mc.ModelCollection): obj.add_gm(self) else: print( "Must be ShowBase, modeling.StaticGeometricModel, GeometricModel, CollisionModel, or CollisionModelCollection!" ) def detach(self): self._objpdnp.detachNode() def remove(self): self._objpdnp.removeNode() def show_localframe(self): self._localframe = gen_frame() self._localframe.attach_to(self) def unshow_localframe(self): if self._localframe is not None: self._localframe.remove() self._localframe = None def copy(self): return copy.deepcopy(self)
def __init__(self, initor=None, name="defaultname", btransparency=True, btwosided=False): """ :param initor: path type defined by os.path or trimesh or nodepath :param btransparency :param name """ if isinstance(initor, StaticGeometricModel): self._objpath = copy.deepcopy(initor.objpath) self._objtrm = copy.deepcopy(initor.objtrm) self._objpdnp = copy.deepcopy(initor.objpdnp) self._name = copy.deepcopy(initor.name) self._localframe = copy.deepcopy(initor.localframe) else: # make a grandma nodepath to separate decorations (-autoshader) and raw nodepath (+autoshader) self._name = name self._objpdnp = NodePath(name) if isinstance(initor, str): self._objpath = initor self._objtrm = da.trm.load(self._objpath) objpdnp_raw = da.trimesh_to_nodepath(self._objtrm, name='pdnp_raw') objpdnp_raw.reparentTo(self._objpdnp) elif isinstance(initor, da.trm.Trimesh): self._objpath = None self._objtrm = initor objpdnp_raw = da.trimesh_to_nodepath(self._objtrm) objpdnp_raw.reparentTo(self._objpdnp) elif isinstance(initor, o3d.geometry.PointCloud ): # TODO should pointcloud be pdnp or pdnp_raw self._objpath = None self._objtrm = da.trm.Trimesh(np.asarray(initor.points)) objpdnp_raw = da.nodepath_from_points(self._objtrm.vertices, name='pdnp_raw') objpdnp_raw.reparentTo(self._objpdnp) elif isinstance( initor, np.ndarray): # TODO should pointcloud be pdnp or pdnp_raw self._objpath = None if initor.shape[1] == 3: self._objtrm = da.trm.Trimesh(initor) objpdnp_raw = da.nodepath_from_points( self._objtrm.vertices) elif initor.shape[1] == 7: self._objtrm = da.trm.Trimesh(initor[:, :3]) objpdnp_raw = da.nodepath_from_points( self._objtrm.vertices, initor[:, 3:].tolist()) objpdnp_raw.setRenderMode(RenderModeAttrib.MPoint, 3) else: # TODO depth UV? raise NotImplementedError objpdnp_raw.reparentTo(self._objpdnp) elif isinstance(initor, o3d.geometry.TriangleMesh): self._objpath = None self._objtrm = da.trm.Trimesh( vertices=initor.vertices, faces=initor.triangles, face_normals=initor.triangle_normals) objpdnp_raw = da.trimesh_to_nodepath(self._objtrm, name='pdnp_raw') objpdnp_raw.reparentTo(self._objpdnp) elif isinstance(initor, NodePath): self._objpath = None self._objtrm = None # TODO nodepath to trimesh? objpdnp_raw = initor objpdnp_raw.reparentTo(self._objpdnp) else: self._objpath = None self._objtrm = None objpdnp_raw = NodePath("pdnp_raw") objpdnp_raw.reparentTo(self._objpdnp) if btransparency: self._objpdnp.setTransparency(TransparencyAttrib.MDual) if btwosided: self._objpdnp.getChild(0).setTwoSided(True) self._localframe = None
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(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, (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
class CogdoFlyingLevelQuadrant: notify = directNotify.newCategory('CogdoFlyingLevelQuadrant') def __init__(self, serialNum, model, level, parent): self.serialNum = serialNum self._model = model self._level = level self._root = NodePath('Quadrant' + ` serialNum `) self._model.reparentTo(self._root) self._root.reparentTo(parent) self._visible = True self.platforms = {} self.gatherables = [] self.obstacles = [] self._playing = False self._obstaclesRoot = NodePath('obstacles') self._obstaclesRoot.reparentTo(self._root) self._initObstacles(self._obstaclesRoot) self._gatherablesRoot = NodePath('gatherables') self._gatherablesRoot.reparentTo(self._root) self._initGatherables(self._gatherablesRoot) self._platformsRoot = NodePath('platforms') self._platformsRoot.reparentTo(self._model) self._initPlatforms(self._platformsRoot) self._optimize() self.place() def _optimize(self): lightCones = NodePath('lightCones') for np in self._platformsRoot.findAllMatches('**/*lightCone*'): np.wrtReparentTo(lightCones) lightCones.reparentTo(self._model) node = self._model.find('**/ducts') if not node.isEmpty(): node.flattenStrong() for np in node.getChildren(): np.wrtReparentTo(self._model) node = self._model.find('**/nests') if not node.isEmpty(): for np in node.getChildren(): np.flattenStrong() np.wrtReparentTo(self._model) for np in self._model.findAllMatches('**/*LayerStack*'): np.wrtReparentTo(self._model) if not self._model.find('**/static').isEmpty(): for np in self._model.find('**/static').getChildren(): np.wrtReparentTo(self._model) self._model.flattenMedium() def _initPlatforms(self, parent): platformModels = self._model.findAllMatches('**/%s' % Globals.Level.PlatformName) for platformModel in platformModels: platform = CogdoFlyingPlatform(platformModel, parent=parent) self.platforms[platform.getName()] = platform def _destroyPlatforms(self): for platform in self.platforms.values(): platform.destroy() del self.platforms def _initGatherables(self, parent): self.generateGatherables(self._model, parent=parent) if Globals.Level.SpawnLaffPowerupsInNests: self.generateNestPowerups(self._model, parent=parent) def generateNestPowerups(self, gatherableModel, parent): nests = gatherableModel.findAllMatches( '**/%s;+s' % Globals.Level.LegalEagleNestName) for nest in nests: offset = Globals.Level.LaffPowerupNestOffset pickup = self._level.gatherableFactory.createPowerup( Globals.Level.GatherableTypes.LaffPowerup) pickup.reparentTo(parent) pickup.setPos(parent, nest.getPos(parent) + offset) if Globals.Level.AddSparkleToPowerups: sparkles = self._level.gatherableFactory.createSparkles( Vec4(1, 1, 1, 1), Vec4(1, 1, 0, 1), 10.0) sparkles.reparentTo(pickup) sparkles.setPos(0, 0, 1) sparkles.start() self.gatherables.append(pickup) def generateGatherables(self, gatherableModel, parent=None, spread=Globals.Level.GatherablesDefaultSpread): parent = parent or self._root mopath = Mopath.Mopath(name='gatherables') def generateMemos(): gatherPaths = gatherableModel.findAllMatches( '**/%s' % Globals.Level.GatherablesPathName) for gatherPath in gatherPaths: mopath.loadNodePath(gatherPath) t = 0.0 while t < mopath.getMaxT(): pickup = self._level.gatherableFactory.createMemo() pickup.reparentTo(parent) mopath.goTo(pickup, t) self.gatherables.append(pickup) t += spread gatherPath.removeNode() angleSpread = 360.0 / Globals.Level.NumMemosInRing gatherPaths = gatherableModel.findAllMatches( '**/%s' % Globals.Level.GatherablesRingName) for gatherPath in gatherPaths: mopath.loadNodePath(gatherPath) t = 0.0 while t < mopath.getMaxT(): angle = 0 r = 3 while angle < 360.0: pickup = self._level.gatherableFactory.createMemo() pickup.reparentTo(parent) mopath.goTo(pickup, t) pickup.setX( parent, pickup.getX() + r * math.cos(math.radians(angle))) pickup.setZ( parent, pickup.getZ() + r * math.sin(math.radians(angle))) self.gatherables.append(pickup) angle += angleSpread t += spread + 0.5 gatherPath.removeNode() def generatePropellers(): gatherables = gatherableModel.findAllMatches( '**/%s' % Globals.Level.PropellerName) for gatherable in gatherables: pickup = self._level.gatherableFactory.createPropeller() pickup.reparentTo(gatherable.getParent()) pickup.setPos(parent, gatherable.getPos(parent)) self.gatherables.append(pickup) gatherable.removeNode() def generatePowerUps(): for powerupType, locName in Globals.Level.PowerupType2Loc.iteritems( ): if powerupType == Globals.Level.GatherableTypes.LaffPowerup and Globals.Level.IgnoreLaffPowerups: continue gatherables = gatherableModel.findAllMatches('**/%s' % locName) for gatherable in gatherables: pickup = self._level.gatherableFactory.createPowerup( powerupType) pickup.reparentTo(parent) pickup.setPos(parent, gatherable.getPos(parent)) if Globals.Level.AddSparkleToPowerups: sparkles = self._level.gatherableFactory.createSparkles( Vec4(1, 1, 1, 1), Vec4(1, 1, 0, 1), 10.0) sparkles.reparentTo(pickup) sparkles.setPos(0, 0, 1) sparkles.start() self.gatherables.append(pickup) gatherable.removeNode() generateMemos() generatePropellers() generatePowerUps() def _initObstacles(self, parent): def initWhirlwinds(): obstacles = self._root.findAllMatches('**/%s' % Globals.Level.WhirlwindName) for obstacleLoc in obstacles: motionPath = self._model.find( '**/%s%s' % (obstacleLoc.getName(), Globals.Level.WhirlwindPathName)) if motionPath.isEmpty(): motionPath = None obstacle = self._level.obstacleFactory.createWhirlwind( motionPath=motionPath) obstacle.model.reparentTo(parent) obstacle.model.setPos(parent, obstacleLoc.getPos(parent)) self.obstacles.append(obstacle) obstacleLoc.removeNode() return def initStreamers(): obstacles = self._model.findAllMatches('**/%s' % Globals.Level.StreamerName) for obstacleLoc in obstacles: obstacle = self._level.obstacleFactory.createFan() obstacle.model.reparentTo(parent) obstacle.model.setPos(parent, obstacleLoc.getPos(parent)) obstacle.model.setHpr(parent, obstacleLoc.getHpr(parent)) obstacle.model.setScale(parent, obstacleLoc.getScale(parent)) obstacle.setBlowDirection() if Globals.Level.AddParticlesToStreamers: particles = self._level.obstacleFactory.createStreamerParticles( Vec4(1, 1, 1, 1), Vec4(1, 1, 1, 1), 10.0) particles.reparentTo(obstacle.model) particles.start() self.obstacles.append(obstacle) obstacleLoc.removeNode() def initWalkingMinions(): motionPaths = self._model.findAllMatches( '**/%s' % Globals.Level.MinionWalkingPathName) for motionPath in motionPaths: obstacle = self._level.obstacleFactory.createWalkingMinion( motionPath=motionPath) obstacle.model.reparentTo(parent) obstacle.model.setPos(parent, motionPath.getPos(parent)) self.obstacles.append(obstacle) def initFlyingMinions(): motionPaths = self._model.findAllMatches( '**/%s' % Globals.Level.MinionFlyingPathName) for motionPath in motionPaths: obstacle = self._level.obstacleFactory.createFlyingMinion( motionPath=motionPath) obstacle.model.reparentTo(parent) obstacle.model.setPos(parent, motionPath.getPos(parent)) self.obstacles.append(obstacle) initWhirlwinds() initStreamers() initWalkingMinions() initFlyingMinions() def place(self): self._root.setPos(0, self._level.convertQuadNumToY(self.serialNum), 0) def destroy(self): if self._visible: self.offstage() self._destroyPlatforms() for obstacle in self.obstacles: obstacle.destroy() for gatherable in self.gatherables: gatherable.destroy() self._root.removeNode() del self._root del self._gatherablesRoot del self._obstaclesRoot del self._platformsRoot del self._level def onstage(self, elapsedTime=0.0): if self._visible: return self._root.unstash() for obstacle in self.obstacles: obstacle.startMoving(elapsedTime) for gatherable in self.gatherables: gatherable.show() self._visible = True def offstage(self): if not self._visible: return self._root.stash() for obstacle in self.obstacles: obstacle.stopMoving() for gatherable in self.gatherables: gatherable.hide() self._visible = False def update(self, dt): if self._visible: for gatherable in self.gatherables: gatherable.update(dt) for obstacle in self.obstacles: obstacle.update(dt) def getModel(self): return self._root