Commit b909d464 authored by cann-alberto's avatar cann-alberto
Browse files

Deploy 05/03/2025

parent e1ff7d1b
......@@ -616,7 +616,6 @@ GameObject:
- component: {fileID: 88074381}
- component: {fileID: 88074380}
- component: {fileID: 88074382}
- component: {fileID: 88074383}
- component: {fileID: 88074384}
m_Layer: 5
m_Name: SceneManager
......@@ -671,8 +670,7 @@ MonoBehaviour:
networkManager: {fileID: 0}
transport: {fileID: 0}
cameraOrbit: {fileID: 7825374990767153394}
pathToRoomExe: C:\\Users\\lab2a\\Documents\\Unity Projects\\MPAI-MMM\\Builds\\MPAI-MMM.exe
--- !u!114 &88074383
--- !u!114 &88074384
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
......@@ -681,23 +679,75 @@ MonoBehaviour:
m_GameObject: {fileID: 88074379}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: c458dc28f1b357249ac5af2884c30b9e, type: 3}
m_Name:
m_EditorClassIdentifier:
networkManager: {fileID: 0}
--- !u!1 &107673262
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 107673265}
- component: {fileID: 107673264}
- component: {fileID: 107673263}
m_Layer: 0
m_Name: RoomsManager
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &107673263
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 107673262}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 92e80ec55d5f926418353d7e6d212a13, type: 3}
m_Name:
m_EditorClassIdentifier:
serverSocket: {fileID: 0}
--- !u!114 &88074384
syncDirection: 0
syncMode: 0
syncInterval: 0
--- !u!114 &107673264
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 88074379}
m_GameObject: {fileID: 107673262}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: c458dc28f1b357249ac5af2884c30b9e, type: 3}
m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3}
m_Name:
m_EditorClassIdentifier:
networkManager: {fileID: 0}
sceneId: 1015590522
_assetId: 0
serverOnly: 1
visibility: 0
hasSpawned: 0
--- !u!4 &107673265
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 107673262}
serializedVersion: 2
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: -0.49864817, y: -0.5244422, z: 0.6539762}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 0}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1001 &119929167
PrefabInstance:
m_ObjectHideFlags: 0
......@@ -7203,3 +7253,4 @@ SceneRoots:
- {fileID: 375110087}
- {fileID: 7825374990767153395}
- {fileID: 88074381}
- {fileID: 107673265}
using Mirror;
using UnityEngine;
public class ClosedRoomsManager : NetworkBehaviour
{
void Update()
{
if (isServer)
{
if (!PortManager.Instance.PortsToDestroy.IsEmpty)
{
while (PortManager.Instance.PortsToDestroy.TryDequeue(out int port))
{
Debug.Log($"Try dequeue and destroy port: {port}");
DestroyRoom(port);
}
}
}
}
public void DestroyRoom(int port)
{
if (!isServer) return;
Debug.Log("Searching the room");
GameObject roomObject = PortManager.Instance.GetRoom(port);
if (roomObject != null)
{
Debug.Log($"Destroying room on port {port}");
// Free the port before destroying the object
PortManager.Instance.FreePort(port);
// destroy the GameObject
NetworkServer.Destroy(roomObject);
Debug.Log($"Room on port {port} has been destroyed.");
}
else
{
Debug.LogWarning($"No room found on port {port}.");
}
}
}
......@@ -15,7 +15,7 @@ public class GameManager : MonoBehaviour
public string pathToRoomExe;
public string currentPlayerPosition;
public string currentPlayerLocation;
public GameObject localPlayerPrefab;
......
......@@ -4,6 +4,7 @@ using ReadyPlayerMe.Samples.QuickStart;
using System;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices.WindowsRuntime;
using UnityEngine;
using UnityEngine.UIElements;
......@@ -77,25 +78,24 @@ public class InGameMenuEvents : MonoBehaviour
//Remove the first line
if (lines.Length > 10)
{
lines = new ArraySegment<string>(lines, 1, lines.Length - 1).ToArray();
//+= "[" + DateTime.Now + "]: " + message + "\n";
lines = new ArraySegment<string>(lines, 1, lines.Length - 1).ToArray();
}
// Add a new line
string[] updatedLines = new string[lines.Length + 1];
Array.Copy(lines, updatedLines, lines.Length);
updatedLines[updatedLines.Length - 1] =
"[" + message.time + "] "+ message.source + " : " + message.inItem + "\n";
"[" + message.time + "] "+ message.source + " : " + message.body + "\n";
// Join the lines back with newlines and print the result
_messageLabel.text = string.Join("\n", updatedLines);
}
}
/* MM-SEND */
#region MM-SEND
private void OnMMSendButtonClicked(ClickEvent evt)
{
VisualElement sendMsgVisualElement = _document.rootVisualElement.Q("SendMsgVisualElement") as VisualElement;
......@@ -117,20 +117,21 @@ public class InGameMenuEvents : MonoBehaviour
private void SendMsg(ClickEvent evt)
{
UnityEngine.Debug.Log($"S-Process: User1;\nAction: MM-Send; \nS-Compl: Message;\nD-Process: To User2"); //
// Retrieve data from the GUI
TextField toTextField = _document.rootVisualElement.Q("toTextField") as TextField;
TextField msgTextField = _document.rootVisualElement.Q("msgTextField") as TextField;
// Create Json data to be sent
string actionDataJson = CreateMessageJson(toTextField.value, msgTextField.value);
StartCoroutine(GameManager.Instance.WebAPIManager.Upload("Activity/actions", actionDataJson, HandleResponse));
UnityEngine.Debug.Log("Message sent to the WebApiServer");
StartCoroutine(GameManager.Instance.WebAPIManager.Upload("Communication/messages", actionDataJson, HandleResponse));
// Send message to the target user
SendTextMessage(toTextField.value, actionDataJson);
UnityEngine.Debug.Log("Message sent to " + toTextField.value);
MessageInfo myMessage = new MessageInfo(DateTime.Now, GameManager.Instance.userID, toTextField.value, "MM-Send", msgTextField.value, GameManager.Instance.currentPlayerPosition, "Square", "string");
MessageInfo myMessage = new MessageInfo(DateTime.Now, GameManager.Instance.userID, toTextField.value, msgTextField.value);
UpdateMessageLabel(myMessage);
// Reset the TextField
msgTextField.value = "";
......@@ -138,22 +139,16 @@ public class InGameMenuEvents : MonoBehaviour
private void HandleResponse(string response)
{
UnityEngine.Debug.Log("Received response: " + response); // Log the response received from the server
// TODO: send the message to the Unity server
UnityEngine.Debug.Log("Received response: " + response); // Log the response received from the server
}
private string CreateMessageJson(string toTextField, string msgTextField)
{
string jsonData = "{" +
"\"time\": \"" + DateTime.Now + "\"," +
string jsonData = "{" +
"\"body\": \"" + msgTextField + "\"," +
"\"source\": \"" + GameManager.Instance.userID + "\"," +
"\"destination\": \"" + toTextField + "\"," +
"\"action\": \"MM-Send\"," +
"\"inItem\": \"" + msgTextField + "\"," +
"\"inLocation\": \"" + GameManager.Instance.currentPlayerPosition + "\"," +
"\"outLocation\": \"Square\"," + // TODO: retrieve position of the target pleyer
"\"rightsID\": \"string\"" +
"\"time\": \"" + DateTime.Now + "\"" +
"}";
return jsonData;
}
......@@ -189,12 +184,11 @@ public class InGameMenuEvents : MonoBehaviour
// Once connected, send the message
GameManager.Instance.ClientSocket.SendSocketMessage(msgTextField);
}
#endregion
/* CREATE ROOM */
#region ROOM
private void OnCreateRoomButtonClicked(ClickEvent evt)
{
UnityEngine.Debug.Log("Create Room button clicked.");
{
_playerTracker = GameManager.Instance.localPlayerPrefab.GetComponent<PlayerTracker>();
if (_playerTracker == null)
......@@ -203,25 +197,58 @@ public class InGameMenuEvents : MonoBehaviour
}
if (_playerTracker != null)
{
_playerTracker.OnRoomInstantiated += HandleRoomInstantiated;
_playerTracker.InstantiateRoomPrefab();
}
else
StartCoroutine(BuyAndCreateRoom(_playerTracker));
}
}
private IEnumerator BuyAndCreateRoom(PlayerTracker playerTracker)
{
// User buys the Parcel
bool isTransactSucces = false;
string newTransact = CreateTransaction();
UnityEngine.Debug.Log($"S-Process: User;\nAction: Transact; \nS-Compl: With Transaction;\nD-Process: User"); //User1 buys Parcel
yield return GameManager.Instance.WebAPIManager.Upload("Transact/transaction", newTransact, (responseText) =>
{
UnityEngine.Debug.LogError("PlayerTracker is null or not assigned.");
}
if (responseText != null)
{
UnityEngine.Debug.Log("Transaction created successfully");
isTransactSucces = true;
}
else
{
UnityEngine.Debug.LogError("Error while creating the trasaction");
}
});
if (!isTransactSucces) yield break;
// Request to istantiate the room pref on the server
_playerTracker.OnRoomInstantiated += HandleRoomInstantiated;
_playerTracker.InstantiateRoomPrefab();
}
private void HandleRoomInstantiated()
{
UnityEngine.Debug.Log("Room prefab instantiated, trying to connet to the server");
private void HandleRoomInstantiated()
{
_playerTracker.OnRoomInstantiated -= HandleRoomInstantiated; // Unsubscribe to avoid memory leaks
// Activate the camera orbit script
cameraOrbit.enabled = true;
}
private string CreateTransaction()
{
string jsonData = "{" +
" \"header\": \"MMM-ACC-V2.2\", " +
" \"mInstanceID\": \"MInstance00\", " +
" \"transactionData\": {" +
" \"assetID\": \" Asset00\", " +
" \"transactionTime\": \"" + DateTime.Now + "\"" +
"}, " +
"\"descrMetadata\": \"" + DateTime.Now + "\"}";
return jsonData;
}
#endregion
void OnApplicationQuit()
{
if (_serverProcess != null && !_serverProcess.HasExited)
......
......@@ -34,7 +34,8 @@ public class MainMenuEvents : MonoBehaviour
_buttonLogin.UnregisterCallback<ClickEvent>(OnLoginButtonClick);
_buttonRegister.UnregisterCallback <ClickEvent>(OnRegisterButtonClick);
}
#region Login
private void OnLoginButtonClick(ClickEvent evt)
{
_registrationForm.style.visibility = Visibility.Hidden;
......@@ -74,35 +75,19 @@ public class MainMenuEvents : MonoBehaviour
Debug.LogError("Failed to login. Account is null.");
yield break;
}
bool actionSent = false;
string actionDataJson = CreateLoginMessageJson(userAccount.users[0].id);
yield return GameManager.Instance.WebAPIManager.Upload("Activity/actions", actionDataJson, (responseText) =>
{
if (responseText != null)
{
Debug.Log("Actions sent successfully:" + responseText);
actionSent = true;
}
else
{
Debug.LogError("Error while sending login messagge.");
}
});
if (!actionSent) yield break;
// Update the DataManager with the retrieved account data
GameManager.Instance.humanID = humanID;
GameManager.Instance.personaUrl = GameManager.Instance.WebAPIManager.BASE_URL + "Registration/avatars/" + userAccount.personae[0].model;
GameManager.Instance.userID = userAccount.users[0].id;
_networkClientManager.ConnectToServer(); // Start Mirror Server
GameManager.Instance.ServerSocket.StartServer(GameManager.Instance.port); // Start Info Server
GameManager.Instance.ServerSocket.StartServer(GameManager.Instance.port); // Start Communication Server
}
//Registration
#endregion
#region Registration
private void OnRegisterButtonClick(ClickEvent evt)
{
_loginForm.style.visibility = Visibility.Hidden;
......@@ -148,6 +133,8 @@ public class MainMenuEvents : MonoBehaviour
private void OnSubmitRegisterButtonClick(ClickEvent evt)
{
Debug.Log("S-Process: Human;\nAction: Register;\nS-Compl: With PersonalProfile;\nD-Process: RGSrvc;\nD-Compl: To human"); //human registers with M-Instance
// Collect personal data in JSON format
string personalDataJson = CreatePersonalDataJson();
......@@ -189,6 +176,8 @@ public class MainMenuEvents : MonoBehaviour
}
});
if (newAccount == null) yield break;
Debug.Log("S-Process: RGSrvc;\nS-Compl: Account;\nD-Process: human");
// Step 3: Create the user
User newUser = null;
......@@ -226,29 +215,9 @@ public class MainMenuEvents : MonoBehaviour
GameManager.Instance.personaUrl = GameManager.Instance.WebAPIManager.BASE_URL + "Registration/avatars/" + personaTextField.value;
GameManager.Instance.userID = newUser.id;
// Step 5: Sending login message to the ActivitySrv
bool actionSent = false;
string actionDataJson = CreateLoginMessageJson(newUser.id);
yield return GameManager.Instance.WebAPIManager.Upload("Activity/actions", actionDataJson, (responseText) =>
{
if (responseText != null)
{
Debug.Log("Actions sent successfully:" + responseText);
actionSent = true;
}
else
{
Debug.LogError("Error while sending login messagge.");
}
});
if (!actionSent) yield break;
// Step 5: Connect to the server
_networkClientManager.ConnectToServer();
GameManager.Instance.ServerSocket.StartServer(GameManager.Instance.port); // Start Info Server
GameManager.Instance.ServerSocket.StartServer(GameManager.Instance.port); // Start Communication Server
}
private string CreatePersonalDataJson()
......@@ -271,9 +240,7 @@ public class MainMenuEvents : MonoBehaviour
" \"nationality\": \"" + nationalityTextField.value + "\"," +
" \"email\": \"" + emailTextField.value + "\" " +
"}, " +
"\"descrMetadata\": \"" + DateTime.Now + "\"}";
Debug.Log("jsonData to be sent [GetPersonalData]: " + jsonData);
"\"descrMetadata\": \"" + DateTime.Now + "\"}";
// Passing data to the online scene
GameManager.Instance.playerName = firstNameTextField.value;
......@@ -305,22 +272,7 @@ public class MainMenuEvents : MonoBehaviour
GameManager.Instance.personaUrl = GameManager.Instance.WebAPIManager.BASE_URL + "Registration/avatars/" + personaTextField.value;
return jsonData;
}
private string CreateLoginMessageJson(string userID)
{
string jsonData = "{" +
"\"time\": \"" + DateTime.Now + "\"," +
"\"source\": \"" + userID + "\"," +
"\"destination\": \"Activity Service\"," +
"\"action\": \"MM-Send\"," +
"\"inItem\": \"Im on MMM\"," +
"\"inLocation\": \"Square\"," +
"\"outLocation\": \"Square\"," +
"\"rightsID\": \"string\"" +
"}";
return jsonData;
}
private string CreateUpdatedAccountJson(Account accountToUpdate, User newUser, string persona)
{
string jsonData = "{" +
......@@ -337,7 +289,7 @@ public class MainMenuEvents : MonoBehaviour
Debug.Log(jsonData);
return jsonData;
}
#endregion
}
......
using Mirror;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;
public class PlayerTracker : NetworkBehaviour
{
public GameObject roomPrefab;
public event Action OnRoomInstantiated; // Define an event
private bool hasTriedToConnect = false;
private static HashSet<int> usedPorts = new HashSet<int>(); // Track used ports
private static int basePort = 7780; // Base port number
private bool hasTriedToConnect = false;
int port = 0;
void Start()
{
hasTriedToConnect = false;
}
{
hasTriedToConnect = false;
}
private void OnTriggerEnter(Collider other)
{
......@@ -26,20 +24,21 @@ public class PlayerTracker : NetworkBehaviour
{
if (other.CompareTag("Parcel"))
{
UnityEngine.Debug.Log("Player enter: " + other.gameObject.name);
string actionDataJson = CreateEmbedJson(other.gameObject.name, GameManager.Instance.userID);
StartCoroutine(GameManager.Instance.WebAPIManager.Upload("Activity/actions", actionDataJson, HandleResponse));
GameManager.Instance.currentPlayerPosition = other.gameObject.name;
UnityEngine.Debug.Log("Player enter: " + other.gameObject.name);
UnityEngine.Debug.Log($"S-Process: User;\nAction: MM-Move; \nS-Compl: Persona From MLoc To MLoc({other.gameObject.name}) With SA ;\nD-Process: LOSrvc"); //Persona moved close to Parcel
string moveDataJson = CreateMoveDataJson(other.gameObject.name);
StartCoroutine(GameManager.Instance.WebAPIManager.Upload("Location/action-request", moveDataJson, HandleResponse));
GameManager.Instance.currentPlayerLocation = other.gameObject.name;
}
if (other.CompareTag("RoomPlaceholder") && !hasTriedToConnect)
{
hasTriedToConnect = true; // To avoid trying multiple conenction ot the same room
NetInfo netInfo = other.GetComponent<NetInfo>();
UnityEngine.Debug.Log("NetInfo[Mirror Server]: " + netInfo.IpAddress + ":" + netInfo.Port + "\nNetInfo[Communication Server]: " + netInfo.IpAddressComServer + ":" + netInfo.PortComServer);
RoomData.port = netInfo.Port;
RoomData.roomName = "Lobby Room";
//SceneManager.LoadScene("Room");
RoomData.roomName = "Room_[" + netInfo.IpAddress+":"+netInfo.Port+"]";
RoomData.netInfo = netInfo;
StartCoroutine(GameManager.Instance.ClientSocket.TryConnectToServerCoroutine(netInfo.IpAddressComServer, netInfo.PortComServer, 10, 2f));
}
......@@ -48,43 +47,40 @@ public class PlayerTracker : NetworkBehaviour
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Parcel"))
UnityEngine.Debug.Log("Exit from:" + other.gameObject.name);
{
if (isLocalPlayer)
{
if (other.CompareTag("Parcel"))
UnityEngine.Debug.Log("Exit from:" + other.gameObject.name);
}
}
// Callback method to handle the response from the GET request
private void HandleResponse(string response)
{
UnityEngine.Debug.Log("Received response: " + response); // Log the response received from the server
UnityEngine.Debug.Log("Received response: " + response); // Log the response received from the server
}
private string CreateEmbedJson(string ParcelName, string userID)
{
private string CreateMoveDataJson(string ParcelName)
{
string position = transform.position.ToString().Replace(",", ".");
string rotation = transform.localRotation.ToString().Replace(",", ".");
string jsonData = "{" +
"\"time\": \"" + DateTime.Now + "\"," +
"\"source\": \"" + userID + "\"," +
"\"destination\": \"Activity Service\"," +
"\"action\": \"MM-Embed\"," +
"\"inItem\": \"At " + ParcelName + "\"," +
"\"inLocation\": \"At " + ParcelName + "\"," +
"\"outLocation\": \"At " + ParcelName + "\"," +
"\"rightsID\": \"string\"" +
"}";
return jsonData;
}
"\"action\": \"MM-Move\"," +
"\"sProcess\": \"" + GameManager.Instance.userID + "\"," +
"\"sComplements\": \"Persona From " + GameManager.Instance.currentPlayerLocation + " To " + ParcelName + " With SA position: " + position + " rotation: " + rotation + "\"," +
"\"dProcess\": \"Location Service\"" +
"}";
return jsonData;
}
[Command]
public void CmdInstantiateRoom(Vector3 position, Quaternion orientation)
{
if (!isServer) return;
// TODO search for a free port
int port = FindFreePort();
// Search for a free port
int port = PortManager.Instance.FindFreePort();
if (port == -1)
{
UnityEngine.Debug.LogError("No available ports to create a new room.");
......@@ -96,10 +92,12 @@ public class PlayerTracker : NetworkBehaviour
NetworkServer.Spawn(roomObject);
netInfo.SetNetworkInfo("127.0.0.1", port, "127.0.0.1", port + 1); // TODO: replace the ipAddresses
// Store the room in the dictionary
PortManager.Instance.TrackRoom(port, roomObject);
UnityEngine.Debug.Log("Launching the server...");
LaunchRoomServer(port);
LaunchRoomServer(port); // Launch the Mirror server
RpcNotifyRoomCreated(); // Notify clients
}
[ClientRpc]
......@@ -108,12 +106,13 @@ public class PlayerTracker : NetworkBehaviour
OnRoomInstantiated?.Invoke(); // Invoke event when room is instatiated
}
// Public method to allow interaction from other scripts
public void InstantiateRoomPrefab()
{
if (isLocalPlayer)
{
{
UnityEngine.Debug.Log($"S-Process: User;\nAction: MM-Add; \nS-Compl:Room At MLoc With SA;\nD-Process: LOSrvc"); //User1 places Room on Parcel
string addDataJson = CreateAddDataJson();
StartCoroutine(GameManager.Instance.WebAPIManager.Upload("Location/action-request", addDataJson, HandleResponse));
CmdInstantiateRoom(transform.position, transform.localRotation);
}
else
......@@ -122,47 +121,44 @@ public class PlayerTracker : NetworkBehaviour
}
}
private string CreateAddDataJson()
{
string position = transform.position.ToString().Replace(",", ".");
string rotation = transform.localRotation.ToString().Replace(",", ".");
string jsonData = "{" +
"\"time\": \"" + DateTime.Now + "\"," +
"\"action\": \"MM-Add\"," +
"\"sProcess\": \"" + GameManager.Instance.userID + "\"," +
"\"sComplements\": \"Room At " + GameManager.Instance.currentPlayerLocation + " With SA position: " + position + " rotation: " + rotation + "\"," +
"\"dProcess\": \"Location Service\"" +
"}";
return jsonData;
}
private void LaunchRoomServer(int port)
{
//Launch the server
string sceneName = "Room Server";
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = GameManager.Instance.pathToRoomExe;
//startInfo.FileName = "C:\\Users\\lab2a\\Documents\\Unity Projects\\MPAI-MMM\\Builds\\MPAI-MMM.exe";
startInfo.FileName = GameManager.Instance.pathToRoomExe;
startInfo.Arguments = $"-scene {sceneName} -port {port}";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.CreateNoWindow = true;
Process serverProcess = new Process();
serverProcess.StartInfo = startInfo;
serverProcess.Start();
serverProcess.EnableRaisingEvents = true;
serverProcess.Exited += (sender, args) => OnRoomServerClosed(port); // Attach event
serverProcess.Start();
}
private int FindFreePort()
{
int maxPort = basePort + 100; // Arbitrary max range for ports
for (int port = basePort; port <= maxPort; port += 2) // Increment by 2 to reserve consecutive ports
{
if (!usedPorts.Contains(port))
{
usedPorts.Add(port);
return port;
}
}
return -1; // No available ports
public void OnRoomServerClosed(int port)
{
UnityEngine.Debug.Log($"Room server closed for port {port}");
PortManager.Instance.PortsToDestroy.Enqueue(port);
}
[Server]
public static void FreePort(int port)
{
if (usedPorts.Contains(port))
{
usedPorts.Remove(port);
UnityEngine.Debug.Log("Freed port: " + port);
}
}
}
using System.Collections.Concurrent;
using System.Collections.Generic;
using UnityEngine;
public class PortManager
{
private static PortManager _instance;
public static PortManager Instance => _instance ??= new PortManager();
private SortedSet<int> availablePorts = new SortedSet<int>();
private Dictionary<int, GameObject> portToRoom = new Dictionary<int, GameObject>();
private int basePort = 7780; // Base port number
public ConcurrentQueue<int> PortsToDestroy = new ConcurrentQueue<int>();
private PortManager()
{
InitializePorts();
}
private void InitializePorts()
{
int maxPort = basePort + 100; // Define max range for ports
for (int port = basePort; port <= maxPort; port += 2) // Reserve consecutive ports
{
availablePorts.Add(port);
}
}
public int FindFreePort()
{
if (availablePorts.Count < 2) return -1; // Ensure at least two available ports
int port = availablePorts.Min; // Get the smallest available port
availablePorts.Remove(port);
//availablePorts.Remove(port + 1); // Reserve secondary port
Debug.Log($"Assigned ports: {port} and {port + 1}");
return port;
}
public void FreePort(int port)
{
Debug.Log("Free port starts");
if (!availablePorts.Contains(port))
{
availablePorts.Add(port);
//availablePorts.Add(port + 1); // Free the secondary port
Debug.Log($"Freed ports: {port} and {port + 1}");
}
}
public void TrackRoom(int port, GameObject roomObject)
{
portToRoom[port] = roomObject;
}
//public GameObject GetRoom(int port)
//{
// Debug.Log("GetRoom");
// return portToRoom.TryGetValue(port, out var roomObject) ? roomObject : null;
//}
public GameObject GetRoom(int port)
{
UnityEngine.Debug.Log($"GetRoom called for port: {port}");
if (portToRoom == null)
{
UnityEngine.Debug.LogError("portToRoom dictionary is NULL!");
return null;
}
UnityEngine.Debug.Log("GetRoom 1" + portToRoom.Count);
if (portToRoom.Count == 0)
{
UnityEngine.Debug.LogWarning("portToRoom dictionary is EMPTY!");
return null;
}
UnityEngine.Debug.Log("GetRoom 2:" + portToRoom.ContainsKey(port));
if (portToRoom.TryGetValue(port, out GameObject roomObject))
{
if (roomObject != null)
{
UnityEngine.Debug.Log($"Room found for port {port}");
return roomObject;
}
else
{
UnityEngine.Debug.LogWarning($"Room for port {port} exists in the dictionary but is NULL!");
return null;
}
}
else
{
UnityEngine.Debug.LogWarning($"No room found for port {port} in portToRoom dictionary.");
return null;
}
}
}
fileFormatVersion: 2
guid: 33072433903b9fd4895c0f5095e0627e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
......@@ -4,6 +4,9 @@ using kcp2k;
using System.IO;
using System;
using System.Collections.Generic;
using GLTFast.Schema;
using static UnityEngine.UIElements.UxmlAttributeDescription;
using Unity.VisualScripting.Antlr3.Runtime;
public class RoomGameManager : MonoBehaviour
{
......@@ -57,14 +60,37 @@ public class RoomGameManager : MonoBehaviour
}
else // A client is connecting to the room
{
Debug.Log("Room loaded with port: " + RoomData.port + ", Name: " + RoomData.roomName);
_transport.port = (ushort)RoomData.port;
//_transport.port = 7780;
//Debug.Log("Room " + RoomData.roomName + " loaded");
Debug.Log($"S-Process: User;\nAction: MM-Embed; \nS-Compl: Persona At MLoc With SA;\nD-Process: LOSrvc"); // Persona moved inside the Room (visible)
string moveDataJson = CreateEmbedDataJson();
StartCoroutine(GameManager.Instance.WebAPIManager.Upload("Location/action-request", moveDataJson, HandleResponse));
_transport.port = (ushort)RoomData.netInfo.Port;
_networkManager.StartClient(); // Start Mirror client
}
}
private string CreateEmbedDataJson()
{
string position = transform.position.ToString().Replace(",", ".");
string rotation = transform.localRotation.ToString().Replace(",", ".");
string jsonData = "{" +
"\"time\": \"" + DateTime.Now + "\"," +
"\"action\": \"MM-Embed\"," +
"\"sProcess\": \"" + GameManager.Instance.userID + "\"," +
"\"sComplements\": \"Persona At " + GameManager.Instance.currentPlayerLocation + " With SA position: " + position + " rotation: " + rotation + "\"," +
"\"dProcess\": \"Location Service\"" +
"}";
return jsonData;
}
private void HandleResponse(string response)
{
Debug.Log("Received response: " + response); // Log the response received from the server
}
private void LogToFileHandler(string logString, string stackTrace, LogType type)
{
using (StreamWriter writer = new StreamWriter(_logFilePath, true))
......@@ -82,6 +108,6 @@ public class RoomGameManager : MonoBehaviour
public static class RoomData
{
public static int port;
public static string roomName;
public static NetInfo netInfo;
}
\ No newline at end of file
......@@ -99,12 +99,11 @@ public class ServerSocket : MonoBehaviour
void OnDestroy()
{
// TODO Close the server socket only when the entire application was closed, not only the current scene
// TODO: Close the server socket only when the entire application was closed, not only the current scene
//isRunning = false;
//stream?.Close();
//client?.Close();
//server?.Stop();
Debug.Log("[ON_DESTROY_SERVER_SOCKET]: Server stopped.");
//server?.Stop();
}
private void Update()
......@@ -123,23 +122,15 @@ public class MessageInfo
public DateTime time;
public string source;
public string destination;
public string action;
public string inItem;
public string inLocation;
public string outLocation;
public string rightsID;
public string body;
public MessageInfo(DateTime time, string source, string destination, string action, string inItem, string inLocation, string outLocation, string rightsID)
public MessageInfo(DateTime time, string source, string destination, string body)
{
this.time = time;
this.source = source;
this.destination = destination;
this.action = action;
this.inItem = inItem;
this.inLocation = inLocation;
this.outLocation = outLocation;
this.rightsID = rightsID;
this.body = body;
}
}
using UnityEngine;
public class SquareGameManager : MonoBehaviour
{
[SerializeField]
private ServerSocket serverSocket;
// Start is called before the first frame update
void Start()
{
Debug.Log("Scene OnlineScene started");
}
// Update is called once per frame
void Update()
{
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment