def test_new_localization_workflow(self): # Write a new localization. article_dir = os.path.join(Article.LOCALIZED_ROOT, 'de') os.makedirs(article_dir) with open(os.path.join(article_dir, 'article1.html'), 'w') as f: text = r'%s{%% tag %%}%sBeispiel' % (UNTRANSLATABLE_BEGIN, UNTRANSLATABLE_END) f.write(text) l7r = Localizer(original_root=Article.ROOT, localized_root=Article.LOCALIZED_ROOT) self.assertEqual(1, len(l7r.articles)) # Test writing localizable HTML l7r.GenerateLocalizableFiles() self.assertTrue(os.path.exists(l7r.articles[0].localizable_file_path)) self.assertTrue(os.path.isfile(l7r.articles[0].localizable_file_path)) # Test importataion. l7r.ImportLocalizedFiles() self.assertEqual([], l7r.articles[0].new_localizations) self.assertTrue(os.path.exists(l7r.articles[0].GetOriginalFilePath('en'))) self.assertTrue(os.path.isfile(l7r.articles[0].GetOriginalFilePath('en'))) self.assertTrue(os.path.exists(l7r.articles[0].GetOriginalFilePath('de'))) self.assertTrue(os.path.isfile(l7r.articles[0].GetOriginalFilePath('de'))) # Verify contents with open(l7r.articles[0].GetOriginalFilePath('de'), 'r') as infile: contents = infile.read() self.assertEqual("{% tag %}Beispiel", contents)
def testSimple(self): l7r = Localizer(original_root=os.path.join(TEST_ROOT, 'test_fixtures', 'localizer_simple')) l7r.GenerateLocalizableFiles() for article in l7r.articles: self.__created_files.append(article.localizable_file_path) self.assertTrue(os.path.exists(article.localizable_file_path)) self.assertTrue(os.path.isfile(article.localizable_file_path))
def __init__(self): # Initialize ROS node rospy.init_node("Controller") self.name = "Controller object" self.rate = rospy.Rate(10) # allow node to 'spin' at 10hz rospy.on_shutdown(self.shutdown) # calls this function when Ctrl+C self.motion = Motion() self.sensor = Sensor() self.localizer = Localizer() self.visited_highlights = [] # Boolean for reached goal self.goalReached = False
class Gnome: def __init__(self, model_path): self.model = np.load(open(model_path, 'r')).item() self.head = 6 self.payload = 6 self.localizer = Localizer() print('Inflation model loaded') # head of data: Latitude, Longitude, Altitude, Speed, Accuracy, (UTC)TimeInMs # payload: Svid, Azi, Ele, SNR, Used, EstPathInflation, ... def update(self, data): head = data[:6] lat, lon = l2key(data[0]), l2key(data[1]) accuracy = data[4] lat_head, lat_body = l_break(lat) lon_head, lon_body = l_break(lon) if not lat_head in self.model or not lon_head in self.model[lat_head]: print('Not covered by model, use original location') return [lat, lon] search_rad = accuracy * 1.3 / ll_m_ratio candidates = {} for cand_lat_body in self.model[lat_head][lon_head]: if abs(lat_body - cand_lat_body) > search_rad: continue candidates[cand_lat_body] = {} for cand_lon_body in self.model[lat_head][lon_head][cand_lat_body]: if abs(lon_body - cand_lon_body) > search_rad: continue candidates[cand_lat_body][cand_lon_body] = \ self.model[lat_head][lon_head][cand_lat_body][cand_lon_body] for cand_lat_body in candidates: for cand_lon_body in candidates[cand_lat_body]: for i in range(self.head, len(data), self.payload): azi, ele = map(int, data[i + 1:i + 3]) if ele in candidates[cand_lat_body][cand_lon_body][azi]: data[i + 5] = int( candidates[cand_lat_body][cand_lon_body][azi][ele]) self.localizer.add_candidate(cand_lat_body, cand_lon_body, data) return self.localizer.update()
def testSimple(self): l7r = Localizer(original_root=os.path.join(TEST_ROOT, 'test_fixtures', 'localizer_simple')) self.assertEqual(3, len(l7r.articles)) self.assertEqual( os.path.join(TEST_ROOT, 'test_fixtures', 'localizer_simple', 'article1'), l7r.articles[0].path) self.assertEqual( os.path.join(TEST_ROOT, 'test_fixtures', 'localizer_simple', 'article2'), l7r.articles[1].path) self.assertEqual( os.path.join(TEST_ROOT, 'test_fixtures', 'localizer_simple', 'article3'), l7r.articles[2].path)
def testDeeper(self): l7r = Localizer(original_root=os.path.join(TEST_ROOT, 'test_fixtures', 'localizer_deeper')) self.assertEqual(6, len(l7r.articles)) self.assertEqual( os.path.join(TEST_ROOT, 'test_fixtures', 'localizer_deeper', 'path1', 'path2', 'article1'), l7r.articles[0].path) self.assertEqual( os.path.join(TEST_ROOT, 'test_fixtures', 'localizer_deeper', 'path1', 'path2', 'article2'), l7r.articles[1].path) self.assertEqual( os.path.join(TEST_ROOT, 'test_fixtures', 'localizer_deeper', 'path1', 'path2', 'article3'), l7r.articles[2].path) self.assertEqual( os.path.join(TEST_ROOT, 'test_fixtures', 'localizer_deeper', 'path3', 'path4', 'article4'), l7r.articles[3].path) self.assertEqual( os.path.join(TEST_ROOT, 'test_fixtures', 'localizer_deeper', 'path3', 'path4', 'article5'), l7r.articles[4].path) self.assertEqual( os.path.join(TEST_ROOT, 'test_fixtures', 'localizer_deeper', 'path3', 'path4', 'article6'), l7r.articles[5].path)
def __init__(self, eventmanager): self._eventmanager = eventmanager self._world = world = eventmanager._world self.burst_deferred_maker = self._world.burst_deferred_maker # shortcuts to BurstDeferred factory. NOTE: don't get wrapped by BehaviorActions - should they? self.make = self.burst_deferred_maker.make self.wrap = self.burst_deferred_maker.wrap self.succeed = self.burst_deferred_maker.succeed self._motion = world.getMotionProxy() self._speech = world.getSpeechProxy() #self._video = world.getALVideoDeviceProxy() self._imops = world.getImopsProxy() self._current_camera = None # This is based on our commands only - we are the only ones changing it self._current_fps = burst_consts.INITIAL_FRAME_PER_SECOND self._joint_names = self._world.jointnames self._journey = Journey(self) self._movecoordinator = self._world._movecoordinator self.currentCamera = CAMERA_WHICH_BOTTOM_CAMERA self._camera_switch_time = world.time self.tracker = Tracker(self) # Please remember to stop # Todo - Locking self.centerer = Centerer(self) # Please remember to stop self.searcher = Searcher(self) # all of these behaviors self.localizer = Localizer(self) # when you stop the InitialBehavior. Thank you. self.headControllers = [self.tracker, self.centerer, self.searcher] # we keep track of the last head bd self._current_head_bd = self.succeed(self) self._current_motion_bd = self.succeed(self) # slight changes between 1.3.8 and 1.2.0 if is_120: self.setWalkConfig = self.setWalkConfig_120 else: self.setWalkConfig = self.setWalkConfig_138
class Server(GameSide): def __init__(self): '''Initializes the server.''' self.mode = "server" self.oP = OutPipe("Server", 0) self.nC = None self.cvars = { "sv_addr": "0.0.0.0", "sv_port": 7777, "sv_netlog": 0, "sv_level": "", "sv_game": 0, "sv_singleplayer": 0, "sv_gamemode": "singleplayer", "sv_startscript": "", "sv_master": "", "sv_dedicated": 0, "sv_chat": 1, "sv_background_red": 0, "sv_background_green": 0, "sv_background_blue": 0, "sv_background_alpha": 0, "sv_password": "", "cl_language": "en", "cl_subtitles": 1, "cl_width": 1280, "cl_height": 720, "cl_fullscreen": 0, "cl_motionblur": 0, "cl_motionblur_amount": 0, "cl_anisotropic": 1, "cl_mipmap": "none", "cl_vsync": "off", "cl_musicvolume": 10, "cl_dialogvolume": 10, "cl_soundvolume": 10, "cl_netping": 0, } self.netVars = {} self.oldNetVars = self.netVars self.oldcvars = self.cvars self.gameMode = None self.level = None self.unassignedPlayers = [] self.entities = [] self.events = [] self.saveFile = None self.chatMessages = [] self.eI = EngineInterface(True) self.sE = ScriptExecuter() self.pR = PhysicsReader(self) self.sH = ShaderHandler() self.l = Localizer(self) self.updateNetwork() self.forceUpdateCVars() self.keepAliveTicker = 0 self.trackedProperties = [] loadServer(self) self.oP("Initialized.") def forceUpdateCVars(self): '''Forces all the cVars to run their updaters as though they had just been set.''' for key in self.cvars.keys(): if not "cl_" == key[:3]: self.configure(key, self.get(key), override=True) self.oP("Force updated cVars.") def configureNetVar(self, var, val): '''Configures a NetVar and updates clients about it.''' self.netVars[var] = val self.events.append([None, ["SYSTEM", "NETVARS", [var, val]]]) self.oP("Configured netVar %s to %s." % (str(var), str(val))) def configure(self, key, val, override=False): '''Configure a cvar.''' changed = False if key in self.cvars.keys(): #Switch for int if type(self.cvars[key]) == type(0): val = int(val) #Used for functions if type(self.cvars[key]) == type(self.configure): self.cvars[key](val) self.oP("CVar %s executed." % key) else: if val != self.cvars[key] or override: changed = True self.cvars[key] = val self.sendEvent([None, ["SYSTEM", "CVARS", [key, val]]]) self.oP("CVar %s configured to %s (%s)." % (key, val, str(type(val)).replace( "<class '", "").replace("'>", ""))) else: self.oP("CVar %s not present." % key) if changed: self.updateGame(key) def endGame(self): '''Ends the game instance.''' self.oP("Ending game instance.") self.endGameMode() self.endLevel() def endGameMode(self): '''Ends the game mode.''' if hasattr(self.gameMode, "kill"): self.gameMode.kill() self.gameMode = None def replaceMesh(self, ent, meshName): '''Replaces the mesh of an entity.''' cR = self.load("Mesh", meshName) name = cR.get("name") resourcePath = cR.get("resourcePath") self.loadLibrary("Mesh", resourcePath, mesh=True) for obj in self.eI.getMainScene().objectsInactive: if obj.name == meshName: meshName = obj.meshes[0] break ent.gameObject.replaceMesh(meshName, True, True) self.sendEvent([None, ["PHYSICS", "MESH", [ent.GUID, meshName]]]) self.oP("Replaced mesh of %s with %s." % (ent.GUID, meshName)) def quitGame(self): '''Ends the game and kills network connections.''' self.oP("Shutting down...") self.endGame() self.purgeNetwork() def setGameMode(self, name): '''Load a gamemode into the engine.''' self.sE.addContext("Server", self) self.sE.execute(GAMEMODE_PATH + name) self.gameMode = self.newGamemode(self) def updateNetwork(self): '''Update the network module for changes to port or addr''' self.purgeNetwork() self.nC = NetCore() if self.get("sv_netlog"): self.nC.configure("DEBUG", True) self.nC.configure("VERBOSE", True) else: self.nC.configure("DEBUG", False) self.nC.configure("VERBOSE", False) self.nC.pingcount = self.get("cl_netping") self.nC.configure("NAME", "Server") self.nC.setProtocol("UDP") self.nC.configure("HOST", self.get("sv_addr")) self.nC.configure("PORT", self.get("sv_port")) self.nC.initialize() def purgeNetwork(self): '''Destroys the NetCore once and for all.''' if self.nC: self.nC.clear() self.nC.destroy() self.nC = None def setMusic(self, music): '''Sets the music track.''' launcher = self.eI.getGlobal("launcher") launcher.sound.playMusic(music) self.events.append([None, ["SYSTEM", "MUSIC_PLAY", [music, 0.0]]]) self.oP("Set music to %s." % music) def stopMusic(self): '''Stops the music track.''' launcher = self.eI.getGlobal("launcher") launcher.sound.stopMusic() self.events.append([None, ["SYSTEM", "MUSIC_STOP", None]]) def playSound(self, sound, emitter=None): '''Plays a sound.''' launcher = self.eI.getGlobal("launcher") if emitter: launcher.sound.playSound(sound, emitter.gameObject) self.events.append( [None, ["SYSTEM", "SOUND_PLAY", [emitter.GUID, sound]]]) else: launcher.sound.playSound(sound) self.events.append([None, ["SYSTEM", "SOUND_PLAY", [None, sound]]]) self.oP("Started sound %s." % sound) def stopSound(self, handle): '''Stops a sound.''' launcher = self.eI.getGlobal("launcher") GUID, sound = launcher.sound.stopSound(handle) self.events.append(["SYSTEM", "SOUND_STOP", [emitter.GUID, sound]]) self.oP("Stopped sound %s." % sound) def stopSoundByGUID(self, GUID, name): '''Stops a sound.''' launcher = self.eI.getGlobal("launcher") GUID, sound = launcher.sound.stopSoundByGUID(GUID, name) self.oP("Stopped sound %s." % sound) self.events.append(["SYSTEM", "SOUND_STOP", [emitter.GUID, sound]]) self.oP("Stopped sound %s." % sound) def playDialog(self, sound, emitter=None): '''Plays a dialog line.''' launcher = self.eI.getGlobal("launcher") if emitter: launcher.sound.playDialog(sound, emitter.gameObject) self.events.append( [None, ["SYSTEM", "DIALOG_PLAY", [emitter.GUID, sound]]]) else: launcher.sound.playDialog(sound) self.events.append( [None, ["SYSTEM", "DIALOG_PLAY", [None, sound]]]) self.oP("Started dialog %s." % sound) def stopDialog(self, handle): '''Stops a dialog line.''' launcher = self.eI.getGlobal("launcher") GUID, sound = launcher.sound.stopDialog(handle) self.events.append(["SYSTEM", "DIALOG_STOP", [emitter.GUID, sound]]) self.oP("Stopped dialog %s." % sound) def stopDialogByGUID(self, GUID, name): '''Stops a dialog line.''' launcher = self.eI.getGlobal("launcher") GUID, sound = launcher.sound.stopDialogByGUID(GUID, name) self.oP("Stopped dialog %s." % sound) self.events.append(["SYSTEM", "DIALOG_STOP", [emitter.GUID, sound]]) self.oP("Stopped dialog %s." % sound) def enableShader(self, index, name, mode): '''Enables a shader as a filter for the entire screen.''' self.sH.enableShader(index, name, mode) def disableShader(self, index): '''Disables a shader that was filtering the entire screen.''' self.sH.disableShader(index) def updateGame(self, key): '''Reacts to changes to the cVars.''' if key == "sv_gamemode" and self.get("sv_game"): self.setGameMode(self.get("sv_gamemode")) elif key == "sv_level" and self.get("sv_game"): self.configure("sv_game", 0) self.configure("sv_game", 1) elif key == "sv_game": if self.get("sv_game"): self.setGameMode(self.get("sv_gamemode")) self.setLevel(self.get("sv_level")) else: self.endGame() elif key == "sv_port" or key == "sv_addr": self.updateNetwork() elif key == "sv_startscript": self.sE.addContext("Server", self) self.sE.execute(self.get("sv_startscript")) elif key in [ "sv_background_red", "sv_background_green", "sv_background_blue", "sv_background_alpha" ] and not self.get("cl_master"): self.eI.setBackgroundColor((self.getBackgroundColor())) elif key == "sv_netlog": if self.get("sv_netlog"): self.nC.configure("DEBUG", True) self.nC.configure("VERBOSE", True) else: self.nC.configure("DEBUG", False) self.nC.configure("VERBOSE", False) elif key == "cl_width" or key == "cl_height": self.eI.setResolution(self.get("cl_width"), self.get("cl_height")) elif key == "cl_fullscreen": self.eI.setFullscreen(self.get("cl_fullscreen")) elif key == "cl_motionblur" or key == "cl_motionblur_amount": self.eI.setMotionBlur(self.get("cl_motionblur"), self.get("cl_motionblur_amount")) elif key == "cl_anisotropic": self.eI.setAnisotropic(self.get("cl_anisotropic")) elif key == "cl_mipmap": self.eI.setMipmapping(self.get("cl_mipmap")) elif key == "cl_vsync": self.eI.setVSync(self.get("cl_vsync")) elif key == "cl_mastervolume": launcher = self.eI.getGlobal("launcher") if launcher: launcher.sound.setMasterVolume(self.get("cl_mastervolume")) elif key == "cl_musicvolume": launcher = self.eI.getGlobal("launcher") if launcher: launcher.sound.setMusicVolume(self.get("cl_musicvolume")) elif key == "cl_dialogvolume": launcher = self.eI.getGlobal("launcher") if launcher: launcher.sound.setDialogVolume(self.get("cl_dialogvolume")) elif key == "cl_soundvolume": launcher = self.eI.getGlobal("launcher") if launcher: launcher.sound.setSoundVolume(self.get("cl_soundvolume")) elif key == "cl_subtitles": launcher = self.eI.getGlobal("launcher") if launcher: launcher.sound.subtitles = self.get("cl_subtitles") elif key == "cl_language": launcher = self.eI.getGlobal("launcher") if launcher: launcher.sound.language = self.get("cl_language") elif key == "cl_netping": self.nC.pingcount = self.get("cl_netping") def getEmergencyUpdate(self, cli): '''Gets a special update to repair desynced clients.''' events = [] for var in self.cvars: if not "cl_" == var[:3]: events.append( [cli, ["SYSTEM", "CVARS", [var, self.cvars[var]]]]) for var in self.netVars: events.append( [cli, ["SYSTEM", "NETVARS", [var, self.netVars[var]]]]) return events def setPlayerCamera(self, cli, GUID): '''Set a client's current camera.''' self.events.append([cli, ["SYSTEM", "SET_CAMERA", GUID]]) if cli: self.oP("Set client %s camera to be %s" % (str(cli.addr), GUID)) else: self.oP("Set all client cameras to be %s" % GUID) def checkServer(self): '''Runs server loops and checks for events.''' events = [] #CVar based events for key in self.cvars.keys(): if not key in self.oldcvars or self.cvars[key] != self.oldcvars[ key]: events.append(["SYSTEM", "CVARS", [key, self.cvars[key]]]) self.oldcvars = self.cvars if self.gameMode: self.gameMode.loop() #Other game events events += self.events self.events = [] return events def sendChatMessage(self, msg, client=None): '''Sends a chat message to the client(s).''' self.sendEvent([client, ["SYSTEM", "CHAT", msg]]) self.chatMessages.append(msg) def sendEvent(self, event): '''Sends an event to the client(s).''' if (event[1][0] == "PHYSICS" and not event[1][1] in ["CREATE", "DELETE"]) or event[1] == "KEEPALIVE": mode = "FAF" else: mode = "RT" #Send global events if event[0] == None: for cli in self.nC.clients: if cli.userProps["confirmed"] or not self.get("sv_password"): cli.send(event[1], mode) #Send one user events else: if event[0].userProps["confirmed"] or not self.get("sv_password"): event[0].send(event[1], mode) def recvEvent(self, cli, event): '''Handles an event from a client.''' if type(event) == type([]) and len(event) >= 3: if event[0] == "INPUT": if event[1] == "COMMAND" or event[1] == "INTERFACE": if cli.userProps["player"]: cli.userProps["player"].pushCommand(event[2]) elif event[0] == "SYSTEM": if event[1] == "PHYSICS": if event[2] == "FORCEUPDATE" and not cli.userProps[ "synced"]: events = self.pR.getEmergencyUpdate(cli) events += self.getEmergencyUpdate(cli) for event in events: self.sendEvent(event) cli.userProps["synced"] = True elif event[1] == "CVARS": if cli.addr[0] == self.get("sv_master"): self.configure(event[2][0], event[2][1]) elif event[1] == "CHAT" and self.get("sv_chat"): self.chatMessages.append(event[2]) self.sendEvent([None, event]) elif event[1] == "NAME": if cli.userProps["player"]: cli.userProps["player"].username = event[2] cli.userProps["username"] = event[2] elif event[1] == "PASSWORD": if event[2] == self.get("sv_password"): cli.userProps["confirmed"] = True elif event[0] == "GAME": self.gameMode.pushGameEvent([event[1], event[2]]) def openSaveFile(self, name): '''Opens the save file.''' try: self.saveFile = shelve.open(SAVE_PATH + name + SAVE_EXT) self.oP("Opened save file %s." % (SAVE_PATH + name + SAVE_EXT)) return True except: self.saveFile = None self.oP("Failed to open save file %s." % (SAVE_PAT + name + SAVE_EXT)) return False def closeSaveFile(self): '''Closes the save file.''' if self.saveFile != None: self.saveFile.close() self.oP("Closed the save file.") self.saveFile = None def saveSaveFile(self): '''Saves the save file.''' if self.saveFile != None: self.oP("Saved the save file.") self.saveFile.sync() def saveState(self): '''Saves the game state.''' self.oP("Saving entity state.") self.openSaveFile("save") if self.saveFile != None: data = Sarcophagus() for ent in self.entities: #if ent.name != "avatar": self.saveEntity(ent, data) for cli in self.nC.clients: if cli.userProps["player"]: self.savePlayer(cli.userProps["player"], data) for player in self.unassignedPlayers: self.savePlayer(player, data) records, playerRecords = data.cleanUp() try: self.saveFile["data"] = data self.oP("Saved data to save file.") except: self.oP("Failed to save data to save file.") self.saveSaveFile() self.closeSaveFile() data.restore(records, playerRecords) for ent in self.entities: #if ent.name != "avatar": data.reconstructEntity(ent) for cli in self.nC.clients: if cli.userProps["player"]: data.reconstructPlayer(cli.userProps["player"]) for player in self.unassignedPlayers: data.reconstructPlayer(player) def loadState(self): '''Loads the game state.''' self.oP("Loading entity state.") self.openSaveFile("save") if self.saveFile != None: if "data" in self.saveFile.keys(): container = self.saveFile["data"] for entry in container.entities: self.loadEntity(entry) for player in container.players: self.loadPlayer(player) self.closeSaveFile() def saveEntity(self, ent, data): '''Saves an Entity to the sarcophagus.''' objData = self.pR.getObjectData(ent) data.deconstructEntity(ent) data.addEntity(ent, objData) def savePlayer(self, player, data): '''Saves a Player to the sarcophagus.''' data.deconstructPlayer(player) data.addPlayer(player) def loadEntity(self, entry): '''Reconstructs an Entity.''' ent = entry[0] ent.reconstructObject(entry[1]) self.oP("Retrieved entity %s from save file." % ent.GUID) self.entities.append(ent) def loadPlayer(self, player): '''Reconstructs a player.''' player.reconstructPlayer(self) self.oP("Retrieved player %s from save file." % player.username) self.unassignedPlayers.append(player) def getOldPlayer(self, name): '''Checks for an unassigned player.''' for player in self.unassignedPlayers: if player.username == name: return player def removeOldPlayer(self, player): '''Removes a player from the unassigned list.''' self.unassignedPlayers.remove(player) def disconnectPlayer(self, cli): '''Handles the disconnection of a player.''' if cli.userProps["player"]: cli.userProps["player"].cli = None self.unassignedPlayers.append(cli.userProps["player"]) def loop(self): '''Does everything basically.''' #cl = OptiClock() #Detector Index self.updateDetectorIndex() #cl.clockIn("DetectorIndex") #KEEP ALIVE self.keepAliveTicker += 1 if self.keepAliveTicker % 600 == 0: self.sendEvent([None, "KEEPALIVE"]) #cl.clockIn("KeepAlive") #RECV THINGS############################################### for cli in self.nC.clients: #Make sure only one client gets through on singleplayer if not self.get("sv_singleplayer") or len(self.nC.clients) <= 1: #Create a player once the username is collected if not cli.userProps["player"] and "username" in cli.userProps: player = self.getOldPlayer(cli.userProps["username"]) if player: self.oP("Client's previous avatar found, reassigning.") cli.userProps["player"] = player player.cli = cli player.reLinkPlayer() self.removeOldPlayer(cli.userProps["player"]) else: self.oP("Client gets a new avatar.") cli.userProps["player"] = Player(self, cli) cli.disconnectFunc = cli.userProps["player"].destruct #If a player has been created elif cli.userProps["player"]: cli.userProps["player"].loop() packet = cli.recv() if packet: payload = packet.getPayload() try: data = eval(payload) except: data = None if data: self.recvEvent(cli, data) #cl.clockIn("RecvLoop") #CHANGE THINGS########################################### #Apply Shaders self.sH.loop() #cl.clockIn("Shaders") #Localize text self.l.loop() #cl.clockIn("Localization") #Entities loop for ent in self.entities: ent.checkPhysics() ent.checkAnimation() if hasattr(ent, "loop"): #print(ent) ent.loop(self, "server") #cl.clockIn("Entities") #Physics Read Loop events = self.pR.loop() #cl.clockIn("Physics") #Self Read Loop events += self.checkServer() #cl.clockIn("GameEvents") #Gamerules Loop if hasattr(self.gameMode, "loop"): self.gameMode.loop() #cl.clockIn("GameMode") #Level loop if self.level and hasattr(self.level, "loop"): self.level.loop(self, "server") #cl.clockIn("Level") #SEND THINGS############################################### #Send Events for event in events: self.sendEvent(event) #cl.clockIn("SendLoop") #KILL THINGS################################################### kill = self.nC.pullKillQueue() if kill and self.gameMode: kill() #cl.clockIn("Kill") self.nC.loop()
def __init__(self, test_run): super(main_window, self).__init__() self.lysing = True # get our experiment variables if test_run != 'True': self.get_experiment_variables() # Set up the user interface self.ui = Ui_MainWindow() self.ui.setupUi(self) # set up the video classes self.vid = ShowVideo(self.ui.verticalLayoutWidget.size()) self.screen_shooter = screen_shooter() self.image_viewer = ImageViewer() # self.autofocuser = autofocuser() self.localizer = Localizer() # add the viewer to our ui self.ui.verticalLayout.addWidget(self.image_viewer) # create our extra threads self.screenshooter_thread = QThread() self.screenshooter_thread.start() self.screen_shooter.moveToThread(self.screenshooter_thread) # self.autofocuser_thread = QThread() # self.autofocuser_thread.start() # self.autofocuser.moveToThread(self.autofocuser_thread) self.localizer_thread = QThread() self.localizer_thread.start() self.localizer.moveToThread(self.localizer_thread) self.video_input_thread = QThread() self.video_input_thread.start() self.vid.moveToThread(self.video_input_thread) # connect the outputs to our signals self.vid.VideoSignal.connect(self.image_viewer.setImage) self.vid.vid_process_signal.connect( self.screen_shooter.screenshot_slot) # self.vid.vid_process_signal.connect(self.autofocuser.vid_process_slot) self.vid.vid_process_signal.connect(self.localizer.vid_process_slot) self.qswitch_screenshot_signal.connect( self.screen_shooter.save_qswitch_fire_slot) self.localizer.qswitch_screenshot_signal.connect( self.screen_shooter.save_qswitch_fire_slot) # self.start_focus_signal.connect(self.autofocuser.autofocus) self.start_localization_signal.connect(self.localizer.localize) # self.autofocuser.position_and_variance_signal.connect(self.plot_variance_and_position) self.image_viewer.click_move_signal.connect(stage.click_move_slot) self.localizer.localizer_move_signal.connect(stage.localizer_move_slot) self.localizer.ai_fire_qswitch_signal.connect( self.ai_fire_qswitch_slot) self.localizer.start_laser_flash_signal.connect( self.start_laser_flash_slot) self.localizer.stop_laser_flash_signal.connect( self.stop_laser_flash_slot) self.vid.reticle_and_center_signal.connect( stage.reticle_and_center_slot) self.vid.reticle_and_center_signal.emit(self.vid.center_x, self.vid.center_y, self.vid.reticle_x, self.vid.reticle_y) # connect to the video thread and start the video self.start_video_signal.connect(self.vid.startVideo) self.start_video_signal.emit() # Screenshot and comment buttons self.ui.misc_screenshot_button.clicked.connect( self.screen_shooter.save_misc_image) self.ui.user_comment_button.clicked.connect(self.send_user_comment) self.ui.noise_filter_checkbox.stateChanged.connect( self.noise_filter_check_changed) # Stage movement buttons self.ui.step_size_doublespin_box.valueChanged.connect( stage.set_step_size) self.setup_combobox() self.localizer.get_position_signal.connect(stage.get_position_slot) stage.position_return_signal.connect( self.localizer.position_return_slot) # Laser control buttons self.ui.qswitch_delay_doublespin_box.valueChanged.connect( laser.set_delay) self.ui.attenuator_doublespin_box.valueChanged.connect( attenuator.set_attenuation) self.ui.cells_to_lyse_doublespin_box.valueChanged.connect( self.localizer.set_cells_to_lyse) self.ui.process_well_pushButton.clicked.connect( self.start_localization) self.show() comment('finished gui init')
class Controller: '''Driver class for controlling tour guide's hybrid paradigm''' def __init__(self): # Initialize ROS node rospy.init_node("Controller") self.name = "Controller object" self.rate = rospy.Rate(10) # allow node to 'spin' at 10hz rospy.on_shutdown(self.shutdown) # calls this function when Ctrl+C self.motion = Motion() self.sensor = Sensor() self.localizer = Localizer() self.visited_highlights = [] # Boolean for reached goal self.goalReached = False def start(self): rospy.loginfo("Starting Tour Guide..") begin = 'q' # Note: the Motion, Sensor, and Localizer classes # seem to take a second to fully initialize so we give # this Controller a second to fully initialize as well rospy.sleep(1) # TODO: here, could we determine if the guide will be # 1) casually walking around, # 2) begin P2P mode, or # 3) begin tour mode? # TODO: for now, it will be 'casually walking around' # TODO: Chris - I was thinking we should just take out 'idle_mode' # for demo purposes. As soon as the program starts, we can ask the user # if they would like a P2P or a regular tour # then go from there # self.idle_mode() # TODO: Chris - I think it will also be easier if we just have the robot # start the tour at its initial position which is at the West Entrance rospy.loginfo("Would you like a P2P tour or a regular tour?") rospy.loginfo("Press a key:") rospy.loginfo("'1': Point To Point") rospy.loginfo("'2': Regular Tour") begin = input() if (begin == 1): self.point_to_point_mode() elif (begin == 2): self.tour_guide_mode() def idle_mode(self): '''Make Turtlebot move around aimlessly and avoid nearby obstacles ''' rospy.loginfo("Initalizing Idle mode.") while not rospy.is_shutdown(): if self.sensor.is_obstacle_detected(): # Rotate Turtlebot accordingly to avoid obstacles self.sensor.avoid_obstacle() else: # If no obstacles detected, no need to rotate self.motion.halt_rotation() self.motion.move_forward() def tour_guide_mode(self): ''' Robot will decide its path/highlights depending on its location''' rospy.loginfo("Initializing Tour Guide mode.") print(self.localizer.position) west_entrance = Locations.WestEntrance east_entrance = Locations.EastEntrance # TODO: just start at nearest entrance and go down the list if self.get_nearest_entrance(west_entrance, east_entrance) == west_entrance: self.localizer.moveToGoal(Locations.WestEntrance) self.localizer.moveToGoal(Locations.Atrium) self.localizer.moveToGoal(Locations.CSOffice) self.localizer.moveToGoal(Locations.ElectronicsLab) self.localizer.moveToGoal(Locations.ComputerLab) self.localizer.moveToGoal(Locations.EastEntrance) else: self.localizer.moveToGoal(Locations.EastEntrance) self.localizer.moveToGoal(Locations.ComputerLab) self.localizer.moveToGoal(Locations.ElectronicsLab) self.localizer.moveToGoal(Locations.Atrium) self.localizer.moveToGoal(Locations.CSOffice) self.localizer.moveToGoal(Locations.WestEntrance) ''' # Go to that highlight self.moveToGoal(nearest_highlight) # Add to "highlights visited" visited_highlights.append(nearest_highlight) # Keep going until all highlights are visited while len(visited_highlights) <= 6: # Calculate next highlight nearest_highlight = self.get_nearest_highlight() # Go to that highlight self.moveToGoal(nearest_highlight) # Add to "highlights visited" visited_highlights.append(nearest_highlight) ''' print( "...And that's all! Thank you for participating in the Devon Tour!" ) def get_nearest_entrance(self, west_entrance, east_entrance): west_entrance_distance = self.distance(west_entrance) east_entrance_distance = self.distance(east_entrance) print("distance to west entrance = " + str(west_entrance_distance)) print("distance to east entrance = " + str(east_entrance_distance)) if west_entrance_distance < east_entrance_distance: return west_entrance else: return east_entrance def distance(self, coordinates): distance = math.sqrt((self.localizer.position.x - coordinates.x)**2 + (self.localizer.position.y - coordinates.y)**2) return distance def point_to_point_mode(self): ''' User chooses which highlights to go to''' choice = self.choose() # Depending on which highlight the user chooses, the robot will # move to the goal if (choice == 1): self.goalReached = self.localizer.moveToGoal(Locations.CSOffice) print( "We've reached the CS Office, where the CS department mainly" + " resides") elif (choice == 2): self.goalReached = self.localizer.moveToGoal(Locations.Atrium) print( "Welcome to the Atrium! This area is used for get-togethers," + "studying, welcome parties, and more!") elif (choice == 3): self.goalReached = self.localizer.moveToGoal( Locations.EastEntrance) print("This is the east entrance") elif (choice == 4): self.goalReached = self.localizer.moveToGoal( Locations.WestEntrance) print("This is the west entrance") elif (choice == 5): self.goalReached = self.localizer.moveToGoal(Locations.ComputerLab) print( "Inside this room here is the CS Computer Lab, where any CS" + " student can come in and use the machines or for TA's office" + " hours") elif (choice == 6): self.goalReached = self.moveToGoal(Locations.ElectronicsLab) print("In this room is the Electronics Lab.") # if choice isn't q and the robot reached its goal if (choice != 'q'): if (self.goalReached): rospy.loginfo("Reached highlight!") # If it fails to reach the goal else: rospy.loginfo("Couldn't reach the highlight, try again") # Loop to keep going until user quits the tour while choice != 'q': choice = self.choose() if (choice == 1): self.goalReached = self.localizer.moveToGoal( Locations.CSOffice) print( "We've reached the CS Office, where the CS department mainly" + " resides") elif (choice == 2): self.goalReached = self.localizer.moveToGoal(Locations.Atrium) print( "Welcome to the Atrium! This area is used for get-togethers," + "studying, welcome parties, and more!") elif (choice == 3): self.goalReached = self.localizer.moveToGoal( Locations.EastEntrance) print("This is the east entrance") elif (choice == 4): self.goalReached = self.localizer.moveToGoal( Locations.WestEntrance) print("This is the west entrance") elif (choice == 5): self.goalReached = self.localizer.moveToGoal( Locations.ComputerLab) print( "Inside this room here is the CS Computer Lab, where any CS" + " student can come in and use the machines or for TA's office" + " hours") elif (choice == 6): self.goalReached = self.localizer.moveToGoal( Locations.ElectronicsLab) print("In this room is the Electronics Lab.") def choose(self): ''' User chooses where they would like to start the tour''' tour = 'q' rospy.loginfo("Initializing P2P Guide mode.") rospy.loginfo("Press a key to go to the highlights:") rospy.loginfo("'1': CS/ECE Office") rospy.loginfo("'2': Atrium") rospy.loginfo("'3': East Entrance") rospy.loginfo("'4': West Entrance") rospy.loginfo("'5': Computer Lab") rospy.loginfo("'6': Electronics Lab") rospy.loginfo("'q': Quit") tour = input() return tour def shutdown(self): '''Shutdown function that's called when user inputs Ctrl + C ''' rospy.loginfo("Stopping Turtlebot") self.motion.halt() rospy.sleep(1) # ensures Turtlebot received the command before def avoid_obstacle(self): '''Checks where a nearby obstacle is and rotates accordingly ''' left_laser = self.sensor.get_left_laser_value() mid_laser = self.sensor.get_mid_laser_value() right_laser = self.sensor.get_right_laser_value() # Check if obstacle in front is 1 ft away if mid_laser <= Distance.FOOT: self.motion.rotate_180() # Check if obstacle is 2 ft to the left elif left_laser < 2 * Distance.FOOT: self.motion.rotate_right() # Check if obstacle is 2 ft to the right elif right_laser < 2 * Distance.FOOT: self.motion.rotate_left()
from PIL import Image from localizer import Localizer from goniometer import Goniometer # TODO: showcase localizer and goniometer # load the best localizer and goniometer # load an image # make a b/w version # use localizer to find resistors # pass the subimages to goniometer to read the angles # get the subimages from the color picture # rotate the subimages back to 0º and output them. localizer = Localizer(filepath='datasets/dataset4/best_model') goniometer = Goniometer(filepath='datasets/dataset5/best_model') image = Image.open('resistors.png') image_bw = Image.convert('F') boxs = localizer.localize(image_bw) for b in boxs
class main_window(QMainWindow): start_video_signal = QtCore.pyqtSignal() qswitch_screenshot_signal = QtCore.pyqtSignal('PyQt_PyObject') start_focus_signal = QtCore.pyqtSignal() start_localization_signal = QtCore.pyqtSignal() def __init__(self, test_run): super(main_window, self).__init__() self.lysing = True # get our experiment variables if test_run != 'True': self.get_experiment_variables() # Set up the user interface self.ui = Ui_MainWindow() self.ui.setupUi(self) # set up the video classes self.vid = ShowVideo(self.ui.verticalLayoutWidget.size()) self.screen_shooter = screen_shooter() self.image_viewer = ImageViewer() # self.autofocuser = autofocuser() self.localizer = Localizer() # add the viewer to our ui self.ui.verticalLayout.addWidget(self.image_viewer) # create our extra threads self.screenshooter_thread = QThread() self.screenshooter_thread.start() self.screen_shooter.moveToThread(self.screenshooter_thread) # self.autofocuser_thread = QThread() # self.autofocuser_thread.start() # self.autofocuser.moveToThread(self.autofocuser_thread) self.localizer_thread = QThread() self.localizer_thread.start() self.localizer.moveToThread(self.localizer_thread) self.video_input_thread = QThread() self.video_input_thread.start() self.vid.moveToThread(self.video_input_thread) # connect the outputs to our signals self.vid.VideoSignal.connect(self.image_viewer.setImage) self.vid.vid_process_signal.connect( self.screen_shooter.screenshot_slot) # self.vid.vid_process_signal.connect(self.autofocuser.vid_process_slot) self.vid.vid_process_signal.connect(self.localizer.vid_process_slot) self.qswitch_screenshot_signal.connect( self.screen_shooter.save_qswitch_fire_slot) self.localizer.qswitch_screenshot_signal.connect( self.screen_shooter.save_qswitch_fire_slot) # self.start_focus_signal.connect(self.autofocuser.autofocus) self.start_localization_signal.connect(self.localizer.localize) # self.autofocuser.position_and_variance_signal.connect(self.plot_variance_and_position) self.image_viewer.click_move_signal.connect(stage.click_move_slot) self.localizer.localizer_move_signal.connect(stage.localizer_move_slot) self.localizer.ai_fire_qswitch_signal.connect( self.ai_fire_qswitch_slot) self.localizer.start_laser_flash_signal.connect( self.start_laser_flash_slot) self.localizer.stop_laser_flash_signal.connect( self.stop_laser_flash_slot) self.vid.reticle_and_center_signal.connect( stage.reticle_and_center_slot) self.vid.reticle_and_center_signal.emit(self.vid.center_x, self.vid.center_y, self.vid.reticle_x, self.vid.reticle_y) # connect to the video thread and start the video self.start_video_signal.connect(self.vid.startVideo) self.start_video_signal.emit() # Screenshot and comment buttons self.ui.misc_screenshot_button.clicked.connect( self.screen_shooter.save_misc_image) self.ui.user_comment_button.clicked.connect(self.send_user_comment) self.ui.noise_filter_checkbox.stateChanged.connect( self.noise_filter_check_changed) # Stage movement buttons self.ui.step_size_doublespin_box.valueChanged.connect( stage.set_step_size) self.setup_combobox() self.localizer.get_position_signal.connect(stage.get_position_slot) stage.position_return_signal.connect( self.localizer.position_return_slot) # Laser control buttons self.ui.qswitch_delay_doublespin_box.valueChanged.connect( laser.set_delay) self.ui.attenuator_doublespin_box.valueChanged.connect( attenuator.set_attenuation) self.ui.cells_to_lyse_doublespin_box.valueChanged.connect( self.localizer.set_cells_to_lyse) self.ui.process_well_pushButton.clicked.connect( self.start_localization) self.show() comment('finished gui init') def get_text(self, text_prompt): text, okPressed = QInputDialog.getText(self, "Experiment Input", text_prompt, QLineEdit.Normal, "") if okPressed and text != None: return text def get_experiment_variables(self): var_dict = { 'stain(s) used:': 'Enter the stain(s) used', 'cell line:': 'Enter the cell line', 'fixative used:': 'Enter the fixative used' } nums = range(10) checks = ['a', 'e', 'i', 'o', 'u'] + [str(num) for num in nums] for key, value in var_dict.items(): good_entry = False while good_entry != True: user_input = self.get_text(var_dict[key]) val = user_input.lower() if any(vowel in val for vowel in checks): comment('{} {}'.format(key, user_input)) good_entry = True def start_autofocus(self): self.start_focus_signal.emit() def start_localization(self): self.start_localization_signal.emit() def noise_filter_check_changed(self, int): if self.ui.noise_filter_checkbox.isChecked(): self.vid.noise_removal = True else: self.vid.noise_removal = False def setup_combobox(self): magnifications = ['4x', '20x', '40x', '60x', '100x'] self.ui.magnification_combobox.addItems(magnifications) self.ui.magnification_combobox.currentIndexChanged.connect( stage.change_magnification) self.ui.cell_type_to_lyse_comboBox.addItems( ['red', 'green', 'green hope']) self.ui.cell_type_to_lyse_comboBox.currentIndexChanged.connect( self.localizer.change_type_to_lyse) self.ui.lysis_mode_comboBox.addItems(['direct', 'excision']) self.ui.lysis_mode_comboBox.currentIndexChanged.connect( self.localizer.change_lysis_mode) def send_user_comment(self): comment('user comment:{}'.format(self.ui.comment_box.toPlainText())) self.ui.comment_box.clear() @QtCore.pyqtSlot() def qswitch_screenshot_slot(self): self.qswitch_screenshot_signal.emit(15) comment('stage position during qswitch: {}'.format( stage.get_position_slot())) laser.fire_qswitch() @QtCore.pyqtSlot('PyQt_PyObject') def ai_fire_qswitch_slot(self, auto_fire): comment('automated firing from localizer!') if auto_fire == True: laser.qswitch_auto() else: laser.fire_qswitch() @QtCore.pyqtSlot() def start_laser_flash_slot(self): laser.fire_auto() @QtCore.pyqtSlot() def stop_laser_flash_slot(self): laser.stop_flash() # def toggle_dmf_or_lysis(self): # # we want to get our objective out of the way first # if self.lysing == True: # ret = self.autofocuser.retract_objective() # if ret == True: # stage.go_to_dmf_location() # elif self.lysing == False: # stage.go_to_lysing_loc() # self.autofocuser.return_objective_to_focus() # self.lysing = not self.lysing def keyPressEvent(self, event): if not event.isAutoRepeat(): print('key pressed {}'.format(event.key())) key_control_dict = { 87: stage.move_up, 65: stage.move_left, 83: stage.move_down, 68: stage.move_right, 66: stage.move_last, 16777249: laser.fire_auto, 70: self.qswitch_screenshot_slot, 81: laser.qswitch_auto, # 73:self.autofocuser.roll_forward, # 75:self.autofocuser.roll_backward, # 79:self.start_autofocus, # 71:self.toggle_dmf_or_lysis, 84: stage.move_left_one_well_slot, 89: stage.move_right_one_well_slot, 96: self.screen_shooter.save_target_image, 16777216: self.localizer.stop_auto_lysis } if event.key() in key_control_dict.keys(): key_control_dict[event.key()]() def keyReleaseEvent(self, event): if not event.isAutoRepeat(): # print('key released: {}'.format(event.key())) key_control_dict = { 16777249: laser.stop_flash, # 73:self.autofocuser.stop_roll, # 75:self.autofocuser.stop_roll } if event.key() in key_control_dict.keys(): key_control_dict[event.key()]() def closeEvent(self, event): self.vid.run_video = False @QtCore.pyqtSlot('PyQt_PyObject') def plot_variance_and_position(self, ituple): positions = ituple[0] variances = ituple[1] plt.plot(positions) plt.plot(variances) plt.legend(['Variance of Laplacian', 'AF Network Output']) plt.xlabel('Position') plt.ylabel('Focus Metric Comparison') plt.show()
'stores them in `./_unlocalized`. If `--yaml` is ' 'also specified, then only the YAML template is ' 'generated.')) parser.add_option('--import', dest='import_html', default=False, action='store_true', help=('Generate Django templates from localized ' 'HTML articles in `./_localized`.')) parser.add_option('--yaml', dest='yaml_infile', default='', help=('Generate localizable template from a specified YAML ' 'file. Output is written to `./[filename].html`')) options = parser.parse_args()[0] if not (options.generate_html or options.import_html): parser.error('You must specify either `--generate` or `--import`.') l7r = Localizer(original_root=Article.ROOT, localized_root=Article.LOCALIZED_ROOT) if options.generate_html and options.yaml_infile: try: l7r.GenerateLocalizableYaml(options.yaml_infile) except YamlProcessorException: parser.error('`%s` couldn\'t be read.' % options.yaml_infile) elif options.generate_html: try: os.mkdir(Article.UNLOCALIZED_ROOT) except OSError: pass l7r.GenerateLocalizableFiles() elif options.import_html: try: os.mkdir(Article.LOCALIZED_ROOT)
# TODO: showcase localizer and goniometer # create a picture # load the best localizer and goniometer # load an image # make a b/w version # use localizer to find resistors # pass the subimages to goniometer to read the angles # get the subimages from the color picture # rotate the subimages back to 0º and output them. # TODO: standarize what kind of arguments each object takes, and be coherent # TODO: test_localizer converts to BW by itself # TODO: goniometer.get_angle() localizer = Localizer(filepath='datasets/dataset4/best_model') goniometer = Goniometer(filepath='datasets/dataset5/best_model') picture_bw = picture.convert('F') resis_boxs = localizer.localize(np.asarray(picture_bw)) plt.show() resis_pics = [] # cropped pictures of the resistors for b in resis_boxs: x1, y1 = b[0], b[1] x2, y2 = b[2], b[3] angle_ind = goniometer.predict(np.asarray(picture_bw)[y1:y2, x1:x2]) angle = goniometer.angle_list[angle_ind[0]] sec = picture.crop((x1, y1, x2, y2)) print(angle)
dataset = 4 imgs_loc = 'datasets/dataset{0}/dataset{0}_imgs.csv'.format(dataset) boxs_loc = 'datasets/dataset{0}/dataset{0}_boxs.csv'.format(dataset) pics = np.genfromtxt(imgs_loc, delimiter=',') boxs = np.genfromtxt(boxs_loc, delimiter=',') # Resize the box lists boxs = boxs.reshape(boxs.shape[0], -1, 4) # dimensions of the whole pictures, constant for now picshape = 240, 240 # height and width # Create the NN model localizer = Localizer(picshape=(240, 240), hidden_layers=(42, 30, 10)) epochs = 20 batch_size = 20 localizer.train(pics, boxs, epochs, batch_size) i = random.randint(0, pics.shape[0] - 1) pic = pics[i, :].reshape(240, 240) utils.test_localizer(localizer, pic, show_probs=True) #print(localizer.predict(pic)) # a hard test, just for fun resistors = Image.open('resistors.png', mode='r') resistors = resistors.convert(mode='F')
# -*- coding: utf-8 -*- import numpy as np import random from PIL import Image import utils from localizer import Localizer from picture_generator import PictureGenerator from keras.utils.np_utils import to_categorical # Create the NN model localizer = Localizer(input_shape=(48, 48), hidden_layers=(42, 30, 10)) # Create the data generator generator = PictureGenerator(batch_size=15, batches_per_epoch=500, return_angles=False, resistor_prob=0.5, real_backgrounds=True, angle_num=8, flatten=False) # Train the model epochs = 10
class Actions(object): """ High level class used by Player to initiate any action that the robot does, including basics: head moves, joint moves, joint scripts (executeMoves) high level moves: change location relative vision and head moves: head tracking, searching, localizing vision and head and body moves: ball kicking We put high level operations in Actions if: * it is an easily specified operation (head scanning) * it is short timed (ball kicking) We will put it in Player instead if: * it is complex, runs for a long time.. (not very well understood) """ verbose = False def __init__(self, eventmanager): self._eventmanager = eventmanager self._world = world = eventmanager._world self.burst_deferred_maker = self._world.burst_deferred_maker # shortcuts to BurstDeferred factory. NOTE: don't get wrapped by BehaviorActions - should they? self.make = self.burst_deferred_maker.make self.wrap = self.burst_deferred_maker.wrap self.succeed = self.burst_deferred_maker.succeed self._motion = world.getMotionProxy() self._speech = world.getSpeechProxy() #self._video = world.getALVideoDeviceProxy() self._imops = world.getImopsProxy() self._current_camera = None # This is based on our commands only - we are the only ones changing it self._current_fps = burst_consts.INITIAL_FRAME_PER_SECOND self._joint_names = self._world.jointnames self._journey = Journey(self) self._movecoordinator = self._world._movecoordinator self.currentCamera = CAMERA_WHICH_BOTTOM_CAMERA self._camera_switch_time = world.time self.tracker = Tracker(self) # Please remember to stop # Todo - Locking self.centerer = Centerer(self) # Please remember to stop self.searcher = Searcher(self) # all of these behaviors self.localizer = Localizer(self) # when you stop the InitialBehavior. Thank you. self.headControllers = [self.tracker, self.centerer, self.searcher] # we keep track of the last head bd self._current_head_bd = self.succeed(self) self._current_motion_bd = self.succeed(self) # slight changes between 1.3.8 and 1.2.0 if is_120: self.setWalkConfig = self.setWalkConfig_120 else: self.setWalkConfig = self.setWalkConfig_138 #=============================================================================== # High Level - anything that uses vision #=============================================================================== # These functions are generally a facade for internal objects, currently: # kicking.Kicker, headtracker.Searcher, headtracker.Tracker @returnsbd # must be first def kickInit(self, target_world_frame=None, side=LEFT): """ Kick the Ball. Returns an already initialized BallKicker instance which can be used to stop the current activity. If target is None it kicks towards the enemy goal (currently the Yellow - TODO). Otherwise target should be a location which will be used to short circuit the scanning process. (caller needs to supply a valid target) Kicking towards a target entails: * if target is default: scan for ball until found (using various strategies) * approach ball using different strategies (far, close) * kick TODO: target can be a robot name, then the kick becomes a pass. This requires being able to detect the location. TODO: have several kick types, one for passing, one for kicking towards goal. """ initkicker = InitialKicker(self, side=side) initkicker.start() return initkicker @returnsbd # must be first def kickBall(self, target_left_right_posts, target_world_frame=None): """ Kick the Ball. Returns an already initialized BallKicker instance which can be used to stop the current activity. If target is None it kicks towards the enemy goal (currently the Yellow - TODO). Otherwise target should be a location which will be used to short circuit the scanning process. (caller needs to supply a valid target) Kicking towards a target entails: * if target is default: scan for ball until found (using various strategies) * approach ball using different strategies (far, close) * kick TODO: target can be a robot name, then the kick becomes a pass. This requires being able to detect the location. TODO: have several kick types, one for passing, one for kicking towards goal. """ ballkicker = BallKicker(self, target_left_right_posts=target_left_right_posts) ballkicker.start() return ballkicker @returnsbd # must be first def runSecondary(self, direction): """ Go to a predefined point and then run kicker depending on the kick off side chosen. Returns an already initialized SecondaryStarter instance which can be used to stop the current activity """ second = SecondaryStarter(self, direction=LEFT) second.start() return second @returnsbd # must be first def passBall(self, target_world_frame=None): passingChallange = passBall(self._eventmanager, self) passingChallange.start() return passingChallange @stopped(['searcher', 'centerer']) @setfps(20) def track(self, target, lostCallback=None): """ Track an object that is seen. If the object is not seen, does nothing. """ return self.tracker.start(target=target, lostCallback=lostCallback) @returnsbd # must be first @stopped(['tracker', 'centerer']) @setfps(20) def search(self, targets, center_on_targets=True, stop_on_first=False): if stop_on_first: return self.searcher.search_one_of(targets, center_on_targets) else: return self.searcher.search(targets, center_on_targets) # TODO: returns centered, maybe_bd - I should wrap this too, but returnsbd # is too inflexible. def executeTracking(self, target, normalized_error_x=0.05, normalized_error_y=0.05, return_exact_error=False): if not all(x.stopped for x in self.headControllers): raise Exception("Can't start searching while tracking") return self.tracker.executeTracking(target, normalized_error_x=normalized_error_x, normalized_error_y=normalized_error_y) @returnsbd # must be first def localize(self): return self.localizer.start() # a Behavior, hence a BurstDeferred #=============================================================================== # Mid Level - any motion that uses callbacks #=============================================================================== @returnsbd # must be first (since other wrappers don't copy the attributes..) @legal_any @setfps(10) def changeLocationRelative(self, delta_x, delta_y = 0.0, delta_theta = 0.0, walk=walks.STRAIGHT_WALK, steps_before_full_stop=0): """ Add an optional addTurn and StraightWalk to ALMotion's queue. Will fire EVENT_CHANGE_LOCATION_DONE once finished. Coordinate frame for robot is same as world: x forward, y left (z up) What kind of walk this is: for simplicity we do a turn, walk, then final turn to wanted angle. @param steps_before_full_stop: Each steps_before_full_stop, the robot will halt, to regain its balance. If the parameter is not set, or is set to 0, the robot will execute its entire journey in one go. """ distance = (delta_x**2 + delta_y**2)**0.5 / 100 # convert cm to meter bearing = atan2(delta_y, delta_x) # TODO: Shouldn't this be the other way around? self._current_motion_bd = self._journey.start(walk=walk, steps_before_full_stop = steps_before_full_stop, delta_theta = delta_theta, distance=distance, bearing=bearing) return self._current_motion_bd @returnsbd # must be first @legal_any @setfps(10) def turn(self, deltaTheta, walk=walks.TURN_WALK): print walk self.setWalkConfig(walk.walkParameters) dgens = [] dgens.append(lambda _: self._motion.setSupportMode(SUPPORT_MODE_DOUBLE_LEFT)) print "ADD TURN (deltaTheta): %f" % (deltaTheta) dgens.append(lambda _: self._motion.addTurn(deltaTheta, walk.defaultSpeed)) duration = 1.0 # TODO - compute duration correctly d = chainDeferreds(dgens) self._current_motion_bd = self._movecoordinator.walk(d, duration=duration, description=('turn', deltaTheta, walk)) return self._current_motion_bd # TODO: Change to walkSideways() @returnsbd # must be first @legal_any @setfps(10) def changeLocationRelativeSideways(self, delta_x, delta_y = 0.0, walk=walks.SIDESTEP_WALK): """ Add an optional addWalkSideways and StraightWalk to ALMotion's queue. Will fire EVENT_CHANGE_LOCATION_DONE once finished. Coordinate frame for robot is same as world: x forward, y left (z up) X & Y are in radians! What kind of walk is this: for simplicity we do sidewalking then walking to target (we assume no orientation change is required) """ print "changeLocationRelativeSideways (delta_x: %3.3f delta_y: %3.3f)" % (delta_x, delta_y) distance, distanceSideways = delta_x / CM_TO_METER, delta_y / CM_TO_METER did_sideways = None dgens = [] # deferred generators. This is the DESIGN PATTERN to collect a bunch of # stuff that would have been synchronous and turn it asynchronous # All lambda's should have one parameter, the result of the last deferred. dgens.append(lambda _: self._motion.setSupportMode(SUPPORT_MODE_DOUBLE_LEFT)) # if abs(distanceSideways) >= MINIMAL_CHANGELOCATION_SIDEWAYS: # walk = walks.SIDESTEP_WALK dgens.append(lambda _: self.setWalkConfig(walk.walkParameters)) defaultSpeed = walk.defaultSpeed stepLength = walk[WalkParameters.StepLength] if distance >= MINIMAL_CHANGELOCATION_X: print "WALKING STRAIGHT (stepLength: %3.3f distance: %3.3f defaultSpeed: %3.3f)" % (stepLength, distance, defaultSpeed) #dgens.append(lambda _: self._motion.addWalkStraight( distance, defaultSpeed )) # Vova trick - start with slower walk, then do the faster walk. slow_walk_distance = min(distance, stepLength*2) if walks.FIRST_TWO_SLOW_STEPS and World.connected_to_nao: dgens.append(lambda _: self._motion.addWalkStraight( slow_walk_distance, DEFAULT_SLOW_WALK_STEPS )) dgens.append(lambda _: self._motion.addWalkStraight( distance - slow_walk_distance, defaultSpeed )) else: print "ADD WALK STRAIGHT: %f, %f" % (distance, defaultSpeed) dgens.append(lambda _: self._motion.addWalkStraight( distance, defaultSpeed )) # When asked to do side-stepping for a very short distance, do a minimal one if abs(distanceSideways) <= MINIMAL_CHANGELOCATION_SIDEWAYS: print "MINOR SIDEWAYS MOVEMENT ENLARGED! (%3.3f)" % distanceSideways if distanceSideways < 0: distanceSideways = -MINIMAL_CHANGELOCATION_SIDEWAYS else: distanceSideways = MINIMAL_CHANGELOCATION_SIDEWAYS print "WALKING SIDEWAYS (%3.3f)" % distanceSideways did_sideways = distanceSideways dgens.append(lambda _: self._motion.addWalkSideways(distanceSideways, defaultSpeed)) duration = (defaultSpeed * distance / stepLength + (did_sideways and defaultSpeed or self._eventmanager.dt) ) * 0.02 # 20ms steps print "Estimated duration: %3.3f" % (duration) d = chainDeferreds(dgens) self._current_motion_bd = self._movecoordinator.walk(d, duration=duration, description=('sideway', delta_x, delta_y, walk.name)) return self._current_motion_bd @returnsbd # must be first @legal_any @setfps(10) def changeLocationArc(self, delta_x, delta_y, walk=walks.STRAIGHT_WALK): #handle divide by zero if delta_y==0: return self.changeLocationRelativeSideways(delta_x, delta_y, walk) #calculate radius #r=((y{-,+}r)**2 + x**2)**0.5 #0= y**2 + r**2 {+/-}y*r*2 + x**2 - r**2 #r=abs( (y**2 + x**2) / (2*y) ) r= abs( delta_y/2 + (delta_x**2)/(2*delta_y) ) #sin angle = y/r angle = asin(delta_x/r) if delta_y<0: angle=-angle #print "Calculated radius: %f, calculated angle %f" % (r, angle) # TODO: Handle addWalkArc limitations (min/max radius) # TODO: Move to journey.py (???) dgens = [] # deferred generators. This is the DESIGN PATTERN to collect a bunch of # stuff that would have been synchronous and turn it asynchronous # All lambda's should have one parameter, the result of the last deferred. dgens.append(lambda _: self._motion.setSupportMode(SUPPORT_MODE_DOUBLE_LEFT)) dgens.append(lambda _: self.setWalkConfig(walk.walkParameters)) defaultSpeed = walk.defaultSpeed # give radius in meters!!! dgens.append(lambda _: self._motion.addWalkArc( angle, r / 100. , defaultSpeed )) # TODO: Calculate arc length to get possible duration (by arc_length/speed) duration = 10 d = chainDeferreds(dgens) self._current_motion_bd = self._movecoordinator.walk(d, duration=duration, description=('arc', delta_x, delta_y, walk.name)) return self._current_motion_bd @returnsbd # must be first @legal_any def sitPoseAndRelax(self): # TODO: This appears to be a blocking function! self._current_motion_bd = self.wrap(self.sitPoseAndRelax_returnDeferred(), data=self) return self._current_head_bd def sitPoseAndRelax_returnDeferred(self): # TODO: This appears to be a blocking function! dgens = [] def removeStiffness(_): if burst.options.debug: print "sitPoseAndRelax: removing body stiffness" return self._motion.setBodyStiffness(0) dgens.append(lambda _: self._clearFootsteps_returnDeferred()) #dgens.append(lambda _: self.executeMove(poses.STAND).getDeferred()) dgens.append(lambda _: self.executeMove(poses.SIT_POS).getDeferred()) dgens.append(removeStiffness) return chainDeferreds(dgens) def setWalkConfig_120(self, param): """ param should be one of the walks.WALK_X """ (ShoulderMedian, ShoulderAmplitude, ElbowMedian, ElbowAmplitude, LHipRoll, RHipRoll, HipHeight, TorsoYOrientation, StepLength, StepHeight, StepSide, MaxTurn, ZmpOffsetX, ZmpOffsetY) = param[:] # XXX we assume the order of these configs doesn't matter, hence the # DeferredList - does it? ds = [] ds.append(self._motion.setWalkArmsConfig( ShoulderMedian, ShoulderAmplitude, ElbowMedian, ElbowAmplitude )) ds.append(self._motion.setWalkArmsEnable(True)) # LHipRoll(degrees), RHipRoll(degrees), HipHeight(meters), TorsoYOrientation(degrees) ds.append(self._motion.setWalkExtraConfig( LHipRoll, RHipRoll, HipHeight, TorsoYOrientation )) ds.append(self._motion.setWalkConfig( StepLength, StepHeight, StepSide, MaxTurn, ZmpOffsetX, ZmpOffsetY )) return DeferredList(ds) def setWalkConfig_138(self, param): """ param should be one of the walks.WALK_X """ # 1.3.8: we currently plan to use the defaults of the new TrapezoidConfig: [5.0, -5.0] # default walk config is : [0.035, 0.01, 0.025, 0.2, 0.23, 3.0] # help said: pHipHeight must be in [0.15f 0.244f] (ShoulderMedian, ShoulderAmplitude, ElbowMedian, ElbowAmplitude, LHipRoll, RHipRoll, HipHeight, TorsoYOrientation, StepLength, StepHeight, StepSide, MaxTurn, ZmpOffsetX, ZmpOffsetY) = param[:] # XXX we assume the order of these configs doesn't matter, hence the # DeferredList - does it? ds = [] ds.append(self._motion.setWalkArmsConfig( ShoulderMedian, ShoulderAmplitude, ElbowMedian, ElbowAmplitude )) ds.append(self._motion.setWalkArmsEnable(True)) ds.append(self._motion.setWalkTrapezoidConfig(LHipRoll, RHipRoll)) ds.append(self._motion.setWalkConfig( StepLength, StepHeight, StepSide, MaxTurn, HipHeight, TorsoYOrientation )) return DeferredList(ds) @returnsbd @legal_head def chainHeads(self, moves): """ chain a number of headMoves, return a burstdeferred on the last move. Useful for debugging, or just for sign language. see nodtester.py """ assert(len(moves) > 0) bd = self.moveHead(*moves[0]) for move in moves[1:]: bd = bd.onDone(lambda _, move=move: self.moveHead(*move)) return bd #=============================================================================== # Low Level #=============================================================================== def switchToTopCamera(self): return self.succeed(self) #return self.setCamera(CAMERA_WHICH_TOP_CAMERA) def switchToBottomCamera(self): return self.succeed(self) #return self.setCamera(CAMERA_WHICH_BOTTOM_CAMERA) @returnsbd # must be first (doesn't add to call stack) # @whocalledme_outofclass def setCamera(self, whichCamera, force=False): """ Set camera used, we have two: top and bottom. whichCamera in [burst_consts.CAMERA_WHICH_TOP_CAMERA, burst_consts.CAMERA_WHICH_BOTTOM_CAMERA] """ # Switching camera's doesn't always work. So we need to actually check for it. # Not sure if this is a webots problem or not, but assuming it isn't webots. return self.succeed(self) def this_doesnt_exist(self): if self._current_camera == whichCamera and not force: return self.succeed(self) dt_since_last = self._world.time - self._camera_switch_time delay = False if dt_since_last < burst_consts.CAMERA_SWITCH_SINCE_LAST_WAIT: print "_"*20 + "Delaying camera switch" + "_"*20 delay = True self._camera_switch_time = self._world.time if whichCamera == CAMERA_WHICH_BOTTOM_CAMERA: s, switcher = 'bottom', self._imops.switchToBottomCamera else: s, switcher = 'top', self._imops.switchToTopCamera print ("_"*20 + "%3.2f: SWITCHING TO %s CAMERA in %3.2f secs (delta %3.2f)" % ( self._world.time, s, burst_consts.CAMERA_SWITCH_ON_SWITCH_WAIT, dt_since_last) + '_'*20) #import time # time.sleep(0.5) # HACK because of switching problem. self._current_camera = whichCamera bd = self.make(self) def onSwitchChilldownComplete(): # called when CAMERA_SWITCH_ON_SWITCH_WAIT time has passed since switcher() called #print "Actions: FINALLY %3.2f" % self._world.time bd.callOnDone() def doSwitch(): # called when CAMERA_SWITCH_SINCE_LAST_WAIT - dt_since_last time has passed self.wrap(switcher(), data=self).onDone(lambda: self._eventmanager.callLater(burst_consts.CAMERA_SWITCH_ON_SWITCH_WAIT, onSwitchChilldownComplete)) if delay: self._eventmanager.callLater( burst_consts.CAMERA_SWITCH_SINCE_LAST_WAIT - dt_since_last, doSwitch) else: doSwitch() return bd @returnsbd # must be first def setCameraFrameRate(self, fps): if self._current_fps == fps: return self._current_fps = fps print "_"*20 + "SETTING FPS TO %s" % fps + "_"*20 bd = self.make(self) self._eventmanager.updateTimeStep(1.0/fps) # convert number of frames per second to dt self._imops.setFramesPerSecond(float(fps)).addCallback(lambda _: bd.callOnDone()).addErrback(log.err) return bd def changeHeadAnglesRelative(self, delta_yaw, delta_pitch, interp_time = 0.15): cur_yaw, cur_pitch = self._world.getAngle("HeadYaw"), self._world.getAngle("HeadPitch") yaw, pitch = cur_yaw + delta_yaw, cur_pitch + delta_pitch if burst.options.debug: print "changeHeadAnglesRelative: %1.2f+%1.2f=%1.2f, %1.2f+%1.2f=%1.2f" % ( cur_yaw, delta_yaw, yaw, cur_pitch, delta_pitch, pitch) return self.executeHeadMove( (((yaw, pitch),interp_time),) ) def changeHeadAnglesRelativeChained(self, delta_yaw, delta_pitch): if burst.options.debug: print "changeHeadAnglesRelativeChained: delta_yaw %1.2f, delta_pitch %1.2f" % (delta_yaw, delta_pitch) return self._movecoordinator.changeChainAngles("Head", [delta_yaw, delta_pitch]) # Kick type - one of the kick types defined in actionconsts KICK_TYPE_STRAIGHT/KICK_TYPE_PASSING/etc... # Kick leg - the leg used to kick # Kick strength - strength of the kick (between 0..1) @setfps(10) def kick(self, kick_type, kick_leg, kick_dist): # TODO: Add support for kick_type/kick_leg tuple, along with kick_strength # OLDER KICKING (not including passing) #return self.executeMove(KICK_TYPES[(kick_type, kick_leg)], # description=('kick', kick_type, kick_leg, kick_strength)) # FOR PASSING: originalKick = KICK_TYPES[(kick_type, kick_leg)] orig_value = originalKick[4][4] if kick_dist > 0: kick_dist = kick_dist / 100 originalKick[4][4] = self.getSpeedFromDistance(kick_dist) bd = self.executeMove(originalKick) originalKick[4][4] = orig_value return bd @setfps(10) def inside_kick(self, kick_type, kick_leg): return self.executeMove(KICK_TYPES[(kick_type, kick_leg)]) @setfps(10) def adjusted_straight_kick(self, kick_leg, kick_side_offset=1.0): if kick_leg==LEFT: return self.executeMove(poses.getGreatKickLeft(kick_side_offset), description=('kick', 'ADJUSTED_KICK', kick_leg, 1.0, kick_side_offset)) else : return self.executeMove(poses.getGreatKickRight(kick_side_offset), description=('kick', 'ADJUSTED_KICK', kick_leg, 1.0, kick_side_offset)) @legal_any @setfps(10) def executeMoveChoreograph(self, (jointCodes, angles, times), whatmove): self._current_motion_bd = self._movecoordinator.doMove(jointCodes, angles, times, 1, description=('choreograph', whatmove)) return self._current_motion_bd
class Client(GameSide): def __init__(self): '''Initializes the client.''' self.mode = "client" self.oP = OutPipe("Client", 0) self.eI = EngineInterface(objectMode=True) self.vP = VideoPlayer() self.sE = ScriptExecuter() self.iR = InputReceiver() self.l = Localizer(self) self.pA = PhysicsApplicator(self) self.sH = ShaderHandler() self.nC = None self.sE.addContext("Client", self) self.cvars = { #Low level settings "cl_update": 1, "cl_synced": 0, "cl_addr": "0.0.0.0", "cl_oport": 7777, "cl_iport": 7778, "cl_netlog": 0, "cl_game": 0, "cl_startscript": "", "cl_master": 0, "cl_predict": 1, "cl_smooth": 0, "cl_name": "Player", "cl_password": "", "cl_camera": "", "cl_lockcontrols": 1, "cl_showmouse": 1, "cl_xsens": 50, "cl_ysens": 50, "cl_inverted": 0, "cl_netping": 0, #High level settings "cl_language": "en", "cl_subtitles": 1, "cl_width": 1280, "cl_height": 720, "cl_fullscreen": 0, "cl_motionblur": 0, "cl_motionblur_amount": 0, "cl_anisotropic": 1, "cl_mipmap": "none", "cl_vsync": "off", "cl_musicvolume": 10, "cl_dialogvolume": 10, "cl_soundvolume": 10, "cl_mastervolume": 10, #Server shared settings "sv_level": "", "sv_gamemode": "", "sv_game": 0, "sv_background_red": 0, "sv_background_green": 0, "sv_background_blue": 0, "sv_background_alpha": 0, } self.netVars = {} self.chatMessages = [] self.interfaces = [] self.entities = [] self.level = None self.gameEvents = [] self.updateNetwork() #self.startLoop() self.forceUpdateCVars() self.keepAliveTicker = 0 self.trackedProperties = [] loadClient(self) self.oP("Initialized.") def forceUpdateCVars(self): '''Forces all the cVars to run their updaters as though they had just been set.''' for key in self.cvars.keys(): if not "sv_" == key[:3]: self.configure(key, self.get(key), override=True) self.oP("Force updated cVars.") def configure(self, key, val, fromServer=False, override=False): '''Configure a cVar.''' changed = False if key in self.cvars.keys() and (not "sv_" == key[:3] or fromServer): #Switch for int if type(self.cvars[key]) == type(0): val = int(val) #Used for functions if type(self.cvars[key]) == type(self.configure): self.cvars[key](val) self.oP("CVar %s executed." % key) else: if val != self.cvars[key] or override: changed = True self.cvars[key] = val self.oP("CVar %s configured to %s (%s)." % (key, val, str(type(val)).replace( "<class '", "").replace("'>", ""))) elif "sv_" == key[:3] and not fromServer and key in self.cvars.keys( ) and self.cvars[key] != val: self.sendEvent(["SYSTEM", "CVARS", [key, val]]) self.oP("Asking server to change CVar %s." % key) else: self.oP("CVar %s not present." % key) if changed: self.updateGame(key) def connectGame(self): '''Connects to a game.''' self.oP("Connecting to game.") self.nC.connect((self.get("cl_addr"), self.get("cl_oport"))) self.configure("cl_game", 1) self.configure("cl_synced", 0) def disconnectGame(self): '''Disconnects from a game.''' self.oP("Disconnecting from a game.") self.updateNetwork() self.configure("cl_game", 0) self.configure("cl_synced", 0) self.configure("cl_update", 1) self.oP("Disconnected from game.") def updateGame(self, key): '''Reacts to changes to the cVars.''' if key == "cl_startscript": self.sE.addContext("Client", self) self.sE.execute(self.get("cl_startscript")) elif key in ["cl_iport"]: self.updateNetwork() elif key == "cl_addr": if self.get("cl_addr") == "0.0.0.0": self.configure("cl_addr", "127.0.0.1") elif key == "cl_name": self.sendEvent(["SYSTEM", "NAME", self.get("cl_name")]) elif key == "sv_level" and not self.get("cl_master"): if self.get("sv_game"): self.setLevel(self.get("sv_level")) elif key == "sv_game" and not self.get("cl_master"): if self.get("sv_game"): self.setLevel(self.get("sv_level")) else: self.endLevel() elif key in [ "sv_background_red", "sv_background_green", "sv_background_blue", "sv_background_alpha" ] and not self.get("cl_master"): self.eI.setBackgroundColor((self.getBackgroundColor())) elif key == "cl_width" or key == "cl_height": self.eI.setResolution(self.get("cl_width"), self.get("cl_height")) elif key == "cl_fullscreen": self.eI.setFullscreen(self.get("cl_fullscreen")) elif key == "cl_motionblur" or key == "cl_motionblur_amount": self.eI.setMotionBlur(self.get("cl_motionblur"), self.get("cl_motionblur_amount")) elif key == "cl_anisotropic": self.eI.setAnisotropic(self.get("cl_anisotropic")) elif key == "cl_mipmap": self.eI.setMipmapping(self.get("cl_mipmap")) elif key == "cl_vsync": self.eI.setVSync(self.get("cl_vsync")) elif key == "cl_camera" and self.get("cl_camera") != "": self.eI.setCamera(self.get("cl_camera")) elif key == "cl_mastervolume": launcher = self.eI.getGlobal("launcher") if launcher: launcher.sound.setMasterVolume(self.get("cl_mastervolume")) elif key == "cl_musicvolume": launcher = self.eI.getGlobal("launcher") if launcher: launcher.sound.setMusicVolume(self.get("cl_musicvolume")) elif key == "cl_dialogvolume": launcher = self.eI.getGlobal("launcher") if launcher: launcher.sound.setDialogVolume(self.get("cl_dialogvolume")) elif key == "cl_soundvolume": launcher = self.eI.getGlobal("launcher") if launcher: launcher.sound.setSoundVolume(self.get("cl_soundvolume")) elif key == "cl_subtitles": launcher = self.eI.getGlobal("launcher") if launcher: launcher.sound.subtitles = self.get("cl_subtitles") elif key == "cl_language": launcher = self.eI.getGlobal("launcher") if launcher: launcher.sound.language = self.get("cl_language") elif key == "cl_lockcontrols": self.iR.locked = self.get("cl_lockcontrols") elif key == "cl_showmouse": self.eI.setMouseState(self.get("cl_showmouse")) elif key == "cl_xsens": self.iR.xsens = self.get("cl_xsens") elif key == "cl_ysens": self.iR.ysens = self.get("cl_ysens") elif key == "cl_inverted": self.iR.inverted = self.get("cl_inverted") elif key == "cl_predict": self.iR.predict = self.get("cl_predict") if not self.get("cl_predict"): for GUID in self.pA.blacklistedGUIDs: self.removeFromRotationBlacklist(GUID) elif key == "cl_smooth": self.pA.smooth = self.get("cl_smooth") elif key == "cl_netlog": if self.get("cl_netlog"): self.nC.configure("DEBUG", True) self.nC.configure("VERBOSE", True) else: self.nC.configure("DEBUG", False) self.nC.configure("VERBOSE", False) elif key == "cl_netping": self.nC.pingcount = self.get("cl_netping") def updateNetwork(self): '''Update the network module for changes to port or addr''' self.purgeNetwork() self.nC = NetCore() if self.get("cl_netlog"): self.nC.configure("DEBUG", True) self.nC.configure("VERBOSE", True) else: self.nC.configure("DEBUG", False) self.nC.configure("VERBOSE", False) self.nC.pingcount = self.get("cl_netping") self.nC.configure("NAME", "Client") self.nC.setProtocol("UDP") self.nC.configure("PORT", self.get("cl_iport")) self.nC.initialize() def purgeNetwork(self): '''Destroys the NetCore once and for all.''' if self.nC: self.nC.clear() self.nC.destroy() self.nC = None def startGameRemote(self): '''Used to connect to another person's game.''' self.oP("Starting game (remote)...") self.configure("cl_master", 0) self.configure("cl_update", 1) self.configure("cl_predict", 1) self.connectGame() def startGameFull(self): '''Used if you want the lobby when you start up a game.''' self.oP("Starting game (full)...") self.configure("cl_master", 1) self.configure("cl_update", 0) self.configure("cl_predict", 0) launcher = self.eI.getGlobal("launcher") if launcher: launcher.bootServer() self.oP("Booted server from client (Full).") self.configure("cl_addr", launcher.s.get("sv_addr")) self.connectGame() def startGameFast(self, level, gamemode, singleplayer=True): '''Used if you want to go straight to the game, usually used for singleplayer.''' self.oP("Starting game (fast)...") self.configure("cl_master", 1) self.configure("cl_update", 0) self.configure("cl_predict", 0) self.configure("cl_game", 1) self.updateNetwork() launcher = self.eI.getGlobal("launcher") if launcher: launcher.bootServer() self.oP("Booted server from client (Fast).") launcher.s.configure("sv_level", level) launcher.s.configure("sv_gamemode", gamemode) launcher.s.configure("sv_game", 1) if singleplayer: launcher.s.configure("sv_singleplayer", 1) else: launcher.s.configure("sv_singleplayer", 0) self.configure("cl_addr", launcher.s.get("sv_addr")) self.connectGame() def endGame(self): '''Ends the game instance and disconnects.''' self.oP("Ending game session...") self.disconnectGame() self.endLevel() launcher = self.eI.getGlobal("launcher") if launcher and self.get("cl_master") and launcher.s: launcher.s.quitGame() launcher.s = None def quitGame(self): '''Quits the game completely.''' self.oP("Shutting down...") self.endGame() self.purgeNetwork() self.eI.quitGame() def setMusic(self, music): '''Sets the music track.''' launcher = self.eI.getGlobal("launcher") launcher.sound.playMusic(music) self.oP("Set music to %s." % music) def stopMusic(self): '''Stops the music track.''' launcher = self.eI.getGlobal("launcher") launcher.sound.stopMusic() self.oP("Stopped music.") def playSound(self, sound, emitter=None): '''Plays the sound.''' launcher = self.eI.getGlobal("launcher") if emitter: launcher.sound.playSound(sound, emitter.gameObject) else: launcher.sound.playSound(sound) self.oP("Started playing sound %s." % sound) def stopSound(self, handle): '''Stops a sound.''' launcher = self.eI.getGlobal("launcher") GUID, name = launcher.sound.stopSound(handle) self.oP("Stopped sound %s." % name) def stopSoundByGUID(self, GUID, name): '''Stops a sound.''' launcher = self.eI.getGlobal("launcher") launcher.sound.stopSoundByGUID(GUID, name) self.oP("Stopped sound %s." % name) def playDialog(self, sound, emitter): '''Plays a dialog line.''' launcher = self.eI.getGlobal("launcher") if emitter: launcher.sound.playDialog(sound, emitter.gameObject) else: launcher.sound.playDialog(sound) self.oP("Playing dialog %s." % sound) def stopDialog(self, handle): '''Stops a dialog line.''' launcher = self.eI.getGlobal("launcher") GUID, name = launcher.sound.stopDialog(handle) self.oP("Stopped dialog %s." % name) def stopDialogByGUID(self, GUID, name): '''Stops a dialog line.''' launcher = self.eI.getGlobal("launcher") launcher.sound.stopDialogByGUID(GUID, name) self.oP("Stopped dialog %s." % name) def enableShader(self, index, name, mode): '''Enables a shader as a filter for the entire screen.''' self.sH.enableShader(index, name, mode) def disableShader(self, index): '''Disables a shader that was filtering the entire screen.''' self.sH.disableShader(index) def playVideo(self, video): '''Plays a video.''' self.vP.playVideo(video) self.oP("Started video %s." % video) def stopVideo(self): '''Stops a video.''' self.vP.stopVideo() self.oP("Stopped video.") def replaceMesh(self, ent, meshName): '''Replaces the mesh of an Entity.''' cR = self.load("Mesh", meshName) name = cR.get("name") resourcePath = cR.get("resourcePath") self.loadLibrary("Mesh", resourcePath, mesh=True) ent.gameObject.replaceMesh(meshName, True, True) self.oP("Replaced mesh of %s with %s." % (ent.GUID, meshName)) def addInterface(self, name): '''Adds an interface.''' if not self.getInterfaceByName(name): cR = self.load("UI", name) name = cR.get("name") resource = cR.get("resourcePath") scriptName = cR.get("scriptPath") #self.loadLibrary("UI", resource) self.oP("Creating interface %s." % name) self.interfaces.append(Interface(name, resource, scriptName)) else: self.oP("Interface %s already exists, not created." % name) def removeInterface(self, name): '''Removes an interface.''' interface = self.getInterfaceByName(name) if interface: self.oP("Removing interface %s." % name) self.interfaces.remove(interface) interface.kill() def removeAllInterfaces(self): '''Removes all interfaces.''' self.oP("Removing all interfaces.") names = [] for interface in self.interfaces: names.append(interface.name) for name in names: self.removeInterface(name) def getInterfaceByName(self, name): '''Gets an interface by name.''' for interface in self.interfaces: if interface.name == name: return interface def addMarker(self, name, GUID): '''Adds a marker tracking the specified Entity.''' cR = self.load("UI", name) name = cR.get("name") resource = cR.get("resourcePath") self.eI.getGlobal("addToWaypoints")(resource, name, GUID) self.oP("Added waypoint %s tracking %s." % (name, GUID)) def removeMarker(self, GUID): '''Removes all markers tracking an Entity.''' for obj in self.eI.getWaypointsScene().objects: if "targetGUID" in obj and obj["targetGUID"] == GUID: obj.endObject() self.oP("Removed waypoints tracking %s." % GUID) def inputClick(self, keyCode, pos): '''Checks for the interface clicks.''' obj, scene = self.eI.getMouseOverObjectScene(pos) if obj and scene: for interface in self.interfaces: if interface.name == self.eI.getTerminalParent(obj).name: interface.onClick(obj.name) return True for i in self.entities: if obj == i.gameObject or obj in i.gameObject.childrenRecursive: i.onClick(obj.name) return True return False def getDisconnectReaction(self): '''Gets the reaction function for disconnecting from the server.''' self.sE.execute(NETSCRIPT_PATH + "disconnect") return self.disconnectReaction def addToRotationBlacklist(self, GUID): '''Adds a GUID to the rotation blacklist.''' if not GUID in self.pA.blacklistedGUIDs: self.pA.blacklistedGUIDs.append(GUID) def removeFromRotationBlacklist(self, GUID): '''Removes a GUID from the rotation blacklist.''' if GUID in self.pA.blacklistedGUIDs: self.pA.blacklistedGUIDs.remove(GUID) def sendInterfaceEvent(self, event, aux=None): '''Sends an interface event.''' self.sendEvent(["INPUT", "INTERFACE", [event, aux]]) def sendChatMessage(self, msg): '''Sends a chat message.''' self.sendEvent(["SYSTEM", "CHAT", msg]) def sendGameEvent(self, mode, data): '''Sends a game event.''' self.sendEvent(["GAME", mode, data]) def sendEvent(self, event): '''Sends an event to the server.''' if event[0] == "INPUT" or event == "KEEPALIVE": mode = "FAF" elif event[0] in ["SYSTEM", "GAME", "NETWORK"]: mode = "RT" if self.nC.clients: server = self.nC.clients[0] server.send(event, mode) def recvEvent(self, event): '''Handles an event from the server.''' if event[0] == "PHYSICS" and self.get("cl_update"): self.pA.update(event) if event[0] == "SYSTEM": if event[1] == "CVARS": self.configure(event[2][0], event[2][1], fromServer=True) elif event[1] == "NETVARS": self.netVars[event[2][0]] = event[2][1] elif event[1] == "SOUND_PLAY" and self.get("cl_update"): entity = self.getEntityByGUID(event[2][0]) self.playSound(event[2][1], entity) elif event[1] == "SOUND_STOP" and self.get("cl_update"): self.stopSoundByGUID(event[2][0], event[2][1]) elif event[1] == "DIALOG_PLAY" and self.get("cl_update"): entity = self.getEntityByGUID(event[2][0]) self.playDialog(event[2][1], entity) elif event[1] == "DIALOG_STOP" and self.get("cl_update"): self.stopDialogByGUID(event[2][0], event[2][1]) elif event[1] == "MUSIC_PLAY" and self.get("cl_update"): self.setMusic(event[2][0]) elif event[1] == "MUSIC_STOP" and self.get("cl_update"): self.stopMusic() elif event[1] == "SET_CAMERA": self.configure("cl_camera", event[2]) elif event[1] == "INTERFACE_CREATE": self.addInterface(event[2]) elif event[1] == "INTERFACE_REMOVE": self.removeInterface(event[2]) elif event[1] == "CHAT": self.chatMessages.append(event[2]) def loop(self): '''Does everything basically.''' #cl = OptiClock() #Detector Index if not self.get("cl_master"): self.updateDetectorIndex() #cl.clockIn("DetectorIndex") #KEEP ALIVE self.keepAliveTicker += 1 if self.keepAliveTicker % 600 == 0: self.sendEvent("KEEPALIVE") #cl.clockIn("KeepAlive") #Do Things####################### #Read in controls self.iR.checkControls() #cl.clockIn("Input") #Update Video Player self.vP.loop() #cl.clockIn("VideoPlayer") if self.get("cl_update"): #Update localization self.l.loop() #cl.clockIn("Localization") #Apply shaders self.sH.loop() #cl.clockIn("Shaders") #Run object code for ent in self.entities: if hasattr(ent, "loop"): ent.checkAnimation() ent.loop(self, "client") #Run interface code #cl.clockIn("Entities") if self.level: if hasattr(self.level, "loop"): self.level.loop(self, "client") #cl.clockIn("Level") for interface in self.interfaces: if hasattr(interface, "loop"): try: interface.loop() except: pass #cl.clockIn("Interface") if self.nC: #Send Things##################### for key in self.iR.keyEvents: self.sendEvent(key) for event in self.gameEvents: self.sendEvent(event) self.gameEvents = [] self.iR.keyEvents = [] #cl.clockIn("SendLoop") #Recv Things##################### if self.nC.clients: server = self.nC.clients[0] packet = server.recv() if packet: payload = packet.getPayload() try: data = eval(payload) except: data = None if data: self.recvEvent(data) #cl.clockIn("RecvLoop") #Initial sync if self.nC.clients: server = self.nC.clients[0] if not self.get("cl_synced"): server.disconnectFunc = self.getDisconnectReaction() self.sendEvent(["SYSTEM", "NAME", self.get("cl_name")]) self.sendEvent( ["SYSTEM", "PASSWORD", self.get("cl_password")]) self.sendEvent(["SYSTEM", "PHYSICS", "FORCEUPDATE"]) self.configure("cl_synced", 1) #cl.clockIn("Sync") #KILL THINGS################################################### kill = self.nC.pullKillQueue() if kill: kill() #cl.clockIn("Kill") self.nC.loop()
def __init__(self): '''Initializes the client.''' self.mode = "client" self.oP = OutPipe("Client", 0) self.eI = EngineInterface(objectMode=True) self.vP = VideoPlayer() self.sE = ScriptExecuter() self.iR = InputReceiver() self.l = Localizer(self) self.pA = PhysicsApplicator(self) self.sH = ShaderHandler() self.nC = None self.sE.addContext("Client", self) self.cvars = { #Low level settings "cl_update": 1, "cl_synced": 0, "cl_addr": "0.0.0.0", "cl_oport": 7777, "cl_iport": 7778, "cl_netlog": 0, "cl_game": 0, "cl_startscript": "", "cl_master": 0, "cl_predict": 1, "cl_smooth": 0, "cl_name": "Player", "cl_password": "", "cl_camera": "", "cl_lockcontrols": 1, "cl_showmouse": 1, "cl_xsens": 50, "cl_ysens": 50, "cl_inverted": 0, "cl_netping": 0, #High level settings "cl_language": "en", "cl_subtitles": 1, "cl_width": 1280, "cl_height": 720, "cl_fullscreen": 0, "cl_motionblur": 0, "cl_motionblur_amount": 0, "cl_anisotropic": 1, "cl_mipmap": "none", "cl_vsync": "off", "cl_musicvolume": 10, "cl_dialogvolume": 10, "cl_soundvolume": 10, "cl_mastervolume": 10, #Server shared settings "sv_level": "", "sv_gamemode": "", "sv_game": 0, "sv_background_red": 0, "sv_background_green": 0, "sv_background_blue": 0, "sv_background_alpha": 0, } self.netVars = {} self.chatMessages = [] self.interfaces = [] self.entities = [] self.level = None self.gameEvents = [] self.updateNetwork() #self.startLoop() self.forceUpdateCVars() self.keepAliveTicker = 0 self.trackedProperties = [] loadClient(self) self.oP("Initialized.")
def __init__(self): '''Initializes the server.''' self.mode = "server" self.oP = OutPipe("Server", 0) self.nC = None self.cvars = { "sv_addr": "0.0.0.0", "sv_port": 7777, "sv_netlog": 0, "sv_level": "", "sv_game": 0, "sv_singleplayer": 0, "sv_gamemode": "singleplayer", "sv_startscript": "", "sv_master": "", "sv_dedicated": 0, "sv_chat": 1, "sv_background_red": 0, "sv_background_green": 0, "sv_background_blue": 0, "sv_background_alpha": 0, "sv_password": "", "cl_language": "en", "cl_subtitles": 1, "cl_width": 1280, "cl_height": 720, "cl_fullscreen": 0, "cl_motionblur": 0, "cl_motionblur_amount": 0, "cl_anisotropic": 1, "cl_mipmap": "none", "cl_vsync": "off", "cl_musicvolume": 10, "cl_dialogvolume": 10, "cl_soundvolume": 10, "cl_netping": 0, } self.netVars = {} self.oldNetVars = self.netVars self.oldcvars = self.cvars self.gameMode = None self.level = None self.unassignedPlayers = [] self.entities = [] self.events = [] self.saveFile = None self.chatMessages = [] self.eI = EngineInterface(True) self.sE = ScriptExecuter() self.pR = PhysicsReader(self) self.sH = ShaderHandler() self.l = Localizer(self) self.updateNetwork() self.forceUpdateCVars() self.keepAliveTicker = 0 self.trackedProperties = [] loadServer(self) self.oP("Initialized.")
def __init__(self, model_path): self.model = np.load(open(model_path, 'r')).item() self.head = 6 self.payload = 6 self.localizer = Localizer() print('Inflation model loaded')