def setResolution(x=800, y=600, fullScreen=False): wp = WindowProperties() wp.setSize(x, y) wp.setFullscreen(fullScreen) base.win.requestProperties(wp)
def getScreenRatio(): props = WindowProperties(base.win.getProperties()) return float(props.getXSize()) / float(props.getYSize())
def disableMouse(): base.disableMouse() props = WindowProperties() props.setCursorHidden(True) base.win.requestProperties(props)
def _setresolution(res, fullscreen=False): wp = WindowProperties() wp.setSize(int(res[0]), int(res[1])) wp.setFullscreen(fullscreen) base.win.requestProperties(wp)
def __init__(self): ShowBase.__init__(self) winProps = WindowProperties() winProps.setTitle("Triangle and SimpleCircle Unittest") # base.win.requestProperties(winProps) (same as below e.g. self == base) self.win.requestProperties(winProps) zUp = Vec3(0.0, 0.0, 1.0) wt = Vec4(1.0, 1.0, 1.0, 1.0) def addToVertex(x, y, z): normal.addData3f(zUp) color.addData4f(wt) # BLOG post about these bullet points then delete them # 1) create GeomVertexData (inside the triangulator's constructor) frmt = GeomVertexFormat.getV3n3cp() triangulator = ConstrainedDelaunayTriangulator(vertexFormat = frmt, onVertexCreationCallback = addToVertex) vdata = triangulator.getGeomVertexData() # 2) create Writers/Rewriters (must all be created before any readers and readers are one-pass-temporary) normal = GeomVertexRewriter(vdata, 'normal') # DOC 'vertex' is the only prohibited column for the user to use color = GeomVertexRewriter(vdata, 'color') # 3) write each column on the vertex data object (for speed, have a different writer for each column) # DOC 1.DT) create triangulator # DOC 2.DT) add vertices (before calling triangulate) # ############# NOT ANGLE OPTIMAL BELOW ##################### # triangulator.addVertexToPolygon(5.0, 0.0, 0.0) # triangulator.addVertexToPolygon(0.0, 0.0, 0.0) # triangulator.addVertexToPolygon(1.5, 2.5, 0.0) # triangulator.addVertexToPolygon(0.0, 5.0, 0.0) # triangulator.addVertexToPolygon(5.0, 5.0, 0.0) # ############# NOT ANGLE OPTIMAL ABOVE ##################### triangulator.addVertexToPolygon(5.0, 0.0, 0.0) triangulator.addVertexToPolygon(6.5, 6.5, 0.0) # triangulator.addVertexToPolygon(1.5, 2.5, 0.0) triangulator.addVertexToPolygon(0.0, 0.0, 0.0) triangulator.addVertexToPolygon(0.0, 5.0, 0.0) triangulator.addVertexToPolygon(5.0, 5.0, 0.0) # DOC 3.DT) add hole vertices (before calling triangulate) # DOC 4.DT) call triangulate triangulator.triangulate(makeDelaunay=True) # ######################## REMOVE ################################### # ######################## REMOVE ################################### assert triangulator.isTriangulated() adjLst = triangulator.getAdjacencyList() foundInvalidReference = [] foundMissingReference = [] # so I can explicitly state all index references are correct for t in adjLst: # check that references with no neighbor haven't missed an edge noneEdges = [] if t._neighbor0 is None: noneEdges.append(t.edgeIndices0) elif t._neighbor1 is None: noneEdges.append(t.edgeIndices1) elif t._neighbor2 is None: noneEdges.append(t.edgeIndices2) for tri_ in adjLst: for edge_ in noneEdges: # the edge that should hold the reference is on t. The one that should get referenced is on tri_ missedCount = 0 if edge_[0] in tri_.edgeIndices0 and edge_[1] in tri_.edgeIndices0 and tri_ != t: missedCount += 1 if edge_[0] in tri_.edgeIndices1 and edge_[1] in tri_.edgeIndices1 and tri_ != t: missedCount += 1 if edge_[0] in tri_.edgeIndices2 and edge_[1] in tri_.edgeIndices2 and tri_ != t: missedCount += 1 if missedCount == 1: foundMissingReference.extend((t, tri_)) notify.warning( "!MISSED REFERENCE TO NEIGHBOR\nreferrer: {} ptIndices: {} neighbors: {}\n".format( t.index, t.getPointIndices(), t.getNeighbors(), ) + "missed: {} ptIndices: {} neighbors: {}".format( tri_.index, tri_.getPointIndices(), tri_.getNeighbors(), )) elif missedCount > 1: foundMissingReference.extend((t, tri_)) notify.warning( "!EXTRANEOUS & MISSED SHARED EDGES\nreferrer: {} ptIndices: {} neighbors: {}\n".format( t.index, t.getPointIndices(), t.getNeighbors(), ) + "missed: {} ptIndices: {} neighbors: {}".format( tri_.index, tri_.getPointIndices(), tri_.getNeighbors(), )) # check that neighbor relations point to correct triangles for n in t.getNeighbors(includeEmpties=False): neighbor = adjLst[n] otherInds = neighbor.getPointIndices() if neighbor.index == t._neighbor0: edge = t.edgeIndices0 elif neighbor.index == t._neighbor1: edge = t.edgeIndices1 elif neighbor.index == t._neighbor2: edge = t.edgeIndices2 if edge[0] not in otherInds and edge[1] not in otherInds: foundInvalidReference.extend((t, neighbor)) notify.warning( "!INVALID REFERENCE TO NEIGHBOR\nreferrer: {} indices: {} neighbors: {}".format( t.index, t.getPointIndices(), t.getNeighbors(), ) + "\nreferee: {} indices: {} neighbors: {}".format( neighbor.index, neighbor.getPointIndices(), neighbor.getNeighbors() )) if not foundMissingReference: notify.warning("No error missing reference in neighbors.") else: notify.warning("!!!ERROR missing reference in neighbor references.") if not foundInvalidReference: notify.warning("No error found in neighbors that were referenced.") else: notify.warning("!!!ERROR found in neighbors that were referenced.") foundPointInsideCircle = False trianglesWithInvalidPoint = set() for t in adjLst: circle_ = t.getCircumcircle() # cycle through triangles checking each point against each circle.center for e in adjLst: p0, p1, p2 = e.getPoints() if circle_.radius - (p0 - circle_.center).length() > EPSILON: foundPointInsideCircle = True notify.warning( "!point in circumcircle point {0} circle {1}\ntriangle1: {2}\ntriangle2: {3}".format( p0, circle_, t, e )) trianglesWithInvalidPoint |= set((t.index, )) if circle_.radius - (p1 - circle_.center).length() > EPSILON: foundPointInsideCircle = True notify.warning( "!point in circumcircle point {0} circle {1}\ntriangle1: {2}\ntriangle2: {3}".format( p1, circle_, t, e )) trianglesWithInvalidPoint |= set((t.index, )) if circle_.radius - (p2 - circle_.center).length() > EPSILON: foundPointInsideCircle = True notify.warning( "!point in circumcircle point {0} circle {1}\ntriangle1: {2}\ntriangle2: {3}".format( p2, circle_, t, e )) trianglesWithInvalidPoint |= set((t.index, )) if not foundPointInsideCircle: notify.warning("No point found inside circumcircle.") else: notify.warning("!!!ERROR found point inside circumcircle. Triangles: {}".format(trianglesWithInvalidPoint)) # TODO test edges that reference no neighbor # triangles = triangulator.getGeomTriangles() # print "Triangulated:" # for tri in triangleList: # print "\t{0}".format(tri) # 4) create a primitive and add the vertices via index (not truly associated with the actual vertex table, yet) # tris = GeomTriangles(Geom.UHDynamic) # t1 = Triangle(0, 1, 2, vdata, tris, vertex) # t2 = Triangle(2, 1, 3, vdata, tris, vertex) # c1 = t1.getCircumcircle() # t1AsEnum = t1.asPointsEnum() # r0 = (t1AsEnum.point0 - c1.center).length() # r1 = (t1AsEnum.point1 - c1.center).length() # r2 = (t1AsEnum.point2 - c1.center).length() # assert abs(r0 - r2) < utilities.EPSILON and abs(r0 - r1) < utilities.EPSILON # t2AsEnum = t2.asPointsEnum() # c2 = t2.getCircumcircle() # r0 = (t2AsEnum.point0 - c2.center).length() # r1 = (t2AsEnum.point1 - c2.center).length() # r2 = (t2AsEnum.point2 - c2.center).length() # assert abs(r0 - r2) < utilities.EPSILON and abs(r0 - r1) < utilities.EPSILON # assert t1.getAngleDeg0() == 90.0 # assert t1.getAngleDeg1() == t1.getAngleDeg2() # # oldInd0 = t1.pointIndex0 # oldInd1 = t1.pointIndex1 # oldInd2 = t1.pointIndex2 # t1.pointIndex0 = t1.pointIndex1 # t1.pointIndex1 = oldInd0 # assert t1.pointIndex0 == oldInd1 # assert t1.pointIndex1 == oldInd0 # assert t1.pointIndex0 != t1.pointIndex1 # t1.reverse() # assert t1.pointIndex1 == oldInd2 # gn = triangulator.getGeomNode('triangles') gnNodePath = render.attachNewNode(gn) # setup a wire frame wireNP = render.attachNewNode('wire') wireNP.setPos(0.0, 0.0, .1) wireNP.setColor(0.1, 0.1, 0.1, 1) wireNP.setRenderMode(RenderModeAttrib.MWireframe, .5, 0) gnNodePath.instanceTo(wireNP) # # # test and draw intersections and circles # pt1 = Point3(0.0, 5.0, 0.0) # pt2 = Point3(1.0, 5.0, 0.0) # intersection = t2.getIntersectionsWithCircumcircle(pt1, pt2) # circle = t2.getCircumcircle() # cuts = 128 # border = circle.getBorder(cuts, closed=True) # assert len(border) == cuts or (len(border) == cuts + 1 and border[0] == border[len(border) - 1]) # n = len(border) # xMid = yMid = 0 # for p in border: # xMid += p.x # yMid += p.y # mid = Point3(xMid / n, yMid / n, border[0].z) # assert mid.almostEqual(circle.center, 0.06) # assert t2.isLeftWinding() # assert t1.containsPoint(c1.center) != t1.containsPoint(c1.center, includeEdges=False) # # circleSegs = LineSegs("circleLines") # circleSegs.setColor(1.0, 0.0, 0.0, 1.0) # for p in border: # circleSegs.drawTo(*p) # circleNode = circleSegs.create(False) # circleNP = render.attachNewNode(circleNode) # circleNP.setZ(-5) # # originSpot = LineSegs("intersection") # originSpot.setColor(1.0, 0.0, 0.0, 1.0) # originSpot.setThickness(10) # for p in intersection: # originSpot.drawTo(p) # spotNode = originSpot.create(False) # spotNP = render.attachNewNode(spotNode) # circleNP.setZ(-0.75) # fix the camera rot/pos PHF.PanditorDisableMouseFunc() camera.setPos(0.0, 0.0, 50.0) camera.lookAt(Point3(0.0)) # 2.5, 2.5, 0.0)) PHF.PanditorEnableMouseFunc() # print "isLeftWinding()", triangulator.isLeftWinding() # TODO port the triangle-indices node func drawTriangleIndices(...) indsNp = ConstrainedDelaunayTriangulator.drawTriangleIndices(triangulator.getTriangleList()) indsNp.setPos(0.0, 0.0, 0.3)
def __init__(self, shown, t0, initTime, leafDroop, lankiness, plant_health): loadPrcFileData('', 'win-size 1024 768') loadPrcFileData("", "window-type none") ShowBase.__init__(self) if shown: self.openMainWindow(type = "onscreen") props = WindowProperties() props.setTitle('TerraBot Simulator') self.win.requestProperties(props) else: self.openMainWindow(type = "offscreen") base.disableMouse() # Allow manual positioning of the camera #camera.setPosHpr(-20, 0, -3, -90, 12, 0) # Under camera.setPosHpr(-20, 0, 7, -90, -12, 0) # Normal #camera.setPosHpr(0, 0, 30, 0, -90, 0) #TOP self.pic = False self.loc = None self.shown = shown self.start_time = t0; atexit.register(self.userExit) self.BASE_TEXT = ''' Pump: OFF Fans: OFF LEDs: 255 ''' self.BASE_TEXT2 = \ ''' Time : {:s} Light level: 0 Temperature : 20 C Soil moisture : 0 Humidity : 50% Volume : 3000 ml Speedup : 1x '''.format(clock_time(t0 + initTime)) self.lastTime = initTime self.droop = leafDroop self.lankiness = lankiness self.plant_health = plant_health #self.accept('escape', self.userExit) self.accept('r', self.resetCam) self.loadModels() self.setupLights() self.setupText() self.setupText2() self.setupSensorCam() self.setTankWater(0) self.setBackgroundColor(.8, .8, .8, 1) self.keys = {} for key in ['arrow_left', 'arrow_right', 'arrow_up', 'arrow_down', 'a', 'd', 'w', 's']: self.keys[key] = 0 self.accept(key, self.push_key, [key, 1]) self.accept('shift-%s' % key, self.push_key, [key, 1]) self.accept('%s-up' % key, self.push_key, [key, 0]) self.fanonSound = loader.loadSfx('sounds/fanon.wav') self.pumponSound = loader.loadSfx('sounds/pumpon.wav') self.fanonSound.setLoop(True) self.pumponSound.setLoop(True) #SetupCamera self.heading = -90.0 self.pitch = -12.0 self.camera.setPos(-20, 0, 7) self.picNextFrame = False self.taskMgr.add(self.update, 'main loop')
error_output( 'illegal form for the background color in the configuration.', prefix='Runner') sys.exit(0) base.setBackgroundColor(_background_color) # Check if we have any screen resolution in our configuration file, if not we use default. (sx, sy) = DEFAULT_RESOLUTION.split('x') if 'screen_resolution' in browser_config.getConfigKeys(): resValue = browser_config.getValue('screen_resolution') (sx, sy) = (int(resValue.split('x')[0]), int(resValue.split('x')[1])) # ## Set the screen resolution. wp = WindowProperties() # Check if we have any fullscreen mode in the configuration. _fullscreen = DEFAULT_FULLSCREEN if 'fullscreen' in browser_config.getConfigKeys(): _fullscreen = bool(int(browser_config['fullscreen'])) wp.setFullscreen(_fullscreen) wp.setSize(int(sx), int(sy)) base.win.requestProperties(wp) # Disable panda3d mouse handler. base.disableMouse() # Initialize the browser in cubemode. photocube.modes.cubeMode.enable()
def __init__(self, scene_file, pedestrian_file, dir, mode): ShowBase.__init__(self) self.globalClock = ClockObject.getGlobalClock() self.globalClock.setMode(ClockObject.MSlave) self.directory = dir self.model = Model(dir) self.loadScene(scene_file) self.loadPedestrians(pedestrian_file) #self.cam_label = OST("Top Down", pos=(0, 0.95), fg=(1,1,1,1), # scale=0.05, mayChange=True) #self.time_label = OST("Time: 0.0", pos=(-1.3, 0.95), fg=(1,1,1,1), # scale=0.06, mayChange=True, align=TextNode.ALeft) #self.accept("arrow_right", self.changeCamera, [1]) #self.accept("arrow_left", self.changeCamera, [-1]) self.accept("escape", self.exit) self.accept("aspectRatioChanged", self.setAspectRatio) self.accept("window-event", self.windowChanged) new_window_fbp = FrameBufferProperties.getDefault() new_window_properties = WindowProperties.getDefault() self.new_window = base.graphicsEngine.makeOutput( base.pipe, 'Top Down View Window', 0, new_window_fbp, new_window_properties, GraphicsPipe.BFRequireWindow) self.new_window_display_region = self.new_window.makeDisplayRegion() #base.disableMouse() lens = OrthographicLens() lens.setFilmSize(1500, 1500) lens.setNearFar(-5000, 5000) self.default_camera = render.attachNewNode(Camera("top down")) self.default_camera.node().setLens(lens) #self.default_camera.setPosHpr(Vec3( -75, 0, 2200), Vec3(0, -90, 0)) self.default_camera.setPosHpr(Vec3(-75, 0, 0), Vec3(0, -90, 0)) #self.new_window = base.openWindow() self.display_regions = [] self.display_regions.append(self.new_window_display_region) self.display_regions.append( base.win.makeDisplayRegion(0, 0.32, 0.52, 1)) self.display_regions.append( base.win.makeDisplayRegion(0.34, 0.66, 0.52, 1)) self.display_regions.append( base.win.makeDisplayRegion(0.68, 1, 0.52, 1)) self.display_regions.append( base.win.makeDisplayRegion(0, 0.32, 0, 0.48)) self.display_regions.append( base.win.makeDisplayRegion(0.34, 0.66, 0, 0.48)) self.display_regions.append( base.win.makeDisplayRegion(0.68, 1, 0, 0.48)) self.display_regions[0].setCamera(self.default_camera) self.border_regions = [] self.border_regions.append( base.win.makeDisplayRegion(0.32, 0.34, 0.52, 1)) self.border_regions.append( base.win.makeDisplayRegion(0.66, 0.68, 0.52, 1)) self.border_regions.append(base.win.makeDisplayRegion( 0, 1, 0.48, 0.52)) self.border_regions.append( base.win.makeDisplayRegion(0.32, 0.34, 0, 0.48)) self.border_regions.append( base.win.makeDisplayRegion(0.66, 0.68, 0, 0.48)) for i in range(0, len(self.border_regions)): border_region = self.border_regions[i] border_region.setClearColor(VBase4(0, 0, 0, 1)) border_region.setClearColorActive(True) border_region.setClearDepthActive(True) #self.setCamera(0) self.controller = Controller(self, mode) self.taskMgr.add(self.updateCameraModules, "Update Camera Modules", 80) self.globalClock.setFrameTime(0.0) self.width = WIDTH self.height = HEIGHT props = WindowProperties() props.setTitle('Virtual Vision Simulator') base.win.requestProperties(props) """new_window_2d_display_region = self.new_window.makeDisplayRegion() new_window_2d_display_region.setSort(20) new_window_camera_2d = NodePath(Camera('2d camera of new window')) lens_2d = OrthographicLens() lens_2d.setFilmSize(2, 2) lens_2d.setNearFar(-1000, 1000) new_window_camera_2d.node().setLens(lens_2d) new_window_render_2d = NodePath('render2d of new window') new_window_render_2d.setDepthTest(False) new_window_render_2d.setDepthWrite(False) new_window_camera_2d.reparentTo(new_window_render_2d) new_window_2d_display_region.setCamera(new_window_camera_2d)""" """aspectRatio = base.getAspectRatio() self.new_window_aspect2d = new_window_render_2d.attachNewNode(PGTop('Aspect2d of new window')) self.new_window_aspect2d.setScale(1.0 / aspectRatio, 1.0, 1.0)""" render.analyze()
def __init__(self): self.d_objects = {} self.client = None self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) #base.win.setWidth(800) props = WindowProperties() props.setTitle('Panda3D/Node.js Networking Experiment') base.win.requestProperties(props) # Post the instructions self.title = addTitle("Roaming Ralph goes Networking") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") self.inst8 = addInstructions(0.55, "Current connection lag:") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) # PlayerStartPos = self.environ.find("**/start_point").getPos() # print "start pos:", PlayerStartPos self.player = None # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # ---------------------------------------------------------------------- # new: create DynObject to "host" a Ralph model for our player avatar # Accept the control keys for movement and rotation self.accept("escape", self.exitGame) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("s", self.setKey, ["cam-right", 1]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("s-up", self.setKey, ["cam-right", 0]) # taskMgr.add(self.moveCamera,"CameraMoveTask") taskMgr.add(self.moveObjects, "ObjectsMoveTask") # Game state variables self.isMoving = False # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 1000) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # 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 __init__(self): self.last_mousex = 0 self.last_mousey = 0 self.zone = None self.zone_reload_name = None self.winprops = WindowProperties( ) # simple console output self.consoleNode = NodePath(PandaNode("console_root")) self.consoleNode.reparentTo(aspect2d) self.console_num_lines = 24 self.console_cur_line = -1 self.console_lines = [] for i in range(0, self.console_num_lines): self.console_lines.append(OnscreenText(text='', style=1, fg=(1,1,1,1), pos=(-1.3, .4-i*.05), align=TextNode.ALeft, scale = .035, parent = self.consoleNode)) # Configuration self.consoleOut('World Forge v.%s loading configuration' % VERSION) self.configurator = Configurator(self) cfg = self.configurator.config resaveRes = False if 'xres' in cfg: self.xres = int(cfg['xres']) else: self.xres = 1024 resaveRes = True if 'yres' in cfg: self.yres = int(cfg['yres']) else: self.yres = 768 resaveRes = True if resaveRes: self.saveDefaultRes() self.xres_half = self.xres / 2 self.yres_half = self.yres / 2 self.mouse_accum = MouseAccume( lambda: (self.xres_half,self.yres_half)) self.eyeHeight = 7.0 self.rSpeed = 80 self.flyMode = 1 # application window setup base.win.setClearColor(Vec4(0,0,0,1)) self.winprops.setTitle( 'World Forge') self.winprops.setSize(self.xres, self.yres) base.win.requestProperties( self.winprops ) base.disableMouse() # Post the instructions self.title = addTitle('World Forge v.' + VERSION) self.inst0 = addInstructions(0.95, "[FLYMODE][1]") self.inst1 = addInstructions(-0.95, "Camera control with WSAD/mouselook. Press K for hotkey list, ESC to exit.") self.inst2 = addInstructions(0.9, "Loc:") self.inst3 = addInstructions(0.85, "Hdg:") self.error_inst = addInstructions(0, '') self.kh = [] self.campos = Point3(155.6, 41.2, 4.93) base.camera.setPos(self.campos) # Accept the application control keys: currently just esc to exit navgen self.accept("escape", self.exitGame) self.accept("window-event", self.resizeGame) # Create some lighting ambient_level = .6 ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(ambient_level, ambient_level, ambient_level, 1.0)) render.setLight(render.attachNewNode(ambientLight)) direct_level = 0.8 directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0.0, 0.0, -1.0)) directionalLight.setColor(Vec4(direct_level, direct_level, direct_level, 1)) directionalLight.setSpecularColor(Vec4(direct_level, direct_level, direct_level, 1)) render.setLight(render.attachNewNode(directionalLight)) # create a point light that will follow our view point (the camera for now) # attenuation is set so that this point light has a torch like effect self.plight = PointLight('plight') self.plight.setColor(VBase4(0.8, 0.8, 0.8, 1.0)) self.plight.setAttenuation(Point3(0.0, 0.0, 0.0002)) self.plnp = base.camera.attachNewNode(self.plight) self.plnp.setPos(0, 0, 0) render.setLight(self.plnp) self.cam_light = 1 self.keyMap = {"left":0, "right":0, "forward":0, "backward":0, "cam-left":0, \ "cam-right":0, "mouse3":0, "flymode":1 } # setup FOG self.fog_colour = (0.8,0.8,0.8,1.0) self.linfog = Fog("A linear-mode Fog node") self.linfog.setColor(self.fog_colour) self.linfog.setLinearRange(700, 980) # onset, opaque distances as params # linfog.setLinearFallback(45,160,320) base.camera.attachNewNode(self.linfog) render.setFog(self.linfog) self.fog = 1 # camera control self.campos = Point3(0, 0, 0) self.camHeading = 0.0 self.camPitch = 0.0 base.camLens.setFov(65.0) base.camLens.setFar(1200) self.cam_speed = 0 # index into self.camp_speeds self.cam_speeds = [40.0, 80.0, 160.0, 320.0, 640.0] # Collision Detection for "WALKMODE" # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. The ray will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0.0, 0.0, 0.0) self.camGroundRay.setDirection(0,0,-1) # straight down self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) # attach the col node to the camCollider dummy node self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays # self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring # self.cTrav.showCollisions(render) # Add the spinCameraTask procedure to the task manager. # taskMgr.add(self.spinCameraTask, "SpinCameraTask") globals.hasClickedSpawn = False; globals.hasClickedGrid = False; taskMgr.add(self.camTask, "camTask") self.toggleControls(1) # need to step the task manager once to make our fake console work taskMgr.step()
def __init__(self): ShowBase.__init__(self) self.disableMouse() self.cam_away = 20 self.cam_elevation = 5 self.rot_rate = .5 self.cam_dist = (self.cam_away**2 + self.cam_elevation**2)**.5 ####### self.environ = GeoMipTerrain("terrain") self.environ.setHeightfield("../terrain/first.png") self.environ.setColorMap("../terrain/first-c.png") self.environ.generate() self.environ.getRoot().setScale(1, 1, 100) self.environ.getRoot().setPos(0, 0, 0) self.environ.getRoot().reparentTo(render) self.environ.getRoot().setName("terrain") self.environ.getRoot().setCollideMask(BitMask32.bit(0)) ####### self.pandaActor = Actor("models/panda", {"walk": "models/panda-walk"}) self.pandaActor.setScale(.5, .5, .5) self.pandaActor.setHpr(180, 0, 0) self.pandaActor.setPos(50, 50, 50) self.pandaActor.reparentTo(render) self.pandaActor.setPythonTag("moving", False) self.avatarYawRot = 0 self.avatarPitchRot = 0 #self.teapot = loader.loadModel("models/teapot") #self.teapot.setScale(1, 1, 1) #self.teapot.setPos(60, 60, 50) #self.teapot.reparentTo(render) self.cam.setHpr(0, 0, 0) self.taskMgr.add(self.updateTerrain, "update terrain", priority=35) self.keys = {"w": 0, "s": 0, "a": 0, "d": 0} self.accept("w", self.setKey, ["w", 1]) self.accept("w-up", self.setKey, ["w", 0]) self.accept("s", self.setKey, ["s", 1]) self.accept("s-up", self.setKey, ["s", 0]) self.accept("a", self.setKey, ["a", 1]) self.accept("a-up", self.setKey, ["a", 0]) self.accept("d", self.setKey, ["d", 1]) self.accept("d-up", self.setKey, ["d", 0]) self.accept("wheel_up", self.zoomCamera, [-1]) self.accept("wheel_down", self.zoomCamera, [1]) self.accept('window-event', self.handleWindowEvent) props = WindowProperties() props.setCursorHidden(True) base.win.requestProperties(props) self.last_mouse_x = self.win.getPointer(0).getX() #self.last_mouse_y = self.win.getPointer(0).getY() self.cTrav = CollisionTraverser() self.pandaGroundRay = CollisionRay(0, 0, 0, 0, 0, 1) self.pandaGroundRayNode = CollisionNode('pandaGroundRay') self.pandaGroundRayNode.addSolid(self.pandaGroundRay) self.pandaGroundRayNode.setFromCollideMask(BitMask32.bit(0)) self.pandaGroundRayNode.setIntoCollideMask(BitMask32.allOff()) self.pandaGroundRayNodepath = self.pandaActor.attachNewNode( self.pandaGroundRayNode) self.pandaGroundRayNodepath.show() self.pandaGroundCollisionHandler = CollisionHandlerFloor() self.pandaGroundCollisionHandler.addCollider( self.pandaGroundRayNodepath, self.pandaActor) self.cTrav.addCollider(self.pandaGroundRayNodepath, self.pandaGroundCollisionHandler)
def __init__(self): ShowBase.__init__(self) mySound = base.loader.loadSfx("sfx/tank_with_radar.ogg") self.mainShot_snd = base.loader.loadSfx("sfx/mainShot.ogg") self.enemyShot_snd = base.loader.loadSfx("sfx/enemyShot.ogg") self.enemyTankExplosion_snd = base.loader.loadSfx( "sfx/enemyTankExplosion.ogg") device_list = self.devices.getDevices() for device in device_list: print(device.device_class) # if device.device_class == DeviceClass.flight_stick: # print("Have Joy stick") # render.setDepthTest(False) self.camLens.setFov(50) render.setAntialias(AntialiasAttrib.MLine) base.setBackgroundColor(0, 0, 0) base.disableMouse() props = WindowProperties() # props.setCursorHidden(True) base.win.requestProperties(props) # Load the environment models self.ground = self.loader.loadModel("models/ground_bl.egg") self.tank = self.loader.loadModel("models/tank_bl.egg") self.tank.setRenderModeWireframe() self.ground.setRenderModeWireframe() self.ground.setScale(100, 100, 1) # tank as lines # set up explosion variables # explosion intervals added in renderTanks() method for t in tanks_list: tanks_dict[t]["explosion"] = Parallel( name="Tank{}-Explosion".format(t)) # group node for all enemy tanks self.tank_group = render.attachNewNode("Tanks") self.renderTanks(self.tank_group) # tank rounds with open('models/tank_round.json', "r") as f: data = json.load(f) lines = create_lineSegs_object(data, 0) lines.setThickness(3) gn_round = lines.create() np_round = NodePath(gn_round) self.tank_round = [] # self.tank_round.append(render.attachNewNode("tank-round")) np_round.instanceTo(self.tank_round[0]) # self.tank_round[0].hide() self.tank_round[0].setColorScale(0.3, 0.3, 1.0, 1.0) self.tank_round[0].setPos(0, 20, -0.2 - 10) self.tank_round[0].setHpr(self.tank_round[0], 0, 90, 0) self.tank_round[0].setScale(0.2, 0.2, 0.2) self.tank_round[0].reparentTo(camera) # render enemy tank round for t in tanks_list: tanks_dict[t]["round"] = render.attachNewNode( "tank{}-round".format(t)) np_round.instanceTo(tanks_dict[t]["round"]) tanks_dict[t]["round"].setPos(-0.4, 0, 1.61325) tanks_dict[t]["round"].setHpr(tanks_dict[t]["round"], 0, 0, 90) tanks_dict[t]["round"].setScale(0.14, 0.14, 0.14) tanks_dict[t]["round"].reparentTo(tanks_dict[t]["tank"]) # # new mountain method self.render_mountains() #################### # collisions # #################### print(CollisionNode.getDefaultCollideMask()) # Initialize collision Handler self.collHandEvent = CollisionHandlerEvent() self.collHandEvent.addInPattern('into-%in') # collision spheres enemy tank for t in tanks_list: cs = CollisionSphere(0, 0, 0.9, tanks_dict[t]["coll_rad"]) cnodePath = tanks_dict[t]["tank"].attachNewNode( CollisionNode('cTank' + t)) cnodePath.node().addSolid(cs) if DEBUG: # cnodePath.show() pass self.tank_group.setCollideMask(BitMask32(0x10)) # print(self.tank_group.getCollideMask()) # print(tanks_dict['1']["tank"].getCollideMask()) # collision sphere for round of main tank cs = CollisionSphere(0, 0, 0, 1) tr_cnodePath = self.tank_round[0].attachNewNode( CollisionNode('cTankRound')) tr_cnodePath.node().addSolid(cs) # collision spheres for enemy tank rounds cs = CollisionSphere(0, 0, 0, 1) for t in tanks_list: np = tanks_dict[t]["round"].attachNewNode( CollisionNode('ceTankRound' + t)) np.node().addSolid(cs) np.node().setFromCollideMask(BitMask32(0x20)) # np.show() # collision sphere main tank cs = CollisionSphere(0, 0, 0, 1) np = self.camera.attachNewNode(CollisionNode('cmTank')) np.node().addSolid(cs) # np.show() # Initialise Traverser traverser = CollisionTraverser('Main Traverser') if DEBUG: traverser.showCollisions(render) base.cTrav = traverser # from objects traverser.addCollider(tr_cnodePath, self.collHandEvent) np_list = render.findAllMatches("**/ceTankRound*") for np in np_list: traverser.addCollider(np, self.collHandEvent) # grid grid_lines = procedural_grid(-1000, 500, -1000, 500, 50) grid_lines.setThickness(1) node = grid_lines.create() self.grid = NodePath(node) self.grid.setColorScale(0.15, 0.2, 0.15, 1.0) self.grid.setPos(0, 0, -0.2) alight = AmbientLight('ambientLight') alight.setColor(Vec4(0, 0, 0, 0)) # ambient light is dim red # alightNP = self.render.attachNewNode(alight) # render sight self.render_sight() # Tasks for t in tanks_list: tanks_dict[t]["move"] = True self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") self.taskMgr.add(self.moveTanksTask, "MoveTanksTask") self.taskMgr.add(self.moveTask, "MoveTask") self.taskMgr.add(self.enemy_shoot_task, "EnemyShoot") # base.messenger.toggleVerbose() self.accept('space', self.shoot) self.accept('space-up', self.shot_clear) self.accept('shot-done', self.reset_shot) self.accept('into-' + 'cmTank', self.struck) for t in tanks_list: self.accept('into-' + 'cTank' + t, self.tank0_round_hit) self.accept('explosion{}-done'.format(t), self.explosion_cleanup, extraArgs=[t]) self.accept('shot{}-done'.format(t), self.enemy_reset_shot, extraArgs=[t]) # on-screen text vect = self.camera.getHpr() self.textObject = OnscreenText(text=str(vect[0]), pos=(-0.5, -0.9), scale=(0.03, 0.05), fg=(0.4, 1.0, 0.4, 1), mayChange=True) self.textObject.reparentTo(self.render2d) mySound.setLoop(True) mySound.play()
def toggleCursor(self, state): props = WindowProperties() props.setCursorHidden(state) base.win.requestProperties(props)
def __init__(self): ShowBase.__init__(self) ########## Window configuration ######### wp = WindowProperties() wp.setSize(1024, 860) wp.setTitle("") wp.setOrigin(-2, -2) self.win.requestProperties(wp) self.win.movePointer(0, wp.getXSize() / 2, wp.getYSize() / 2) print wp.getXSize() / 2, wp.getYSize() / 2 ########## Gameplay settings ######### self.gameMode = {"display": PLAY, "play": TERRAIN} self.level = 1.5 self.mode_initialized = False ######### Camera ######### self.disableMouse() self.mainCamera = Camera(self.camera) self.mainCamera.camObject.setHpr(0, 0, 0) self.loadLevel() ######### Events ######### self.taskMgr.add(self.gameLoop, "gameLoop", priority=35) self.keys = {"w": 0, "s": 0, "a": 0, "d": 0, "space": 0, "escape": 0} self.accept("w", self.setKey, ["w", 1]) self.accept("w-up", self.setKey, ["w", 0]) self.accept("s", self.setKey, ["s", 1]) self.accept("s-up", self.setKey, ["s", 0]) self.accept("a", self.setKey, ["a", 1]) self.accept("a-up", self.setKey, ["a", 0]) self.accept("d", self.setKey, ["d", 1]) self.accept("d-up", self.setKey, ["d", 0]) self.accept("space", self.setKey, ["space", 1]) self.accept("space-up", self.setKey, ["space", 0]) self.accept("escape", self.setKey, ["escape", 1]) self.accept("escape-up", self.setKey, ["escape", 0]) self.accept("wheel_up", self.zoomCamera, [-1]) self.accept("wheel_down", self.zoomCamera, [1]) self.accept("window-event", self.handleWindowEvent) ######### GUI ######### #self.fonts = {"failure" : loader.loadFont('myfont.ttf')} self.guiElements = [] self._GCLK = None self._FT = None
def gameLoop(self, task): #Compensate for inconsistent update intervals dt = globalClock.getDt() if self.GAME_MODE == MAIN_MENU: if not self.mode_initialized: self.buildMainMenu() self.mode_initialized = True if self.GAME_MODE == IN_GAME_MENU: if not self.mode_initialized: inGameMenuFogColor = (50, 150, 50) inGameMenuFog = Fog("inGameMenuFog") inGameMenuFog.setMode(Fog.MExponential) inGameMenuFog.setColor(*inGameMenuFogColor) inGameMenuFog.setExpDensity(.01) render.setFog(inGameMenuFog) self.buildInGameMenu() self.mode_initialized = True if self.GAME_MODE == NORMAL: if not self.mode_initialized: props = WindowProperties() props.setCursorHidden(True) base.win.requestProperties(props) self.last_mouse_x = self.win.getPointer(0).getX() self.last_mouse_y = self.win.getPointer(0).getY() self.mode_initialized = True #Handle keyboard input self.avatar.handleKeys(self.keys) self.avatar.move(dt) #Mouse-based viewpoint rotation mouse_pos = self.win.getPointer(0) current_mouse_x = mouse_pos.getX() current_mouse_y = mouse_pos.getY() mouse_shift_x = current_mouse_x - self.last_mouse_x mouse_shift_y = current_mouse_y - self.last_mouse_y self.last_mouse_x = current_mouse_x self.last_mouse_y = current_mouse_y if current_mouse_x < 5 or current_mouse_x >= (self.win_center_x * 1.5): base.win.movePointer(0, self.win_center_x, current_mouse_y) self.last_mouse_x = self.win_center_x if current_mouse_y < 5 or current_mouse_y >= (self.win_center_y * 1.5): base.win.movePointer(0, current_mouse_x, self.win_center_y) self.last_mouse_y = self.win_center_y yaw_shift = -((mouse_shift_x) * Camera.ROT_RATE[0]) pitch_shift = -((mouse_shift_y) * Camera.ROT_RATE[1]) self.avatar.yawRot += yaw_shift self.mainCamera.pitchRot += pitch_shift if self.mainCamera.pitchRot > Camera.MAX_PITCH_ROT: self.mainCamera.pitchRot = Camera.MAX_PITCH_ROT elif self.mainCamera.pitchRot < Camera.MIN_PITCH_ROT: self.mainCamera.pitchRot = Camera.MIN_PITCH_ROT self.avatar.objectNP.setH(self.avatar.yawRot) self.mainCamera.camObject.setH(self.avatar.yawRot) self.mainCamera.camObject.setP(self.mainCamera.pitchRot) if self.NAVIGATION_MODE == TERRAIN: xy_plane_cam_dist = Camera.AVATAR_DIST cam_z_adjust = Camera.ELEVATION elif self.NAVIGATION_MODE == SPACE: xy_plane_cam_dist = Camera.AVATAR_DIST * cos( radians(self.pitchRot)) cam_z_adjust = Camera.AVATAR_DIST * sin(radians(self.pitchRot)) cam_x_adjust = xy_plane_cam_dist * sin(radians(self.avatar.yawRot)) cam_y_adjust = xy_plane_cam_dist * cos(radians(self.avatar.yawRot)) self.mainCamera.camObject.setPos( self.avatar.objectNP.getX() + cam_x_adjust, self.avatar.objectNP.getY() - cam_y_adjust, self.avatar.objectNP.getZ() + cam_z_adjust) #Find collisions self.cTrav.traverse(render) return Task.cont
def __init__(self): ShowBase.__init__(self) # enable physics engine self.enableParticles() # take care of cursor shit self.resetCursor() # set up loading screen self.loadingText = OnscreenText("Loading...", 1, fg=(1, 1, 1, 1), pos=(0, 0), align=TextNode.ACenter, scale=.07, mayChange=1) self.graphicsEngine.renderFrame( ) #render a frame otherwise the screen will remain black self.graphicsEngine.renderFrame() #idem dito self.graphicsEngine.renderFrame( ) #you need to do this because you didn't yet call run() self.graphicsEngine.renderFrame( ) #run() automatically renders the frames for you # get menu background music playing self.loadingText.setText('Loading models/audio/sfx/menu_music.ogg') self.graphicsEngine.renderFrame( ) #render a frame otherwise the screen will remain black self.graphicsEngine.renderFrame() #idem dito self.graphicsEngine.renderFrame( ) #you need to do this because you didn't yet call run() self.graphicsEngine.renderFrame( ) #run() automatically renders the frames for you menuMusic = self.loader.loadSfx("models/audio/sfx/menu_music.ogg") menuMusic.setLoop(True) menuMusic.play() # set title window props = WindowProperties() props.setTitle('Tokoyo Ghoul') self.win.requestProperties(props) # Load the environment model. self.loadingText.setText('Loading models/environment.egg.pz') self.setBackgroundColor((0, 1, 1, .5)) self.graphicsEngine.renderFrame( ) #render a frame otherwise the screen will remain black self.graphicsEngine.renderFrame() #idem dito self.graphicsEngine.renderFrame( ) #you need to do this because you didn't yet call run() self.graphicsEngine.renderFrame( ) #run() automatically renders the frames for you self.scene = self.loader.loadModel("models/output.bam") # Reparent the model to render. self.scene.reparentTo(self.render) # Apply scale and position transforms on the model. self.scene.setScale(0.15, 0.15, 0.15) self.scene.setPos(0, 0, 0) # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") # add fog and such #myFog = Fog("titlefog") #myFog.setColor((1,0,0,0.1)) #myFog.setExpDensity(0.3) #self.render.setFog(myFog) # Load and transform the didicus actor. #self.pandaActor = Actor("models/camera", #{"walk": "models/panda-walk4"}) self.loadingText.setText('Loading models/african.x') self.graphicsEngine.renderFrame( ) #render a frame otherwise the screen will remain black self.graphicsEngine.renderFrame() #idem dito self.graphicsEngine.renderFrame( ) #you need to do this because you didn't yet call run() self.graphicsEngine.renderFrame( ) #run() automatically renders the frames for you self.pandaActor = Actor("models/camera") self.pandaActor.setPos(10, -10, 5) self.pandaActor.setScale(0.5, 0.5, 0.5) self.pandaActor.reparentTo(self.render) # Loop its animation. #self.pandaActor.loop("walk") # Create the four lerp intervals needed for the panda to # walk back and forth. pandaPosInterval1 = self.pandaActor.posInterval(13, Point3(-10, -10, 5), startPos=Point3( 0, 0, 5)) pandaPosInterval2 = self.pandaActor.posInterval(13, Point3(0, 0, 5), startPos=Point3( -10, -10, 5)) pandaHprInterval1 = self.pandaActor.hprInterval(3, Point3(180, 0, 0), startHpr=Point3( 0, 0, 0)) pandaHprInterval2 = self.pandaActor.hprInterval(3, Point3(0, 0, 0), startHpr=Point3( 180, 0, 0)) # Create and play the sequence that coordinates the intervals. self.pandaPace = Sequence(pandaPosInterval1, pandaHprInterval1, pandaPosInterval2, pandaHprInterval2, name="pandaPace") self.pandaPace.loop() # Make the menu options # Create a frame self.startgamebutton = DirectButton(pos=(1, 0, -0.6), text=("Play"), scale=.1, command=self.startGame) self.exitbutton = DirectButton(pos=(1, 0, -0.74), text=("Exit"), scale=.1, command=self.close) # load the title image self.loadingText.setText('Loading images/title.png') self.graphicsEngine.renderFrame( ) #render a frame otherwise the screen will remain black self.graphicsEngine.renderFrame() #idem dito self.graphicsEngine.renderFrame( ) #you need to do this because you didn't yet call run() self.graphicsEngine.renderFrame( ) #run() automatically renders the frames for you # clean up loading screen self.loadingText.cleanup()
def init_mouse_control_event(self): props = WindowProperties() #props.setCursorHidden(True) self.app.win.requestProperties(props)
def cursorShit(self): # To set relative mode and hide the cursor: props = WindowProperties() props.setCursorHidden(True) props.setMouseMode(WindowProperties.M_confined) self.win.requestProperties(props)
def set(self, pipe, width, height, fullscreen, embedded): self.notify.debugStateCall(self) state = False self.notify.info('SET') if self.restrict_to_embedded: fullscreen = 0 embedded = 1 if embedded: if base.appRunner.windowProperties: width = base.appRunner.windowProperties.getXSize() height = base.appRunner.windowProperties.getYSize() self.current_pipe = base.pipe self.current_properties = WindowProperties(base.win.getProperties()) properties = self.current_properties self.notify.debug('DISPLAY PREVIOUS:') self.notify.debug(' EMBEDDED: %s' % bool(properties.getParentWindow())) self.notify.debug(' FULLSCREEN: %s' % bool(properties.getFullscreen())) self.notify.debug(' X SIZE: %s' % properties.getXSize()) self.notify.debug(' Y SIZE: %s' % properties.getYSize()) self.notify.debug('DISPLAY REQUESTED:') self.notify.debug(' EMBEDDED: %s' % bool(embedded)) self.notify.debug(' FULLSCREEN: %s' % bool(fullscreen)) self.notify.debug(' X SIZE: %s' % width) self.notify.debug(' Y SIZE: %s' % height) if self.current_pipe == pipe and bool( self.current_properties.getParentWindow( )) == bool(embedded) and self.current_properties.getFullscreen( ) == fullscreen and self.current_properties.getXSize( ) == width and self.current_properties.getYSize() == height: self.notify.info('DISPLAY NO CHANGE REQUIRED') state = True else: properties = WindowProperties() properties.setSize(width, height) properties.setFullscreen(fullscreen) properties.setParentWindow(0) if embedded: if base.appRunner.windowProperties: properties = base.appRunner.windowProperties original_sort = base.win.getSort() if self.resetWindowProperties(pipe, properties): self.notify.debug('DISPLAY CHANGE SET') properties = base.win.getProperties() self.notify.debug('DISPLAY ACHIEVED:') self.notify.debug(' EMBEDDED: %s' % bool(properties.getParentWindow())) self.notify.debug(' FULLSCREEN: %s' % bool(properties.getFullscreen())) self.notify.debug(' X SIZE: %s' % properties.getXSize()) self.notify.debug(' Y SIZE: %s' % properties.getYSize()) if bool(properties.getParentWindow()) == bool( embedded) and properties.getFullscreen( ) == fullscreen and properties.getXSize( ) == width and properties.getYSize() == height: self.notify.info('DISPLAY CHANGE VERIFIED') state = True else: self.notify.warning( 'DISPLAY CHANGE FAILED, RESTORING PREVIOUS DISPLAY') self.restoreWindowProperties() else: self.notify.warning('DISPLAY CHANGE FAILED') self.notify.warning('DISPLAY SET - BEFORE RESTORE') self.restoreWindowProperties() self.notify.warning('DISPLAY SET - AFTER RESTORE') base.win.setSort(original_sort) base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() return state
def resetCursor(self): # To revert to normal mode: props = WindowProperties() props.setCursorHidden(False) props.setMouseMode(WindowProperties.M_absolute) self.win.requestProperties(props)
from pandac.PandaModules import * loadPrcFile("./config.prc") import direct.directbase.DirectStart from direct.task import Task from direct.actor import Actor from direct.showbase import DirectObject from direct.gui.OnscreenText import OnscreenText from direct.fsm import FSM from direct.interval.IntervalGlobal import * #tirando o cursor do mouse from pandac.PandaModules import WindowProperties props = WindowProperties() props.setCursorHidden(True) base.win.requestProperties(props) import control from level import * from screens import * import options class Game(FSM.FSM): def __init__(self): FSM.FSM.__init__(self, 'Game') self.wm = None
def set(self, pipe, width, height, fullscreen, embedded): self.notify.debugStateCall(self) state = False self.notify.info("SET") #fullscreen = options.fullscreen_runtime #embedded = options.embedded_runtime if self.restrict_to_embedded: fullscreen = 0 embedded = 1 if embedded: if base.appRunner.windowProperties: width = base.appRunner.windowProperties.getXSize() height = base.appRunner.windowProperties.getYSize() self.current_pipe = base.pipe self.current_properties = WindowProperties(base.win.getProperties()) properties = self.current_properties self.notify.debug("DISPLAY PREVIOUS:") self.notify.debug(" EMBEDDED: %s" % bool(properties.getParentWindow())) self.notify.debug(" FULLSCREEN: %s" % bool(properties.getFullscreen())) self.notify.debug(" X SIZE: %s" % properties.getXSize()) self.notify.debug(" Y SIZE: %s" % properties.getYSize()) self.notify.debug("DISPLAY REQUESTED:") self.notify.debug(" EMBEDDED: %s" % bool(embedded)) self.notify.debug(" FULLSCREEN: %s" % bool(fullscreen)) self.notify.debug(" X SIZE: %s" % width) self.notify.debug(" Y SIZE: %s" % height) if ((self.current_pipe == pipe) and \ (bool(self.current_properties.getParentWindow( )) == bool(embedded)) and \ (self.current_properties.getFullscreen ( ) == fullscreen) and \ (self.current_properties.getXSize ( ) == width) and \ (self.current_properties.getYSize ( ) == height)): # no display change required self.notify.info("DISPLAY NO CHANGE REQUIRED") state = True else: properties = WindowProperties() properties.setSize(width, height) properties.setFullscreen(fullscreen) properties.setParentWindow(0) if embedded: if base.appRunner.windowProperties: properties = base.appRunner.windowProperties # get current sort order original_sort = base.win.getSort() if self.resetWindowProperties(pipe, properties): self.notify.debug("DISPLAY CHANGE SET") # verify display change properties = base.win.getProperties() self.notify.debug("DISPLAY ACHIEVED:") self.notify.debug(" EMBEDDED: %s" % bool(properties.getParentWindow())) self.notify.debug(" FULLSCREEN: %s" % bool(properties.getFullscreen())) self.notify.debug(" X SIZE: %s" % properties.getXSize()) self.notify.debug(" Y SIZE: %s" % properties.getYSize()) if ((bool(properties.getParentWindow( )) == bool(embedded)) and \ (properties.getFullscreen ( ) == fullscreen) and \ (properties.getXSize ( ) == width) and \ (properties.getYSize ( ) == height)): self.notify.info("DISPLAY CHANGE VERIFIED") state = True else: self.notify.warning( "DISPLAY CHANGE FAILED, RESTORING PREVIOUS DISPLAY") self.restoreWindowProperties() else: self.notify.warning("DISPLAY CHANGE FAILED") self.notify.warning("DISPLAY SET - BEFORE RESTORE") self.restoreWindowProperties() self.notify.warning("DISPLAY SET - AFTER RESTORE") # set current sort order base.win.setSort(original_sort) base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() return state
def __init__(self): ShowBase.__init__(self) props = WindowProperties() props.setTitle("Gesture Maze") base.win.requestProperties(props) self.tital = OnscreenText(text="Gesture Maze Control", parent=base.a2dTopLeft, align=TextNode.ALeft, pos=(0.05, -0.08), fg=(1, 1, 1, 1), scale=0.06, shadow=(0, 0, 0, 0.5)) self.accept("escape", sys.exit) camera_num = 0 self.gesture_controler = gesture_control.GestureControler(0) self.disableMouse() camera.setPosHpr(0, 0, 25, 0, -90, 0) self.maze = loader.loadModel("models/%s" % settings.maze_id) self.maze.reparentTo(render) self.walls = self.maze.find("**/wall_collide") self.walls.node().setIntoCollideMask(BitMask32.bit(0)) # self.walls.show() self.loseTriggers = [] for i in range(6): trigger = self.maze.find("**/hole_collide" + str(i)) trigger.node().setIntoCollideMask(BitMask32.bit(0)) trigger.node().setName("loseTriggers") self.loseTriggers.append(trigger) # trigger.show() self.mazeGround = self.maze.find("**/ground_collide") self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1)) self.ballRoot = render.attachNewNode("ballRoot") self.ball = loader.loadModel("models/ball") self.ball.reparentTo(self.ballRoot) self.ballSphere = self.ball.find("**/ball") self.ballSphere.node().setFromCollideMask(BitMask32.bit(0)) self.ballSphere.node().setIntoCollideMask(BitMask32.allOff()) self.ballGroundRay = CollisionRay() self.ballGroundRay.setOrigin(0, 0, 10) self.ballGroundRay.setDirection(0, 0, -1) self.ballGroundCol = CollisionNode("groundRay") self.ballGroundCol.addSolid(self.ballGroundRay) self.ballGroundCol.setFromCollideMask(BitMask32.bit(1)) self.ballGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol) # self.ballGroundColNp.show() self.cTrav = CollisionTraverser() self.cHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ballSphere, self.cHandler) self.cTrav.addCollider(self.ballGroundColNp, self.cHandler) # self.cTrav.showCollisions(render) ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(LVector3(0, 0, -1)) directionalLight.setColor((0.375, 0.375, 0.375, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) self.ballRoot.setLight(render.attachNewNode(ambientLight)) self.ballRoot.setLight(render.attachNewNode(directionalLight)) m = Material() m.setSpecular((1, 1, 1, 1)) m.setShininess(96) self.ball.setMaterial(m, 1) self.start()
def openMainWindow(self, *args, **kw): ShowBase.ShowBase.openMainWindow(self, *args, **kw) if self.windowTitle is not None: wp = WindowProperties() wp.setTitle(self.windowTitle) self.win.requestProperties(wp)