5using System.Collections;
6using System.Collections.Generic;
10using System.Net.Sockets;
11using System.Runtime.InteropServices;
13using System.Threading;
18using System.Diagnostics;
25 public List<GameObject> SendPoseObjects;
26 public List<SendPose> SendPoseObjectsNoChildren;
29 public struct SendPose
36 const ushort PORT_NO = 42069;
37 private TcpListener listener;
38 private Thread worker;
39 private List<Socket> sockets;
40 private List<Thread> threads;
42 private object[] lastLoadedObjects;
43 private string modelName;
45 private string requestedFile;
48 [DllImport(
"kernel32.dll")]
49 [
return: MarshalAs(UnmanagedType.Bool)]
50 static extern bool AllocConsole();
52 [DllImport(
"kernel32.dll", SetLastError =
true)]
53 static extern bool AttachConsole(
int pid);
54 [DllImport(
"kernel32", SetLastError =
true)]
55 static extern bool FreeConsole();
64 var stdout = Console.OpenStandardOutput();
65 var sw =
new System.IO.StreamWriter(stdout, Encoding.GetEncoding(
"ISO-8859-1"));
67 Console.InputEncoding = Encoding.GetEncoding(
"ISO-8859-1");
68 Console.OutputEncoding = Encoding.GetEncoding(
"ISO-8859-1");
72 sockets =
new List<Socket>();
73 threads =
new List<Thread>();
74 listener =
new TcpListener(IPAddress.Any, PORT_NO);
76 worker =
new Thread(WaitingForClient);
79 StartCoroutine(NetworkUpdate());
85 private IEnumerator NetworkUpdate()
89 yield
return new WaitForSeconds(0.1f);
91 foreach (var go
in SendPoseObjects)
95 foreach (var go
in SendPoseObjectsNoChildren)
102 private void OnDestroy()
105 foreach (var t
in threads)
111 public void WaitingForClient()
113 Console.WriteLine(
"WaitingForClient started");
117 Socket sckt = listener.AcceptSocket();
119 Console.WriteLine(
"Client connected: " + sckt.RemoteEndPoint.ToString());
121 Thread td =
new Thread(
new ThreadStart(ReadSocket));
129 public void SendMsgToAllClients(
string msg)
132 var bytearray = Encoding.GetEncoding(
"ISO-8859-1").GetBytes(msg);
133 foreach (var s
in sockets.ToArray())
140 catch (SocketException)
145 public void SendMsgToAllClients(
string tag,
string msg,
string ID)
148 var bytearray = Encoding.GetEncoding(
"ISO-8859-1").GetBytes(tag + ID +
";" + msg +
"{EOS}");
150 foreach (var s
in sockets.ToArray())
157 catch (SocketException)
162 public void SendMsgToAllClients(
string tag,
byte[] array,
string ID =
"")
164 foreach (var s
in sockets.ToArray())
166 var IDByte = (Encoding.GetEncoding(
"ISO-8859-1").GetBytes(ID));
167 var TagByte = (Encoding.GetEncoding(
"ISO-8859-1").GetBytes(tag));
168 var combinedArray = Combine(
new byte[] { (byte)TagByte.Length }, TagByte,
new byte[] { (byte)IDByte.Length }, IDByte, array);
169 var convertedArray = Convert.ToBase64String(combinedArray);
174 s.Send(Encoding.GetEncoding(
"ISO-8859-1").GetBytes(
"{B64}" + convertedArray +
"{EOS}"));
176 catch (SocketException)
182 [NaughtyAttributes.Button]
185 ProcessResponse(
"{REQ}a1.json");
188 [NaughtyAttributes.Button]
191 requestedFile =
"pb_Scene";
192 ProcessResponse(
"{REQ}pb_Scene");
195 private byte[] Combine(params
byte[][] arrays)
197 byte[] rv =
new byte[arrays.Sum(a => a.Length)];
199 foreach (
byte[] array
in arrays)
201 System.Buffer.BlockCopy(array, 0, rv, offset, array.Length);
202 offset += array.Length;
206 [NaughtyAttributes.Button]
207 void TesztLoadModel()
209 requestedFile =
"cube.fbx";
210 LoadModel(
@"D:\GIT\UNITY\vrtanoda\Assets\StreamingAssets\cube.fbx");
212 private void ProcessResponse(
byte[] array)
214 var command = Encoding.GetEncoding(
"ISO-8859-1").GetString(array);
218 if (command.StartsWith(
"{REQ}"))
221 var goName = command.Remove(0, 5);
223 if (goName.EndsWith(
".json"))
225 Console.WriteLine(
"Client requested scene: " + goName);
227 var path = Application.streamingAssetsPath.Remove(Application.streamingAssetsPath.LastIndexOf(
'/'));
228 path = path.Remove(path.LastIndexOf(
'/'));
230 var path = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
232 string[] filename = { goName };
234 var json = File.ReadAllText(name.First());
235 var loaded_array = (
object[])JsonConvert.DeserializeObject<
object[]>(json, pb_Serialization.ConverterSettings);
236 lastLoadedObjects = loaded_array;
238 var actions = controller.actions;
239 SendMsgToAllClients(
"{JSON}" + json +
"{EOS}");
240 foreach (var action
in actions)
248 var proc =
VoiceTTS.SpeakToFile(voiceAct.textToSpeak, voiceAct.
ID, voiceAct.selectedLanguage);
249 StartCoroutine(waiter(proc, voiceAct));
255 StartCoroutine(videoUpload(sha));
262 Console.WriteLine(
"Client requested GameObject: " + goName);
263 if (goName ==
"pb_Scene")
265 requestedFile =
"pb_Scene";
269 if (lastLoadedObjects ==
null)
271 Console.WriteLine(
"Can't send, no JSON loaded!");
275 var path = Application.streamingAssetsPath.Remove(Application.streamingAssetsPath.LastIndexOf(
'/'));
276 path = path.Remove(path.LastIndexOf(
'/'));
278 var path = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
282 if (goName.Length == 64)
286 string[] filename = { fn };
288 Debug.Log(filepath.First());
289 requestedFile = Path.GetFileName(filepath.First());
290 LoadModel(filepath.First());
324 private void ProcessResponse(
string command)
326 ProcessResponse(Encoding.GetEncoding(
"ISO-8859-1").GetBytes(command));
333 if (node.hash == hash)
337 var retval = GetGONameFromHash(node, hash);
338 if (retval !=
"")
return retval;
343 public IEnumerator waiter(Process p,
VoiceAction voiceAct)
350 string appPath = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf(
'/')) ;
351 var clipPath = System.IO.Path.Combine(appPath, voiceAct.
ID);
352 var audioFile = File.ReadAllBytes(clipPath);
354 File.Delete(voiceAct.
ID);
357 if (fileServer.
loadedFiles.ContainsKey(voiceAct.
ID +
".wav"))
362 SendMsgToAllClients(
"{FSR}", voiceAct.
ID +
".wav", voiceAct.
ID);
363 Console.WriteLine(voiceAct.
ID +
" sent");
371 string appPath = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf(
'/')) ;
372 var clipPath = System.IO.Path.Combine(appPath, sha.selectedGO.name);
373 var videoFile = File.ReadAllBytes(clipPath);
375 if (fileServer.
loadedFiles.ContainsKey(sha.selectedGO.name))
376 fileServer.
loadedFiles[sha.selectedGO.name] = videoFile;
378 fileServer.
loadedFiles.Add(sha.selectedGO.name, videoFile);
380 SendMsgToAllClients(
"{FSR}", sha.selectedGO.name, sha.
ID);
381 Console.WriteLine(sha.selectedGO.name +
" sent");
385 public void ReadSocket()
387 var myindex = threads.Count - 1;
388 var s = sockets[myindex];
389 var remoteIP = s.RemoteEndPoint.ToString();
392 List<byte> receivedBytes =
new List<byte>();
398 byte[] receive =
new byte[1];
403 int ret = s.Receive(receive, receive.Length, 0);
406 string recieved = Encoding.GetEncoding(
"ISO-8859-1").GetString(receive);
407 if (recieved ==
"{" && end ==
"" || recieved ==
"E" && end ==
"{" || recieved ==
"O" && end ==
"{E" || recieved ==
"S" && end ==
"{EO" || recieved ==
"}" && end ==
"{EOS")
416 var array = receivedBytes.ToArray();
417 Dispatcher.InvokeAsync(() =>
419 ProcessResponse(array);
422 receivedBytes.Clear();
429 receivedBytes.AddRange(Encoding.GetEncoding(
"ISO-8859-1").GetBytes(end));
432 receivedBytes.Add(receive[0]);
441 Debug.Log(
"ReadSocket exception!");
449 Console.WriteLine(
"Connection Closed with: {0}!", remoteIP);
452 private void OnDisable()
459 private void LoadModel(
string path)
461 using (var assetLoader =
new AssetLoaderAsync())
464 assetLoaderOptions.MaterialTransparencyMode = MaterialTransparencyMode.Cutout;
465 assetLoaderOptions.AdvancedConfigs.Add(AssetAdvancedConfig.CreateConfig(AssetAdvancedPropertyClassNames.FBXImportPreservePivots,
false));
466 var thread = assetLoader.LoadFromFile(path, assetLoaderOptions,
null, progressCallback: ProgressCallback, onAssetLoaded: OnLoadFinished);
470 private void ProgressCallback(
float progress)
472 Dispatcher.InvokeAsync(() =>
478 Console.WriteLine(
"Loading model progress: {0}%", (progress * 100).ToString(
"F1"));
482 private void OnLoadFinished(GameObject go)
484 var goChildren = go.GetComponentsInChildren<Transform>();
485 GameObject goSelected =
null;
486 foreach (var child
in goChildren)
488 if (child.gameObject.name == modelName) goSelected = child.gameObject;
490 if (goSelected !=
null)
494 ShaderChanger.
Change(goSelected.GetComponentsInChildren<MeshRenderer>(),
"Ciconia Studio/Double Sided/Standard/Diffuse Bump");
499 if (fileServer.
loadedFiles.ContainsKey(requestedFile))
500 fileServer.
loadedFiles[requestedFile] = GameObjectSerializer.SerializeGameObject(goSelected,
true);
502 fileServer.
loadedFiles.Add(requestedFile, GameObjectSerializer.SerializeGameObject(goSelected,
true));
504 SendMsgToAllClients(
"{FSR}", requestedFile, hash);
510 ShaderChanger.
Change(go.GetComponentsInChildren<MeshRenderer>(),
"Ciconia Studio/Double Sided/Standard/Diffuse Bump");
515 if (fileServer.
loadedFiles.ContainsKey(requestedFile))
516 fileServer.
loadedFiles[requestedFile] = GameObjectSerializer.SerializeGameObject(go,
true);
518 fileServer.
loadedFiles.Add(requestedFile, GameObjectSerializer.SerializeGameObject(go,
true));
520 SendMsgToAllClients(
"{FSR}", requestedFile, hash);
525 private void DrawLogo()
527 Console.Title = Application.productName +
" - v" + Application.version +
" Server";
529 Console.WriteLine(
" ___ _ ");
530 Console.WriteLine(
" / _ \\ | | ");
531 Console.WriteLine(
" / /_\\ \\_ __ _ __ ___ _ __ | |_ _ _ _ __ ___ ");
532 Console.WriteLine(
" | _ | '_ \\| '_ \\ / _ \\ '_ \\| __| | | | '_ ` _ \\ ");
533 Console.WriteLine(
" | | | | |_) | |_) | __/ | | | |_| |_| | | | | | |");
534 Console.WriteLine(
" \\_| |_/ .__/| .__/ \\___|_| |_|\\__|\\__,_|_| |_| |_|");
535 Console.WriteLine(
" | | | | ");
536 Console.WriteLine(
" |_| |_| v" + Application.version);
TriLibCore.AssetLoaderOptions AssetLoaderOptions
static IEnumerable< string > GetFiles(string path, string[] searchPatterns, SearchOption searchOption=SearchOption.TopDirectoryOnly)
List< pb_SceneNode > children
Dictionary< string, byte[]> loadedFiles
static string GetFileNameForGameObject(GILES.Serialization.pb_SceneNode sn, string go, out string modelName)
static bool IsInChild(Transform t, string childName)
byte[] PoseToByteArray(GameObject go, bool limitToMixamoRig=true)
byte[] TransformToByteArray(GameObject go, bool local=true)
static void Change(Material mat, string shaderName)