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

Deploy 05/03/2025

parent e1ff7d1b
...@@ -616,7 +616,6 @@ GameObject: ...@@ -616,7 +616,6 @@ GameObject:
- component: {fileID: 88074381} - component: {fileID: 88074381}
- component: {fileID: 88074380} - component: {fileID: 88074380}
- component: {fileID: 88074382} - component: {fileID: 88074382}
- component: {fileID: 88074383}
- component: {fileID: 88074384} - component: {fileID: 88074384}
m_Layer: 5 m_Layer: 5
m_Name: SceneManager m_Name: SceneManager
...@@ -671,8 +670,7 @@ MonoBehaviour: ...@@ -671,8 +670,7 @@ MonoBehaviour:
networkManager: {fileID: 0} networkManager: {fileID: 0}
transport: {fileID: 0} transport: {fileID: 0}
cameraOrbit: {fileID: 7825374990767153394} cameraOrbit: {fileID: 7825374990767153394}
pathToRoomExe: C:\\Users\\lab2a\\Documents\\Unity Projects\\MPAI-MMM\\Builds\\MPAI-MMM.exe --- !u!114 &88074384
--- !u!114 &88074383
MonoBehaviour: MonoBehaviour:
m_ObjectHideFlags: 0 m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0} m_CorrespondingSourceObject: {fileID: 0}
...@@ -681,23 +679,75 @@ MonoBehaviour: ...@@ -681,23 +679,75 @@ MonoBehaviour:
m_GameObject: {fileID: 88074379} m_GameObject: {fileID: 88074379}
m_Enabled: 1 m_Enabled: 1
m_EditorHideFlags: 0 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_Script: {fileID: 11500000, guid: 92e80ec55d5f926418353d7e6d212a13, type: 3}
m_Name: m_Name:
m_EditorClassIdentifier: m_EditorClassIdentifier:
serverSocket: {fileID: 0} syncDirection: 0
--- !u!114 &88074384 syncMode: 0
syncInterval: 0
--- !u!114 &107673264
MonoBehaviour: MonoBehaviour:
m_ObjectHideFlags: 0 m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0} m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0} m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0} m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 88074379} m_GameObject: {fileID: 107673262}
m_Enabled: 1 m_Enabled: 1
m_EditorHideFlags: 0 m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: c458dc28f1b357249ac5af2884c30b9e, type: 3} m_Script: {fileID: 11500000, guid: 9b91ecbcc199f4492b9a91e820070131, type: 3}
m_Name: m_Name:
m_EditorClassIdentifier: 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 --- !u!1001 &119929167
PrefabInstance: PrefabInstance:
m_ObjectHideFlags: 0 m_ObjectHideFlags: 0
...@@ -7203,3 +7253,4 @@ SceneRoots: ...@@ -7203,3 +7253,4 @@ SceneRoots:
- {fileID: 375110087} - {fileID: 375110087}
- {fileID: 7825374990767153395} - {fileID: 7825374990767153395}
- {fileID: 88074381} - {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 ...@@ -15,7 +15,7 @@ public class GameManager : MonoBehaviour
public string pathToRoomExe; public string pathToRoomExe;
public string currentPlayerPosition; public string currentPlayerLocation;
public GameObject localPlayerPrefab; public GameObject localPlayerPrefab;
......
...@@ -4,6 +4,7 @@ using ReadyPlayerMe.Samples.QuickStart; ...@@ -4,6 +4,7 @@ using ReadyPlayerMe.Samples.QuickStart;
using System; using System;
using System.Collections; using System.Collections;
using System.Diagnostics; using System.Diagnostics;
using System.Runtime.InteropServices.WindowsRuntime;
using UnityEngine; using UnityEngine;
using UnityEngine.UIElements; using UnityEngine.UIElements;
...@@ -77,25 +78,24 @@ public class InGameMenuEvents : MonoBehaviour ...@@ -77,25 +78,24 @@ public class InGameMenuEvents : MonoBehaviour
//Remove the first line //Remove the first line
if (lines.Length > 10) if (lines.Length > 10)
{ {
lines = new ArraySegment<string>(lines, 1, lines.Length - 1).ToArray(); lines = new ArraySegment<string>(lines, 1, lines.Length - 1).ToArray();
//+= "[" + DateTime.Now + "]: " + message + "\n";
} }
// Add a new line // Add a new line
string[] updatedLines = new string[lines.Length + 1]; string[] updatedLines = new string[lines.Length + 1];
Array.Copy(lines, updatedLines, lines.Length); Array.Copy(lines, updatedLines, lines.Length);
updatedLines[updatedLines.Length - 1] = 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 // Join the lines back with newlines and print the result
_messageLabel.text = string.Join("\n", updatedLines); _messageLabel.text = string.Join("\n", updatedLines);
} }
} }
/* MM-SEND */
#region MM-SEND
private void OnMMSendButtonClicked(ClickEvent evt) private void OnMMSendButtonClicked(ClickEvent evt)
{ {
VisualElement sendMsgVisualElement = _document.rootVisualElement.Q("SendMsgVisualElement") as VisualElement; VisualElement sendMsgVisualElement = _document.rootVisualElement.Q("SendMsgVisualElement") as VisualElement;
...@@ -117,20 +117,21 @@ public class InGameMenuEvents : MonoBehaviour ...@@ -117,20 +117,21 @@ public class InGameMenuEvents : MonoBehaviour
private void SendMsg(ClickEvent evt) 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 // Retrieve data from the GUI
TextField toTextField = _document.rootVisualElement.Q("toTextField") as TextField; TextField toTextField = _document.rootVisualElement.Q("toTextField") as TextField;
TextField msgTextField = _document.rootVisualElement.Q("msgTextField") as TextField; TextField msgTextField = _document.rootVisualElement.Q("msgTextField") as TextField;
// Create Json data to be sent // Create Json data to be sent
string actionDataJson = CreateMessageJson(toTextField.value, msgTextField.value); string actionDataJson = CreateMessageJson(toTextField.value, msgTextField.value);
StartCoroutine(GameManager.Instance.WebAPIManager.Upload("Activity/actions", actionDataJson, HandleResponse)); StartCoroutine(GameManager.Instance.WebAPIManager.Upload("Communication/messages", actionDataJson, HandleResponse));
UnityEngine.Debug.Log("Message sent to the WebApiServer");
// Send message to the target user // Send message to the target user
SendTextMessage(toTextField.value, actionDataJson); SendTextMessage(toTextField.value, actionDataJson);
UnityEngine.Debug.Log("Message sent to " + toTextField.value); 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); UpdateMessageLabel(myMessage);
// Reset the TextField // Reset the TextField
msgTextField.value = ""; msgTextField.value = "";
...@@ -138,22 +139,16 @@ public class InGameMenuEvents : MonoBehaviour ...@@ -138,22 +139,16 @@ public class InGameMenuEvents : MonoBehaviour
private void HandleResponse(string response) 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
// TODO: send the message to the Unity server
} }
private string CreateMessageJson(string toTextField, string msgTextField) private string CreateMessageJson(string toTextField, string msgTextField)
{ {
string jsonData = "{" + string jsonData = "{" +
"\"time\": \"" + DateTime.Now + "\"," + "\"body\": \"" + msgTextField + "\"," +
"\"source\": \"" + GameManager.Instance.userID + "\"," + "\"source\": \"" + GameManager.Instance.userID + "\"," +
"\"destination\": \"" + toTextField + "\"," + "\"destination\": \"" + toTextField + "\"," +
"\"action\": \"MM-Send\"," + "\"time\": \"" + DateTime.Now + "\"" +
"\"inItem\": \"" + msgTextField + "\"," +
"\"inLocation\": \"" + GameManager.Instance.currentPlayerPosition + "\"," +
"\"outLocation\": \"Square\"," + // TODO: retrieve position of the target pleyer
"\"rightsID\": \"string\"" +
"}"; "}";
return jsonData; return jsonData;
} }
...@@ -189,12 +184,11 @@ public class InGameMenuEvents : MonoBehaviour ...@@ -189,12 +184,11 @@ public class InGameMenuEvents : MonoBehaviour
// Once connected, send the message // Once connected, send the message
GameManager.Instance.ClientSocket.SendSocketMessage(msgTextField); GameManager.Instance.ClientSocket.SendSocketMessage(msgTextField);
} }
#endregion
/* CREATE ROOM */ #region ROOM
private void OnCreateRoomButtonClicked(ClickEvent evt) private void OnCreateRoomButtonClicked(ClickEvent evt)
{ {
UnityEngine.Debug.Log("Create Room button clicked.");
_playerTracker = GameManager.Instance.localPlayerPrefab.GetComponent<PlayerTracker>(); _playerTracker = GameManager.Instance.localPlayerPrefab.GetComponent<PlayerTracker>();
if (_playerTracker == null) if (_playerTracker == null)
...@@ -203,25 +197,58 @@ public class InGameMenuEvents : MonoBehaviour ...@@ -203,25 +197,58 @@ public class InGameMenuEvents : MonoBehaviour
} }
if (_playerTracker != null) if (_playerTracker != null)
{ {
_playerTracker.OnRoomInstantiated += HandleRoomInstantiated; StartCoroutine(BuyAndCreateRoom(_playerTracker));
_playerTracker.InstantiateRoomPrefab(); }
} }
else
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 _playerTracker.OnRoomInstantiated -= HandleRoomInstantiated; // Unsubscribe to avoid memory leaks
// Activate the camera orbit script // Activate the camera orbit script
cameraOrbit.enabled = true; 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() void OnApplicationQuit()
{ {
if (_serverProcess != null && !_serverProcess.HasExited) if (_serverProcess != null && !_serverProcess.HasExited)
......
...@@ -34,7 +34,8 @@ public class MainMenuEvents : MonoBehaviour ...@@ -34,7 +34,8 @@ public class MainMenuEvents : MonoBehaviour
_buttonLogin.UnregisterCallback<ClickEvent>(OnLoginButtonClick); _buttonLogin.UnregisterCallback<ClickEvent>(OnLoginButtonClick);
_buttonRegister.UnregisterCallback <ClickEvent>(OnRegisterButtonClick); _buttonRegister.UnregisterCallback <ClickEvent>(OnRegisterButtonClick);
} }
#region Login
private void OnLoginButtonClick(ClickEvent evt) private void OnLoginButtonClick(ClickEvent evt)
{ {
_registrationForm.style.visibility = Visibility.Hidden; _registrationForm.style.visibility = Visibility.Hidden;
...@@ -74,35 +75,19 @@ public class MainMenuEvents : MonoBehaviour ...@@ -74,35 +75,19 @@ public class MainMenuEvents : MonoBehaviour
Debug.LogError("Failed to login. Account is null."); Debug.LogError("Failed to login. Account is null.");
yield break; 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 // Update the DataManager with the retrieved account data
GameManager.Instance.humanID = humanID; GameManager.Instance.humanID = humanID;
GameManager.Instance.personaUrl = GameManager.Instance.WebAPIManager.BASE_URL + "Registration/avatars/" + userAccount.personae[0].model; GameManager.Instance.personaUrl = GameManager.Instance.WebAPIManager.BASE_URL + "Registration/avatars/" + userAccount.personae[0].model;
GameManager.Instance.userID = userAccount.users[0].id; GameManager.Instance.userID = userAccount.users[0].id;
_networkClientManager.ConnectToServer(); // Start Mirror Server _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) private void OnRegisterButtonClick(ClickEvent evt)
{ {
_loginForm.style.visibility = Visibility.Hidden; _loginForm.style.visibility = Visibility.Hidden;
...@@ -148,6 +133,8 @@ public class MainMenuEvents : MonoBehaviour ...@@ -148,6 +133,8 @@ public class MainMenuEvents : MonoBehaviour
private void OnSubmitRegisterButtonClick(ClickEvent evt) 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 // Collect personal data in JSON format
string personalDataJson = CreatePersonalDataJson(); string personalDataJson = CreatePersonalDataJson();
...@@ -189,6 +176,8 @@ public class MainMenuEvents : MonoBehaviour ...@@ -189,6 +176,8 @@ public class MainMenuEvents : MonoBehaviour
} }
}); });
if (newAccount == null) yield break; if (newAccount == null) yield break;
Debug.Log("S-Process: RGSrvc;\nS-Compl: Account;\nD-Process: human");
// Step 3: Create the user // Step 3: Create the user
User newUser = null; User newUser = null;
...@@ -226,29 +215,9 @@ public class MainMenuEvents : MonoBehaviour ...@@ -226,29 +215,9 @@ public class MainMenuEvents : MonoBehaviour
GameManager.Instance.personaUrl = GameManager.Instance.WebAPIManager.BASE_URL + "Registration/avatars/" + personaTextField.value; GameManager.Instance.personaUrl = GameManager.Instance.WebAPIManager.BASE_URL + "Registration/avatars/" + personaTextField.value;
GameManager.Instance.userID = newUser.id; 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 // Step 5: Connect to the server
_networkClientManager.ConnectToServer(); _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() private string CreatePersonalDataJson()
...@@ -271,9 +240,7 @@ public class MainMenuEvents : MonoBehaviour ...@@ -271,9 +240,7 @@ public class MainMenuEvents : MonoBehaviour
" \"nationality\": \"" + nationalityTextField.value + "\"," + " \"nationality\": \"" + nationalityTextField.value + "\"," +
" \"email\": \"" + emailTextField.value + "\" " + " \"email\": \"" + emailTextField.value + "\" " +
"}, " + "}, " +
"\"descrMetadata\": \"" + DateTime.Now + "\"}"; "\"descrMetadata\": \"" + DateTime.Now + "\"}";
Debug.Log("jsonData to be sent [GetPersonalData]: " + jsonData);
// Passing data to the online scene // Passing data to the online scene
GameManager.Instance.playerName = firstNameTextField.value; GameManager.Instance.playerName = firstNameTextField.value;
...@@ -305,22 +272,7 @@ public class MainMenuEvents : MonoBehaviour ...@@ -305,22 +272,7 @@ public class MainMenuEvents : MonoBehaviour
GameManager.Instance.personaUrl = GameManager.Instance.WebAPIManager.BASE_URL + "Registration/avatars/" + personaTextField.value; GameManager.Instance.personaUrl = GameManager.Instance.WebAPIManager.BASE_URL + "Registration/avatars/" + personaTextField.value;
return jsonData; 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) private string CreateUpdatedAccountJson(Account accountToUpdate, User newUser, string persona)
{ {
string jsonData = "{" + string jsonData = "{" +
...@@ -337,7 +289,7 @@ public class MainMenuEvents : MonoBehaviour ...@@ -337,7 +289,7 @@ public class MainMenuEvents : MonoBehaviour
Debug.Log(jsonData); Debug.Log(jsonData);
return jsonData; return jsonData;
} }
#endregion
} }
......
using Mirror; using Mirror;
using System; using System;
using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using UnityEngine; using UnityEngine;
using UnityEngine.SceneManagement; using UnityEngine.UIElements;
public class PlayerTracker : NetworkBehaviour public class PlayerTracker : NetworkBehaviour
{ {
public GameObject roomPrefab; public GameObject roomPrefab;
public event Action OnRoomInstantiated; // Define an event public event Action OnRoomInstantiated; // Define an event
private bool hasTriedToConnect = false; private bool hasTriedToConnect = false;
private static HashSet<int> usedPorts = new HashSet<int>(); // Track used ports
private static int basePort = 7780; // Base port number
int port = 0;
void Start() void Start()
{ {
hasTriedToConnect = false; hasTriedToConnect = false;
} }
private void OnTriggerEnter(Collider other) private void OnTriggerEnter(Collider other)
{ {
...@@ -26,20 +24,21 @@ public class PlayerTracker : NetworkBehaviour ...@@ -26,20 +24,21 @@ public class PlayerTracker : NetworkBehaviour
{ {
if (other.CompareTag("Parcel")) if (other.CompareTag("Parcel"))
{ {
UnityEngine.Debug.Log("Player enter: " + other.gameObject.name); UnityEngine.Debug.Log("Player enter: " + other.gameObject.name);
string actionDataJson = CreateEmbedJson(other.gameObject.name, GameManager.Instance.userID); 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
StartCoroutine(GameManager.Instance.WebAPIManager.Upload("Activity/actions", actionDataJson, HandleResponse));
GameManager.Instance.currentPlayerPosition = other.gameObject.name; 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) if (other.CompareTag("RoomPlaceholder") && !hasTriedToConnect)
{ {
hasTriedToConnect = true; // To avoid trying multiple conenction ot the same room hasTriedToConnect = true; // To avoid trying multiple conenction ot the same room
NetInfo netInfo = other.GetComponent<NetInfo>(); NetInfo netInfo = other.GetComponent<NetInfo>();
UnityEngine.Debug.Log("NetInfo[Mirror Server]: " + netInfo.IpAddress + ":" + netInfo.Port + "\nNetInfo[Communication Server]: " + netInfo.IpAddressComServer + ":" + netInfo.PortComServer); UnityEngine.Debug.Log("NetInfo[Mirror Server]: " + netInfo.IpAddress + ":" + netInfo.Port + "\nNetInfo[Communication Server]: " + netInfo.IpAddressComServer + ":" + netInfo.PortComServer);
RoomData.port = netInfo.Port; RoomData.roomName = "Room_[" + netInfo.IpAddress+":"+netInfo.Port+"]";
RoomData.roomName = "Lobby Room"; RoomData.netInfo = netInfo;
//SceneManager.LoadScene("Room");
StartCoroutine(GameManager.Instance.ClientSocket.TryConnectToServerCoroutine(netInfo.IpAddressComServer, netInfo.PortComServer, 10, 2f)); StartCoroutine(GameManager.Instance.ClientSocket.TryConnectToServerCoroutine(netInfo.IpAddressComServer, netInfo.PortComServer, 10, 2f));
} }
...@@ -48,43 +47,40 @@ public class PlayerTracker : NetworkBehaviour ...@@ -48,43 +47,40 @@ public class PlayerTracker : NetworkBehaviour
} }
private void OnTriggerExit(Collider other) private void OnTriggerExit(Collider other)
{ {
if (other.CompareTag("Parcel")) if (isLocalPlayer)
UnityEngine.Debug.Log("Exit from:" + other.gameObject.name); {
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) 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 = "{" + string jsonData = "{" +
"\"time\": \"" + DateTime.Now + "\"," + "\"time\": \"" + DateTime.Now + "\"," +
"\"source\": \"" + userID + "\"," + "\"action\": \"MM-Move\"," +
"\"destination\": \"Activity Service\"," + "\"sProcess\": \"" + GameManager.Instance.userID + "\"," +
"\"action\": \"MM-Embed\"," + "\"sComplements\": \"Persona From " + GameManager.Instance.currentPlayerLocation + " To " + ParcelName + " With SA position: " + position + " rotation: " + rotation + "\"," +
"\"inItem\": \"At " + ParcelName + "\"," + "\"dProcess\": \"Location Service\"" +
"\"inLocation\": \"At " + ParcelName + "\"," + "}";
"\"outLocation\": \"At " + ParcelName + "\"," + return jsonData;
"\"rightsID\": \"string\"" + }
"}";
return jsonData;
}
[Command] [Command]
public void CmdInstantiateRoom(Vector3 position, Quaternion orientation) public void CmdInstantiateRoom(Vector3 position, Quaternion orientation)
{ {
if (!isServer) return; if (!isServer) return;
// TODO search for a free port // Search for a free port
int port = FindFreePort(); int port = PortManager.Instance.FindFreePort();
if (port == -1) if (port == -1)
{ {
UnityEngine.Debug.LogError("No available ports to create a new room."); UnityEngine.Debug.LogError("No available ports to create a new room.");
...@@ -96,10 +92,12 @@ public class PlayerTracker : NetworkBehaviour ...@@ -96,10 +92,12 @@ public class PlayerTracker : NetworkBehaviour
NetworkServer.Spawn(roomObject); NetworkServer.Spawn(roomObject);
netInfo.SetNetworkInfo("127.0.0.1", port, "127.0.0.1", port + 1); // TODO: replace the ipAddresses 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..."); UnityEngine.Debug.Log("Launching the server...");
LaunchRoomServer(port); LaunchRoomServer(port); // Launch the Mirror server
RpcNotifyRoomCreated(); // Notify clients RpcNotifyRoomCreated(); // Notify clients
} }
[ClientRpc] [ClientRpc]
...@@ -108,12 +106,13 @@ public class PlayerTracker : NetworkBehaviour ...@@ -108,12 +106,13 @@ public class PlayerTracker : NetworkBehaviour
OnRoomInstantiated?.Invoke(); // Invoke event when room is instatiated OnRoomInstantiated?.Invoke(); // Invoke event when room is instatiated
} }
// Public method to allow interaction from other scripts
public void InstantiateRoomPrefab() public void InstantiateRoomPrefab()
{ {
if (isLocalPlayer) 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); CmdInstantiateRoom(transform.position, transform.localRotation);
} }
else else
...@@ -122,47 +121,44 @@ public class PlayerTracker : NetworkBehaviour ...@@ -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) private void LaunchRoomServer(int port)
{ {
//Launch the server //Launch the server
string sceneName = "Room Server"; string sceneName = "Room Server";
ProcessStartInfo startInfo = new ProcessStartInfo(); ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = GameManager.Instance.pathToRoomExe; startInfo.FileName = GameManager.Instance.pathToRoomExe;
//startInfo.FileName = "C:\\Users\\lab2a\\Documents\\Unity Projects\\MPAI-MMM\\Builds\\MPAI-MMM.exe";
startInfo.Arguments = $"-scene {sceneName} -port {port}"; startInfo.Arguments = $"-scene {sceneName} -port {port}";
startInfo.UseShellExecute = false; startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true; startInfo.RedirectStandardError = true;
startInfo.CreateNoWindow = true; startInfo.CreateNoWindow = true;
Process serverProcess = new Process(); Process serverProcess = new Process();
serverProcess.StartInfo = startInfo; serverProcess.StartInfo = startInfo;
serverProcess.Start(); serverProcess.EnableRaisingEvents = true;
serverProcess.Exited += (sender, args) => OnRoomServerClosed(port); // Attach event
serverProcess.Start();
} }
private int FindFreePort() public void OnRoomServerClosed(int port)
{ {
int maxPort = basePort + 100; // Arbitrary max range for ports UnityEngine.Debug.Log($"Room server closed for port {port}");
PortManager.Instance.PortsToDestroy.Enqueue(port);
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
} }
[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; ...@@ -4,6 +4,9 @@ using kcp2k;
using System.IO; using System.IO;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using GLTFast.Schema;
using static UnityEngine.UIElements.UxmlAttributeDescription;
using Unity.VisualScripting.Antlr3.Runtime;
public class RoomGameManager : MonoBehaviour public class RoomGameManager : MonoBehaviour
{ {
...@@ -57,14 +60,37 @@ public class RoomGameManager : MonoBehaviour ...@@ -57,14 +60,37 @@ public class RoomGameManager : MonoBehaviour
} }
else // A client is connecting to the room else // A client is connecting to the room
{ {
Debug.Log("Room loaded with port: " + RoomData.port + ", Name: " + RoomData.roomName); //Debug.Log("Room " + RoomData.roomName + " loaded");
_transport.port = (ushort)RoomData.port; Debug.Log($"S-Process: User;\nAction: MM-Embed; \nS-Compl: Persona At MLoc With SA;\nD-Process: LOSrvc"); // Persona moved inside the Room (visible)
//_transport.port = 7780; string moveDataJson = CreateEmbedDataJson();
StartCoroutine(GameManager.Instance.WebAPIManager.Upload("Location/action-request", moveDataJson, HandleResponse));
_transport.port = (ushort)RoomData.netInfo.Port;
_networkManager.StartClient(); // Start Mirror client _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) private void LogToFileHandler(string logString, string stackTrace, LogType type)
{ {
using (StreamWriter writer = new StreamWriter(_logFilePath, true)) using (StreamWriter writer = new StreamWriter(_logFilePath, true))
...@@ -82,6 +108,6 @@ public class RoomGameManager : MonoBehaviour ...@@ -82,6 +108,6 @@ public class RoomGameManager : MonoBehaviour
public static class RoomData public static class RoomData
{ {
public static int port;
public static string roomName; public static string roomName;
public static NetInfo netInfo;
} }
\ No newline at end of file
...@@ -99,12 +99,11 @@ public class ServerSocket : MonoBehaviour ...@@ -99,12 +99,11 @@ public class ServerSocket : MonoBehaviour
void OnDestroy() 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; //isRunning = false;
//stream?.Close(); //stream?.Close();
//client?.Close(); //client?.Close();
//server?.Stop(); //server?.Stop();
Debug.Log("[ON_DESTROY_SERVER_SOCKET]: Server stopped.");
} }
private void Update() private void Update()
...@@ -123,23 +122,15 @@ public class MessageInfo ...@@ -123,23 +122,15 @@ public class MessageInfo
public DateTime time; public DateTime time;
public string source; public string source;
public string destination; public string destination;
public string action; public string body;
public string inItem;
public string inLocation;
public string outLocation;
public string rightsID;
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.time = time;
this.source = source; this.source = source;
this.destination = destination; this.destination = destination;
this.action = action; this.body = body;
this.inItem = inItem;
this.inLocation = inLocation;
this.outLocation = outLocation;
this.rightsID = rightsID;
} }
} }
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