public Task <string> RequestMapfile(string worldName, string targetDirectory) { lock (imageCache) { if (pendingMapRequests.Any(x => x.name == worldName)) { return(pendingMapRequests.First(x => x.name == worldName).completionSource.Task); } var request = new MapfileRequest { name = worldName, targetDirectory = targetDirectory, completionSource = new TaskCompletionSource <string>() }; pendingMapRequests.Add(request); Networking.Instance.SendMessage( $@"{{ ""cmd"": [""ImgDir"", ""RequestMapfile""], ""args"": {{ ""name"": ""{worldName}"" }} }}" ); return(request.completionSource.Task); } }
public void OnNetworkMessage(IEnumerable <string> cmd, JObject args) { if (cmd.First() == "TextureFile") { var path = args["path"].Value <string>(); var data = args["data"].Value <string>(); int width = args["width"].Value <int>(); int height = args["height"].Value <int>(); ImageRequest request; lock (imageCache) { if (!pendingRequests.ContainsKey(path)) { return; //#TODO log/handle } request = pendingRequests[path]; } var dataBytes = Convert.FromBase64String(data); //ABGR -> BGRA for (int i = 0; i < dataBytes.Length; i += 4) { var A = dataBytes[i]; var B = dataBytes[i + 1]; var G = dataBytes[i + 2]; var R = dataBytes[i + 3]; dataBytes[i] = B; dataBytes[i + 1] = G; dataBytes[i + 2] = R; dataBytes[i + 3] = A; } var bmp = SKImage.FromPixelCopy(new SKImageInfo(width, height, SKColorType.Bgra8888), dataBytes); //if (bmp == null) Debugger.Break(); request.completionSource.SetResult(bmp); //if (bmp != null) //{ // using (var data2 = bmp.Encode(SKEncodedImageFormat.Png, 80)) // using (var stream = File.OpenWrite(Path.Combine("P:/", Path.ChangeExtension(Path.GetFileName(path), ".png") ))) // { // // save the data to a stream // data2.SaveTo(stream); // } //} lock (imageCache) { imageCache[path] = bmp; pendingRequests.Remove(path); } } else if (cmd.First() == "MapFile") { var path = args["name"].Value <string>(); var data = args["data"].Value <string>(); MapfileRequest request = pendingMapRequests.FirstOrDefault(x => path.StartsWith(x.name)); lock (imageCache) { request = pendingMapRequests.FirstOrDefault(x => path.StartsWith(x.name)); //#TODO log/handle if (request == null) { return; } } var dataBytes = Convert.FromBase64String(data); //If source was not compressed, still store it compressed, save some disk space especially on mobile if (path.EndsWith("z") || Path.GetExtension(path) == ".zip") { using (var writer = File.Create(Path.Combine(request.targetDirectory, path))) { writer.Write(dataBytes, 0, dataBytes.Length); } } else { path = path + "z"; //svgz using (var writer = File.Create(Path.Combine(request.targetDirectory, path))) { using (GZipStream compressionStream = new GZipStream(writer, CompressionMode.Compress)) { compressionStream.Write(dataBytes, 0, dataBytes.Length); } } } request.completionSource.SetResult(Path.Combine(request.targetDirectory, path)); lock (imageCache) { pendingMapRequests.Remove(request); } } }