// Use this for initialization void Start() { // Get custom arguments from command line Map = GetArg("-m", "-map") ?? Map; GameType = GetArg("-t", "-gameType") ?? GameType; // ex: get game type from command line RoomID = GetArg("-r", "-room") ?? RoomID; // Validate the requested Level var validMap = false; foreach (string value in BoltScenes.AllScenes) { if (SceneManager.GetActiveScene().name != value) { if (Map == value) { validMap = true; break; } } } if (!validMap) { BoltLog.Error("Invalid configuration: please verify level name"); Application.Quit(); } // Start the Server BoltLauncher.StartServer(); DontDestroyOnLoad(this); }
/// <summary> /// It will perform all steps to load the serialized data on re-config the entities on the project /// </summary> private static void Load() { var result = JsonSerializerUpdateUtils.LoadData(SerializedDataPath); if (result != null) { var prefabList = GetPrefabListFromProject(); foreach (var prefab in prefabList) { foreach (var updateItem in result) { if (prefab.name.Equals(updateItem.name)) { UpdateBoltEntity(prefab, updateItem); } } } BoltLog.Info("Load DONE!"); } else { BoltLog.Error("Unable to load data"); } }
// ======= PRIVATE METHODS ===================================================================================== public static int FindMissingComponents() { int missingScriptsCount = 0; List <Component> components = new List <Component>(); var folders = new string[] { "Assets" }; var iter = AssetDatabase.FindAssets("t:Prefab", folders).GetEnumerator(); while (iter.MoveNext()) { var guid = (string)iter.Current; var path = AssetDatabase.GUIDToAssetPath(guid); var go = AssetDatabase.LoadAssetAtPath <GameObject>(path); go.GetComponentsInChildren(true, components); for (int j = 0; j < components.Count; ++j) { if (components[j] == null) { ++missingScriptsCount; BoltLog.Error("Missing script: " + path); } } components.Clear(); } if (missingScriptsCount != 0) { BoltLog.Info("Found {0} Missing Scripts", missingScriptsCount); } return(missingScriptsCount); }
// Bolt Events public override void SceneLoadLocalDone(string scene, IProtocolToken token) { if (scene.Equals("PhotonLobby") && sceneFlag == false) { return; } BoltLog.Info(string.Format("New scene: {0}", scene)); try { if (lobbyScene.SimpleSceneName == scene) { ChangeBodyTo(uiMainMenu); uiTopPanel.HideBackButton(); uiTopPanel.SetInGame(false); sceneFlag = true; } else { ChangeBodyTo(null); uiTopPanel.SetInGame(true); uiTopPanel.ToggleVisibility(false); uiTopPanel.SetupBackButton("Menu", ShutdownEventHandler); sceneFlag = false; } } catch (Exception e) { BoltLog.Error(e); } }
public override void SimulateController() { if (!(up || down || left || right || (canShoot && triggerShoot))) { return; } var input = PlayerCmd.Create(); input.Up = up; input.Down = down; input.Left = left; input.Right = right; input.Attack = false; if (canShoot && triggerShoot) { input.AtkDir = DetectShoot(); input.Attack = true; } print("simulate controller"); try { entity.QueueInput(input); } catch (Exception e) { BoltLog.Error(e); entity.ClearInputQueue(); } }
public void OnDisconnected(DisconnectCause cause) { if (cause == DisconnectCause.None || cause == DisconnectCause.DisconnectByClientLogic) { return; } BoltLog.Error("[BoltVoiceBridge] OnDisconnected cause={0}", cause); }
private void OnServerNotAvailable() { BoltLog.Error("Game server is not available!"); DisconnectFromMatchmaking(); m_GameState = EGameState.Menu; }
// public override void ConnectRequest(UdpKit.UdpEndPoint endpoint, Bolt.IProtocolToken token) // { // BoltConsole.Write("Connecting request", Color.red); // var playerToken = token as PlayerToken; // if(playerToken != null) // { // BoltConsole.Write("Token received", Color.red); // BoltNetwork.Accept(endpoint, playerToken); // } else { // BoltConsole.Write("No tokens", Color.red); // BoltNetwork.Accept(endpoint); // } // } public override void Connected(BoltConnection connection) { BoltLog.Error("ServerCallBack: Client player are being made, connection: " + connection.ToString()); PlayerToken playerToken = connection.ConnectToken as PlayerToken; //BoltConsole.Write(playerToken.playerName + " ja " + playerToken.playerNumber, Color.magenta); MultiplayerPlayerRegistery.CreateClientPlayer(connection, playerToken); }
//========== PUBLIC METHODS ==================================================================================== public override void BoltStartDone() { m_GameState = EGameState.Playing; #if BOLT_CLOUD BoltLog.Error("Can't connect to {0}:{1}. Direct connection is not available in free version!", m_IPAddress, m_Port); #else BoltNetwork.Connect(new UdpEndPoint(UdpIPv4Address.Parse(m_IPAddress), (ushort)m_Port)); #endif }
private void LateUpdate() { if (BoltNetwork.Frame % 60 == 0 && // every 60 frame _hadClients && // someone has connected before BoltNetwork.Clients.Any() == false) // and there is no one now { BoltLog.Error("Shutting down: not clients left"); BoltNetwork.Shutdown(); } }
void Start() { #if UNITY_EDITOR_OSX Process p = new Process(); p.StartInfo.FileName = "osascript"; p.StartInfo.Arguments = @"-e 'tell application """ + UnityEditor.PlayerSettings.productName + @""" activate end tell'"; p.Start(); #endif BoltRuntimeSettings settings = BoltRuntimeSettings.instance; _serverEndPoint = new UdpEndPoint(UdpIPv4Address.Localhost, (ushort)settings.debugStartPort); _clientEndPoint = new UdpEndPoint(UdpIPv4Address.Localhost, 0); BoltConfig cfg; cfg = settings.GetConfigCopy(); cfg.connectionTimeout = 60000000; cfg.connectionRequestTimeout = 500; cfg.connectionRequestAttempts = 1000; if (string.IsNullOrEmpty(settings.debugStartMapName) == false) { if (BoltDebugStartSettings.DebugStartIsServer) { BoltLog.Warn("Starting as SERVER"); BoltLauncher.StartServer(_serverEndPoint, cfg); } else if (BoltDebugStartSettings.DebugStartIsClient) { BoltLog.Warn("Starting as CLIENT"); BoltLauncher.StartClient(_clientEndPoint, cfg); } else if (BoltDebugStartSettings.DebugStartIsSinglePlayer) { BoltLog.Warn("Starting as SINGLE PLAYER"); BoltLauncher.StartSinglePlayer(cfg); } BoltDebugStartSettings.PositionWindow(); } else { BoltLog.Error("No map found to start from"); } }
public void Apply() { if (Atlas == null || FontXML == null) { BoltLog.Error("Make sure Atlas and FontXML aren't null"); return; } XmlDocument xmlData = new XmlDocument(); xmlData.LoadXml(FontXML.text); XmlNode fontNode = xmlData.FirstChild; if (fontNode.Name != "font") { BoltLog.Error("Invalid font xml"); } Glyphs = new GlyphDictionary(); BaseSize = 1f; LineHeight = 1f; VScale = 1f; HScale = 1f; if (Atlas.width > Atlas.height) { HScale = Atlas.width / Atlas.height; } else if (Atlas.width < Atlas.height) { VScale = Atlas.height / Atlas.width; } foreach (XmlNode node in fontNode.ChildNodes) { if (node.Name == "info") { BaseSize = Convert.ToSingle(attribute(node, "size")); } else if (node.Name == "common") { LineHeight = Convert.ToSingle(attribute(node, "lineHeight")) / Atlas.height * VScale; } else if (node.Name == "chars") { parseChars(node); } else if (node.Name == "kernings") { parseKernings(node); } } }
private void SetupAndConnect() { #if BOLT_VOICE_SAMPLE // Registers this class to receive Photon callbacks voiceConnection.Client.AddCallbackTarget(this); // Auto automatically this.ConnectNow(); #else BoltLog.Error("[BoltVoiceBridge] Unable to initilize the Voice connection, please insert 'BOLT_VOICE_SAMPLE' into your Scripting Symbols"); #endif }
public static void DesealizePrefabs() { BoltLog.Info("Deserializing from version: {0}", BoltNetwork.Version); if (VerifyVersion(false)) { Load(); } else { BoltLog.Error("Minimal Bolt SDK to update to is v1.3.0"); } }
public static void SerializePrefabs() { BoltLog.Info("Serializing from version: {0}", BoltNetwork.Version); if (VerifyVersion(true)) { Save(); } else { BoltLog.Error("Minimal Bolt SDK to update from is v1.2.14"); } }
public override void OnEvent(DataStreamCheck evnt) { if (evnt.hash.Equals(hash)) { BoltLog.Info("Other end received data: it's EQUAL"); } else { BoltLog.Error("Other end received data: it's NOT EQUAL"); } canSend = true; }
void Start() { #if UNITY_EDITOR_OSX Process p = new Process(); p.StartInfo.FileName = "osascript"; p.StartInfo.Arguments = @"-e 'tell application """ + UnityEditor.PlayerSettings.productName + @""" activate end tell'"; p.Start(); #endif UdpEndPoint _serverEndPoint = new UdpEndPoint(UdpIPv4Address.Localhost, (ushort)BoltRuntimeSettings.instance.debugStartPort); UdpEndPoint _clientEndPoint = new UdpEndPoint(UdpIPv4Address.Localhost, 0); BoltConfig cfg; cfg = BoltRuntimeSettings.instance.GetConfigCopy(); cfg.connectionTimeout = 60000000; cfg.connectionRequestTimeout = 500; cfg.connectionRequestAttempts = 1000; if (string.IsNullOrEmpty(BoltRuntimeSettings.instance.debugStartMapName) == false) { if (BoltDebugStartSettings.startServer) { BoltLauncher.StartServer(_serverEndPoint, cfg); BoltNetwork.LoadScene(BoltRuntimeSettings.instance.debugStartMapName); } else if (BoltDebugStartSettings.startClient) { BoltLauncher.StartClient(_clientEndPoint, cfg); BoltNetwork.Connect(_serverEndPoint); } BoltDebugStartSettings.PositionWindow(); } else { BoltLog.Error("No map found to start from"); } if (!BoltNetwork.isClient && !BoltNetwork.isServer) { BoltLog.Error("failed to start debug mode"); } }
IEnumerator SetHostInfoRoutine(String servername, Boolean dedicated, Bolt.IProtocolToken protocolToken) { var t = new Timer(ROOM_CREATE_TIMEOUT); while (_lbClient.State != ClientState.JoinedLobby && t.Waiting) { yield return(null); } if (_lbClient.State != ClientState.JoinedLobby) { BoltLog.Error("Can't call BoltNetwork.SetHostInfo when not in lobby"); yield break; } // var maxPlayers = dedicated ? BoltNetwork.maxConnections : BoltNetwork.maxConnections + 1; // check for null token and create one var token = protocolToken as PhotonHostInfoToken; if (token == null) { token = new PhotonHostInfoToken(); } if (token.CustomRoomProperties == null) { token.CustomRoomProperties = new ExitGames.Client.Photon.Hashtable(); } token.CustomRoomProperties ["UdpSessionId"] = Guid.NewGuid().ToString(); if (_config.UsePunchThrough) { token.CustomRoomProperties ["SocketPeerId"] = BoltNetwork.UdpSocket.SocketPeerId.ToString(); } // _lbClient.OpCreateRoom(servername, new RoomOptions() { CustomRoomProperties = token.CustomRoomProperties, CustomRoomPropertiesForLobby = new string[] { "UdpSessionId", "SocketPeerId" }, MaxPlayers = (byte)maxPlayers, }, null); }
public override void OnEvent(DataStreamCheck evnt) { if (evnt.hash.Equals(hash)) { var diff = Time.time - timestamp; timestamp = 0; BoltLog.Info("Other end received data: it's EQUAL in {0}secs", diff); } else { BoltLog.Error("Other end received data: it's NOT EQUAL"); } canSend = true; }
public void RegisterVirtualButton(CrossPlatformInputManager.VirtualButton button) { // check if already have a buttin with that name and log an error if we do if (m_VirtualButtons.ContainsKey(button.name)) { BoltLog.Error("There is already a virtual button named " + button.name + " registered."); } else { // add any new buttons m_VirtualButtons.Add(button.name, button); // if we dont want to match to the input manager then always use a virtual axis if (!button.matchWithInputManager) { m_AlwaysUseVirtual.Add(button.name); } } }
public void RegisterVirtualAxis(CrossPlatformInputManager.VirtualAxis axis) { // check if we already have an axis with that name and log and error if we do if (m_VirtualAxes.ContainsKey(axis.name)) { BoltLog.Error("There is already a virtual axis named " + axis.name + " registered."); } else { // add any new axes m_VirtualAxes.Add(axis.name, axis); // if we dont want to match with the input manager setting then revert to always using virtual if (!axis.matchWithInputManager) { m_AlwaysUseVirtual.Add(axis.name); } } }
// Use this for initialization void StartHeadlessServer() { if (IsHeadlessMode() == false && HeadlessTesting == false) { return; } if (Application.internetReachability == NetworkReachability.NotReachable) { Debug.Log("Internet Not Reachable"); Invoke("StartHeadlessServer", 1f); return; } // Get custom arguments from command line Map = GetArg("-m", "-map") ?? Map; GameType = GetArg("-t", "-gameType") ?? GameType; // ex: get game type from command line RoomID = GetArg("-r", "-room") ?? RoomID; // Validate the requested Level var validMap = false; foreach (string value in BoltScenes.AllScenes) { if (SceneManager.GetActiveScene().name != value) { if (Map == value) { validMap = true; break; } } } if (!validMap) { BoltLog.Error("Invalid configuration: please verify level name"); Application.Quit(); } // Start the Server BoltLauncher.StartServer(); }
/// <summary> /// Connect the local peer into the custom Voice Room on the same Region as Bolt is already connected /// </summary> public void ConnectNow() { BoltLog.Info("[BoltVoiceBridge] Starting Voice connection..."); var customSettings = new AppSettings(); voiceConnection.Settings.CopyTo(customSettings); // Connect to the same Region as Bolt is connected customSettings.FixedRegion = Region; if (voiceConnection.ConnectUsingSettings(customSettings)) { BoltLog.Info("[BoltVoiceBridge] Connecting to Region {0}", customSettings.FixedRegion); } else { BoltLog.Error("[BoltVoiceBridge] Not able to connect"); } }
void OnWizardCreate() { if (Atlas == null || FontXML == null) { BoltLog.Error("Make sure Atlas and FontXML aren't null"); return; } if (PrepareTextures) { string atlasPath = AssetDatabase.GetAssetPath(Atlas); TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(atlasPath); importer.textureType = TextureImporterType.Default; importer.mipmapEnabled = false; importer.anisoLevel = 4; importer.filterMode = FilterMode.Bilinear; importer.wrapMode = TextureWrapMode.Clamp; importer.maxTextureSize = 4096; //importer.textureFormat = TextureImporterFormat.Alpha8; AssetDatabase.ImportAsset(atlasPath, ImportAssetOptions.ForceUpdate); } TypogenicFont asset = ScriptableObject.CreateInstance <TypogenicFont>(); asset.Atlas = Atlas; asset.FontXML = FontXML; asset.Apply(); CreateAsset(asset, FontXML.name + " Data.asset"); if (CreateMaterial) { Material material = new Material(Shader.Find("Typogenic/Unlit Font")); material.mainTexture = Atlas; CreateAsset(material, FontXML.name + ".mat"); } AssetDatabase.SaveAssets(); EditorUtility.FocusProjectWindow(); Selection.activeObject = asset; }
/// <summary> /// Serialize a list of UpdateItem into a JSON file /// </summary> /// <param name="items">UpdateItem list to save</param> /// <param name="path">Path to save the file</param> /// <returns>True if all went well, false otherwise</returns> public static bool SaveData(List <UpdateItem> items, string path) { try { using (var sw = new StreamWriter(path)) { using (JsonWriter writer = new JsonTextWriter(sw)) { serializer.Serialize(writer, items, typeof(List <UpdateItem>)); } } return(true); } catch (Exception e) { BoltLog.Error(e); BoltLog.Error(string.Format("Error while serializing Bolt Entities to file at {0}", path)); } return(false); }
/// <summary> /// Start this peer as the Game Server /// </summary> private void OnServerActive() { if (BoltNetwork.IsRunning) { return; } try { // In order to start the server property when running on the PlayFab stack, it's necessary // to setup the local port where the server will listen and suppress the STUN request by passing // the binding information provided by PlayFab BindingInfo info; if (BuildBindingInfo(out info)) { // Override the STUN information sent by this peer, in other words, the public IP:PORT of this // instance. This information is gattered directly from the PlayFab stack, that provides statically // the binding data of each Virtual Machine BoltLauncher.SetUdpPlatform(new PhotonPlatform(new PhotonPlatformConfig() { ForceExternalEndPoint = info.externalInfo })); // Set the Server port using the information from the binding configuration BoltLauncher.StartServer(info.internalServerPort); } else // Shutdow if the binding info was not found { BoltLog.Error(MessageInvalidBinding); OnShutdown(); } } catch (Exception ex) { BoltLog.Error(MessageExceptionServer); BoltLog.Exception(ex); OnShutdown(); } }
/// <summary> /// Load data from a JSON into a list of UpdateItem /// </summary> /// <param name="path">Path of the JSON file</param> /// <returns>List of UpdateItem</returns> public static List <UpdateItem> LoadData(string path) { List <UpdateItem> result = null; try { using (var sw = new StreamReader(path)) { using (JsonReader reader = new JsonTextReader(sw)) { result = (List <UpdateItem>)serializer.Deserialize(reader, typeof(List <UpdateItem>)); } } } catch (Exception e) { BoltLog.Error(e); BoltLog.Error(string.Format("Error while deserializing Bolt Entities to file at {0}", path)); result = null; } return(result); }
static public Boolean JoinSession(UdpSession session, System.Object token) { if (session.Source == UdpSessionSource.Photon) { if (Instance._connectState != ConnectState.Idle) { BoltLog.Error("Already attempting connection to a photon room"); return(true); } if (Instance._lbClient.State != ClientState.JoinedLobby) { BoltLog.Error("Can't call BoltNetwork.Connect when not in lobby"); return(true); } Instance._currentConnectRoutine = Instance.StartCoroutine(Instance.JoinSessionRoutine(session, token)); return(true); } else { return(false); } }
private void DrawSetupPhoton() { DrawInputWithLabel("Photon Cloud Setup", () => { GUILayout.BeginVertical(); GUILayout.Space(5); GUILayout.Label(BoltWizardText.PHOTON, textLabel); GUILayout.EndVertical(); GUILayout.BeginHorizontal(); GUILayout.Label(BoltWizardText.PHOTON_DASH, textLabel); if (GUILayout.Button("Visit Dashboard", minimalButton)) { OpenURL("https://dashboard.photonengine.com/")(); } GUILayout.EndHorizontal(); }, false); GUILayout.Space(15); BoltRuntimeSettings settings = BoltRuntimeSettings.instance; DrawInputWithLabel("Photon Bolt App ID or Email", () => { GUILayout.BeginVertical(); AppIdOrEmail = EditorGUILayout.TextField(AppIdOrEmail, centerInputText); GUILayout.EndVertical(); }, false, true, 300); DrawInputWithLabel("Region", () => { settings.photonCloudRegionIndex = EditorGUILayout.Popup(settings.photonCloudRegionIndex, BoltRuntimeSettings.photonCloudRegions); }, true, true); DrawInputWithLabel("NAT Punchthrough Enabled", () => { settings.photonUsePunch = BoltEditorGUI.Toggle(settings.photonUsePunch); }, true, true); // Action if (beforeNextCallback == null) { beforeNextCallback = () => { if (requestingAppId) { BoltLog.Info("Please, wait until your request for a new AppID finishes."); return(false); } if (AccountService.IsValidEmail(AppIdOrEmail)) { try { EditorUtility.DisplayProgressBar(BoltWizardText.CONNECTION_TITLE, BoltWizardText.CONNECTION_INFO, 0.5f); BoltLog.Info("Starting request"); requestingAppId = new AccountService().RegisterByEmail( AppIdOrEmail, new List <ServiceTypes>() { ServiceTypes.Bolt }, (response) => { if (response.ReturnCode == AccountServiceReturnCodes.Success) { var appKey = response.ApplicationIds[((int)ServiceTypes.Bolt).ToString()]; settings.photonAppId = appKey; AppIdOrEmail = appKey; BoltLog.Info("You new App ID: {0}", AppIdOrEmail); } else { BoltLog.Warn( "It was not possible to process your request, please go to the Photon Cloud Dashboard."); BoltLog.Warn("Return Code: {0}", AccountServiceReturnCodes.ReturnCodes[response.ReturnCode]); } requestingAppId = false; EditorUtility.ClearProgressBar(); }, (err) => { BoltLog.Error(err); requestingAppId = false; EditorUtility.ClearProgressBar(); }); if (requestingAppId) { BoltLog.Info("Requesting your new App ID"); } else { BoltLog.Warn( "It was not possible to process your request, please go to the Photon Cloud Dashboard."); EditorUtility.ClearProgressBar(); } } catch (Exception ex) { EditorUtility.DisplayDialog("Error", ex.Message, "ok"); } } else if (IsAppId(AppIdOrEmail)) { settings.photonAppId = AppIdOrEmail; return(true); } else { ShowNotification(new GUIContent("Please specify a valid Photon Bolt App ID or Email.")); } return(false); }; } }
public override void BoltStartFailed(UdpConnectionDisconnectReason disconnectReason) { BoltLog.Error("Failed to start debug mode"); }