public static string lerror = ""; // Gets the last error that occurred in this struct. Similar to the C perror(). public static bool Decompress(byte[] indata, string outfile) { try { System.IO.MemoryStream ms = new System.IO.MemoryStream(indata); System.IO.StreamWriter sw = new System.IO.StreamWriter(outfile); System.IO.Compression.GZipStream gzs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress); int lbyte = gzs.ReadByte(); while (lbyte != -1) { sw.BaseStream.WriteByte((byte)lbyte); lbyte = gzs.ReadByte(); } gzs.Close(); gzs.Dispose(); sw.Close(); sw.Dispose(); } catch (System.Exception ex) { lerror = ex.Message; return(false); } return(true); }
public static bool decompress(string infile, string outfile) { try { System.IO.StreamWriter sw = new System.IO.StreamWriter(outfile); System.IO.StreamReader sr = new System.IO.StreamReader(infile); System.IO.Compression.GZipStream gzs = new System.IO.Compression.GZipStream(sr.BaseStream, System.IO.Compression.CompressionMode.Decompress); int lbyte = gzs.ReadByte(); while (lbyte != -1) { sw.BaseStream.WriteByte((byte) lbyte); lbyte = gzs.ReadByte(); } gzs.Close(); gzs.Dispose(); sw.Close(); sw.Dispose(); } catch (System.Exception ex) { lerror = ex.Message; return false; } return true; }
/// <summary> /// Unzip the bits </summary> public static Bits bitsGZIPDecode(Bits bits) { sbyte[] sdata = bits.Data; byte[] bdata = (byte[])(Array)sdata; System.IO.MemoryStream byteIn = new System.IO.MemoryStream(bdata); System.IO.Compression.GZipStream zipIn = new System.IO.Compression.GZipStream(byteIn, System.IO.Compression.CompressionMode.Compress); int b; Bits result = new Bits(); while ((b = zipIn.ReadByte()) >= 0) { result.addValue(b, 8); } return(result); }
public void UpdateNetwork(GameTime gameTime) { // Update the server with our status. timeSinceLastUpdate += gameTime.ElapsedGameTime.TotalSeconds; if (timeSinceLastUpdate > 0.05) { timeSinceLastUpdate = 0; if (CurrentStateType == "Infiniminer.States.MainGameState") { propertyBag.SendPlayerUpdate(); } } // Recieve messages from the server. while ((msgBuffer = propertyBag.netClient.ReadMessage()) != null) { switch (msgBuffer.MessageType) { case NetIncomingMessageType.StatusChanged: { if (propertyBag.netClient.ConnectionStatus == NetConnectionStatus.RespondedConnect) { anyPacketsReceived = true; } if (propertyBag.netClient.ConnectionStatus == NetConnectionStatus.Disconnected) { anyPacketsReceived = false; try { string[] reason = msgBuffer.ReadString().Split(";".ToCharArray()); if (reason.Length < 2 || reason[0] == "VER") { InfiniminerMessageBox.Show("Error: client/server version incompability!\r\nServer: " + msgBuffer.ReadString() + "\r\nClient: " + Defines.INFINIMINER_VERSION); } else { InfiniminerMessageBox.Show("Error: you are banned from this server!"); } } catch { } ChangeState("Infiniminer.States.ServerBrowserState"); } } break; case NetIncomingMessageType.Data: { try { InfiniminerMessage dataType = (InfiniminerMessage)msgBuffer.ReadByte(); switch (dataType) { case InfiniminerMessage.BlockBulkTransfer: { anyPacketsReceived = true; try { //This is either the compression flag or the x coordiante byte isCompressed = msgBuffer.ReadByte(); byte x; byte y; //255 was used because it exceeds the map size - of course, bytes won't work anyway if map sizes are allowed to be this big, so this method is a non-issue if (isCompressed == 255) { var compressed = msgBuffer.ReadBytes(msgBuffer.LengthBytes - (int)(msgBuffer.Position / 8)); var compressedstream = new System.IO.MemoryStream(compressed); var decompresser = new System.IO.Compression.GZipStream(compressedstream, System.IO.Compression.CompressionMode.Decompress); x = (byte)decompresser.ReadByte(); y = (byte)decompresser.ReadByte(); propertyBag.mapLoadProgress[x, y] = true; for (byte dy = 0; dy < 16; dy++) { for (byte z = 0; z < 64; z++) { BlockType blockType = (BlockType)decompresser.ReadByte(); if (blockType != BlockType.None) { propertyBag.blockEngine.downloadList[x, y + dy, z] = blockType; } } } } else { x = isCompressed; y = msgBuffer.ReadByte(); propertyBag.mapLoadProgress[x, y] = true; for (byte dy = 0; dy < 16; dy++) { for (byte z = 0; z < 64; z++) { BlockType blockType = (BlockType)msgBuffer.ReadByte(); if (blockType != BlockType.None) { propertyBag.blockEngine.downloadList[x, y + dy, z] = blockType; } } } } bool downloadComplete = true; for (x = 0; x < 64; x++) { for (y = 0; y < 64; y += 16) { if (propertyBag.mapLoadProgress[x, y] == false) { downloadComplete = false; break; } } } if (downloadComplete) { ChangeState("Infiniminer.States.TeamSelectionState"); if (!NoSound) { MediaPlayer.Stop(); } propertyBag.blockEngine.DownloadComplete(); } } catch (Exception e) { Console.OpenStandardError(); Console.Error.WriteLine(e.Message); Console.Error.WriteLine(e.StackTrace); Console.Error.Close(); } } break; case InfiniminerMessage.SetBeacon: { Vector3 position = msgBuffer.ReadVector3(); string text = msgBuffer.ReadString(); PlayerTeam team = (PlayerTeam)msgBuffer.ReadByte(); if (text == "") { if (propertyBag.beaconList.ContainsKey(position)) { propertyBag.beaconList.Remove(position); } } else { Beacon newBeacon = new Beacon(); newBeacon.ID = text; newBeacon.Team = team; propertyBag.beaconList.Add(position, newBeacon); } } break; case InfiniminerMessage.TriggerConstructionGunAnimation: { propertyBag.constructionGunAnimation = msgBuffer.ReadFloat(); if (propertyBag.constructionGunAnimation <= -0.1) { propertyBag.PlaySound(InfiniminerSound.RadarSwitch); } } break; case InfiniminerMessage.ResourceUpdate: { // ore, cash, weight, max ore, max weight, team ore, red cash, blue cash, all uint propertyBag.playerOre = msgBuffer.ReadUInt32(); propertyBag.playerCash = msgBuffer.ReadUInt32(); propertyBag.playerWeight = msgBuffer.ReadUInt32(); propertyBag.playerOreMax = msgBuffer.ReadUInt32(); propertyBag.playerWeightMax = msgBuffer.ReadUInt32(); propertyBag.teamOre = msgBuffer.ReadUInt32(); propertyBag.teamRedCash = msgBuffer.ReadUInt32(); propertyBag.teamBlueCash = msgBuffer.ReadUInt32(); } break; case InfiniminerMessage.BlockSet: { // x, y, z, type, all bytes byte x = msgBuffer.ReadByte(); byte y = msgBuffer.ReadByte(); byte z = msgBuffer.ReadByte(); BlockType blockType = (BlockType)msgBuffer.ReadByte(); if (blockType == BlockType.None) { if (propertyBag.blockEngine.BlockAtPoint(new Vector3(x, y, z)) != BlockType.None) { propertyBag.blockEngine.RemoveBlock(x, y, z); } } else { if (propertyBag.blockEngine.BlockAtPoint(new Vector3(x, y, z)) != BlockType.None) { propertyBag.blockEngine.RemoveBlock(x, y, z); } propertyBag.blockEngine.AddBlock(x, y, z, blockType); CheckForStandingInLava(); } } break; case InfiniminerMessage.TriggerExplosion: { Vector3 blockPos = msgBuffer.ReadVector3(); // Play the explosion sound. propertyBag.PlaySound(InfiniminerSound.Explosion, blockPos); // Create some particles. propertyBag.particleEngine.CreateExplosionDebris(blockPos); // Figure out what the effect is. float distFromExplosive = (blockPos + 0.5f * Vector3.One - propertyBag.playerPosition).Length(); if (distFromExplosive < 3) { propertyBag.KillPlayer(Defines.deathByExpl); //"WAS KILLED IN AN EXPLOSION!"); } else if (distFromExplosive < 8) { // If we're not in explosion mode, turn it on with the minimum ammount of shakiness. if (propertyBag.screenEffect != ScreenEffect.Explosion) { propertyBag.screenEffect = ScreenEffect.Explosion; propertyBag.screenEffectCounter = 2; } // If this bomb would result in a bigger shake, use its value. propertyBag.screenEffectCounter = Math.Min(propertyBag.screenEffectCounter, (distFromExplosive - 2) / 5); } } break; case InfiniminerMessage.PlayerSetTeam: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { Player player = propertyBag.playerList[playerId]; player.Team = (PlayerTeam)msgBuffer.ReadByte(); } } break; case InfiniminerMessage.PlayerJoined: { uint playerId = msgBuffer.ReadUInt32(); string playerName = msgBuffer.ReadString(); bool thisIsMe = msgBuffer.ReadBoolean(); bool playerAlive = msgBuffer.ReadBoolean(); propertyBag.playerList[playerId] = new Player(null, (Game)this); propertyBag.playerList[playerId].Handle = playerName; propertyBag.playerList[playerId].ID = playerId; propertyBag.playerList[playerId].Alive = playerAlive; propertyBag.playerList[playerId].AltColours = customColours; propertyBag.playerList[playerId].redTeam = red; propertyBag.playerList[playerId].blueTeam = blue; if (thisIsMe) { propertyBag.playerMyId = playerId; } } break; case InfiniminerMessage.PlayerLeft: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { propertyBag.playerList.Remove(playerId); } } break; case InfiniminerMessage.PlayerDead: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { Player player = propertyBag.playerList[playerId]; player.Alive = false; propertyBag.particleEngine.CreateBloodSplatter(player.Position, player.Team == PlayerTeam.Red ? Color.Red : Color.Blue); if (playerId != propertyBag.playerMyId) { propertyBag.PlaySound(InfiniminerSound.Death, player.Position); } } } break; case InfiniminerMessage.PlayerAlive: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { Player player = propertyBag.playerList[playerId]; player.Alive = true; } } break; case InfiniminerMessage.PlayerUpdate: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { Player player = propertyBag.playerList[playerId]; player.UpdatePosition(msgBuffer.ReadVector3(), gameTime.TotalGameTime.TotalSeconds); player.Heading = msgBuffer.ReadVector3(); player.Tool = (PlayerTools)msgBuffer.ReadByte(); player.UsingTool = msgBuffer.ReadBoolean(); player.Score = (uint)(msgBuffer.ReadUInt16() * 100); } } break; case InfiniminerMessage.GameOver: { propertyBag.teamWinners = (PlayerTeam)msgBuffer.ReadByte(); } break; case InfiniminerMessage.ChatMessage: { ChatMessageType chatType = (ChatMessageType)msgBuffer.ReadByte(); string chatString = Defines.Sanitize(msgBuffer.ReadString()); //Time to break it up into multiple lines propertyBag.addChatMessage(chatString, chatType, 10); } break; case InfiniminerMessage.PlayerPing: { uint playerId = (uint)msgBuffer.ReadInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { if (propertyBag.playerList[playerId].Team == propertyBag.playerTeam) { propertyBag.playerList[playerId].Ping = 1; propertyBag.PlaySound(InfiniminerSound.Ping); } } } break; case InfiniminerMessage.PlaySound: { InfiniminerSound sound = (InfiniminerSound)msgBuffer.ReadByte(); bool hasPosition = msgBuffer.ReadBoolean(); if (hasPosition) { Vector3 soundPosition = msgBuffer.ReadVector3(); propertyBag.PlaySound(sound, soundPosition); } else { propertyBag.PlaySound(sound); } } break; } } catch { } //Error in a received message } break; } } // Make sure our network thread actually gets to run. Thread.Sleep(1); }
static void DfsPut(string[] args, long maxLineSize) { if (args.Length > 0 && "-rv" == args[0]) { args = SubArray(args, 1); ReplicationDebugVerbose = true; } if (!dfs.DfsConfigExists(DFSXMLPATH)) { Console.Error.WriteLine("DFS not setup; use: {0} format", appname); SetFailure(); return; } if (args.Length < 1) { Console.Error.WriteLine("dfs put error: {0} dfs put <localpath> [<dfspath>]", appname); SetFailure(); return; } { string localpath = args[0]; if (!System.IO.File.Exists(localpath)) { Console.Error.WriteLine("File not found: {0}", localpath); SetFailure(); return; } string dfspath; if (args.Length > 1) { dfspath = args[1]; if (dfspath.StartsWith("dfs://", StringComparison.OrdinalIgnoreCase)) { dfspath = dfspath.Substring(6); } } else { dfspath = (new System.IO.FileInfo(localpath)).Name; } int RecordLength = -1; { int ic = dfspath.IndexOf('@'); if (-1 != ic) { try { RecordLength = Surrogate.GetRecordSize(dfspath.Substring(ic + 1)); dfspath = dfspath.Substring(0, ic); } catch (FormatException e) { Console.Error.WriteLine("Invalid Record Length or DFS path: {0}", e.Message); SetFailure(); return; } catch (OverflowException e) { Console.Error.WriteLine("Invalid Record Length or DFS path: {0}", e.Message); SetFailure(); return; } } } { string reason = ""; if (dfs.IsBadFilename(dfspath, out reason)) { Console.Error.WriteLine("Invalid DFS path: {0}", reason); SetFailure(); return; } } EnsureNetworkPath(localpath); { dfs dc = LoadDfsConfig(); if (localpath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { if (-1 != dfspath.IndexOf(@".\") || -1 != dfspath.IndexOf(@"./")) { // Prevent navigating directories. Console.Error.WriteLine("Invalid DFS name for DLL"); SetFailure(); return; } System.IO.FileInfo dllfi = new System.IO.FileInfo(localpath); dc.Find(dfspath, DfsFileTypes.DLL); // Error if not dll, otherwise fine to replace. string[] slaves = dc.Slaves.SlaveList.Split(';'); MySpace.DataMining.Threading.ThreadTools<string>.Parallel( new Action<string>( delegate(string slave) { string netpath = Surrogate.NetworkPathForHost(slave); string cacpath = netpath + @"\" + dfs.DLL_DIR_NAME; try { System.IO.Directory.CreateDirectory(cacpath); } catch { } System.IO.File.Copy(localpath, cacpath + @"\" + dfspath, true); }), slaves); using (LockDfsMutex()) // Needed: change between load & save should be atomic. { dc = LoadDfsConfig(); // Reload in case of changes during put. dfs.DfsFile dfsfile = dc.Find(dfspath, DfsFileTypes.DLL); // Error if not dll, otherwise fine to replace. if (null == dfsfile) { dfsfile = new dfs.DfsFile(); dc.Files.Add(dfsfile); } dfsfile.Type = DfsFileTypes.DLL; dfsfile.Name = dfspath; dfsfile.Size = dllfi.Length; UpdateDfsXml(dc); } Console.WriteLine("dfs://{0} successfully written", dfspath); } else { for (int i = 0; i < dc.Files.Count; i++) { if (0 == string.Compare(dc.Files[i].Name, dfspath, true)) { Console.Error.WriteLine("Error: The specified file already exists in DFS: {0}", dfspath); SetFailure(); return; } } long sampledist = dc.DataNodeBaseSize / dc.DataNodeSamples; using (System.IO.FileStream _fs = new System.IO.FileStream(localpath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { //const int MAX_SIZE_PER_RECEIVE = 0x400 * 64; //byte[] fbuf = new byte[MAX_SIZE_PER_RECEIVE]; byte[] fbuf = new byte[maxLineSize]; int[] lbuf = new int[3]; short lbufCount = 0; System.IO.Stream fs = _fs; if (localpath.EndsWith(".gz", StringComparison.OrdinalIgnoreCase)) { fs = new System.IO.Compression.GZipStream(_fs, System.IO.Compression.CompressionMode.Decompress); if (RecordLength < 1) { lbuf[2] = fs.ReadByte(); lbuf[1] = fs.ReadByte(); lbuf[0] = fs.ReadByte(); if (!(lbuf[2] == 0xEF && lbuf[1] == 0xBB && lbuf[0] == 0xBF)) { lbufCount = 3; } } } else { if (RecordLength < 1) { //remove BOM fs.Read(fbuf, 0, 3); if (!(fbuf[0] == 0xEF && fbuf[1] == 0xBB && fbuf[2] == 0xBF)) { fs.Position = 0; } } } string[] slaves = dc.Slaves.SlaveList.Split(',', ';'); if (null == dc.Slaves.SlaveList || dc.Slaves.SlaveList.Length == 0 || slaves.Length < 1) { Console.Error.WriteLine("SlaveList expected in configuration (no machines)"); SetFailure(); return; } if (dc.Replication > 1) { slaves = ExcludeUnhealthySlaveMachines(slaves, true).ToArray(); } if (0 == slaves.Length) { Console.Error.WriteLine("No healthy machines for DFS put"); SetFailure(); return; } Random rnd = new Random((DateTime.Now.Millisecond / 2) + (System.Diagnostics.Process.GetCurrentProcess().Id / 2)); List<dfs.DfsFile.FileNode> ninfos = new List<dfs.DfsFile.FileNode>(64); int nextslave = rnd.Next() % slaves.Length; long curbytepos = 0; for (; ; ) { #if DEBUG if (RecordLength > 0) { if (lbufCount != 0) { // lbufCount should be zero here because BOM isn't used with rectangular records. throw new Exception("Internal error: (RecordLength > 0) && (lbufCount != 0)"); } } #endif string SlaveHost = slaves[nextslave]; string SlaveIP = IPAddressUtil.GetIPv4Address(SlaveHost); if (++nextslave >= slaves.Length) { nextslave = 0; } string netdir = NetworkPathForHost(SlaveHost); string chunkname = GenerateZdFileDataNodeName(dfspath); string chunkpath = netdir + @"\" + chunkname; string samplepath = netdir + @"\" + chunkname + ".zsa"; using (System.IO.FileStream _fc = new System.IO.FileStream(chunkpath, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write, System.IO.FileShare.None, FILE_BUFFER_SIZE)) { System.IO.FileStream samps = null; if (RecordLength < 1) { samps = new System.IO.FileStream(samplepath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None); } try { long chunkpos = 0; long nextsamplepos = 0; long Position = curbytepos; System.IO.Stream fc = _fc; if (1 == dc.slave.CompressDfsChunks) { fc = new System.IO.Compression.GZipStream(_fc, System.IO.Compression.CompressionMode.Compress); } MySpace.DataMining.DistributedObjects.Entry.ToBytes(4 + 8, fbuf, 0); // Size of header. MySpace.DataMining.DistributedObjects.Entry.LongToBytes(Position, fbuf, 4); fc.Write(fbuf, 0, 4 + 8); { long chunkremain = dc.DataNodeBaseSize; long Length = 0; bool eof = false; while (chunkremain > 0 && !eof) { if (RecordLength > 0) { int recordremain = RecordLength; while (recordremain > 0) { int xread = recordremain; if (xread > fbuf.Length) { xread = fbuf.Length; } xread = fs.Read(fbuf, 0, xread); if (xread < 1) { eof = true; if (recordremain != RecordLength) { Console.Error.WriteLine("Warning: incomplete record at end of input file"); } break; } fc.Write(fbuf, 0, xread); chunkremain -= xread; recordremain -= xread; curbytepos += xread; #if DEBUG if (recordremain < 0) { throw new Exception("DEBUG: (recordremain < 0)"); } #endif } } else { int xread = 0; for (; ; ) { int ib; if (lbufCount == 0) { ib = fs.ReadByte(); } else { ib = lbuf[--lbufCount]; } if (-1 == ib) { eof = true; break; } if (xread < fbuf.Length) { fbuf[xread++] = (byte)ib; } if ('\n' == ib) { break; } } //Length += xread; chunkremain -= xread; curbytepos += xread; fc.Write(fbuf, 0, xread); chunkpos += xread; if (chunkpos >= nextsamplepos) { samps.Write(fbuf, 0, xread); nextsamplepos += sampledist; } } } Length = curbytepos - Position; if (0 == Length) { break; } Length = curbytepos - Position; { dfs.DfsFile.FileNode fnode = new dfs.DfsFile.FileNode(); fnode.Host = SlaveHost; fnode.Position = Position; fnode.Length = Length; fnode.Name = chunkname; ninfos.Add(fnode); } } fc.Close(); } finally { if (null != samps) { samps.Dispose(); } } } } string dfspathreplicating = ".$" + dfspath + ".$replicating-" + Guid.NewGuid().ToString(); using (LockDfsMutex()) // Needed: change between load & save should be atomic. { dc = LoadDfsConfig(); // Reload in case of changes during put. if (null != dc.FindAny(dfspathreplicating)) { Console.Error.WriteLine("Error: file exists: file put into DFS from another location during put: " + dfspathreplicating); SetFailure(); return; } dfs.DfsFile dfsfile = new dfs.DfsFile(); //dfsfile.Nodes = new List<dfs.DfsFile.FileNode>(ninfos); if (RecordLength > 0) { dfsfile.XFileType = DfsFileTypes.BINARY_RECT + "@" + RecordLength.ToString(); } dfsfile.Nodes = ninfos; dfsfile.Name = dfspathreplicating; dfsfile.Size = curbytepos; dc.Files.Add(dfsfile); UpdateDfsXml(dc); } fs.Close(); ReplicationPhase(dfspathreplicating, true, 0, slaves); using (LockDfsMutex()) // Needed: change between load & save should be atomic. { dc = LoadDfsConfig(); // Reload in case of changes during put. dfs.DfsFile dfu = dc.FindAny(dfspathreplicating); if (null != dfu) { if (null != DfsFindAny(dc, dfspath)) { Console.Error.WriteLine("Error: file exists: file put into DFS from another location during put"); SetFailure(); return; } dfu.Name = dfspath; UpdateDfsXml(dc); } } Console.WriteLine("Sent {0} bytes to file dfs://{1}", curbytepos, dfspath); } } } } }
public void UpdateNetwork(GameTime gameTime) { // Update the server with our status. timeSinceLastUpdate += gameTime.ElapsedGameTime.TotalSeconds; if (timeSinceLastUpdate > 0.05) { timeSinceLastUpdate = 0; if (CurrentStateType == "Infiniminer.States.MainGameState") propertyBag.SendPlayerUpdate(); } // Recieve messages from the server. NetMessageType msgType; while (propertyBag.netClient.ReadMessage(msgBuffer, out msgType)) { switch (msgType) { case NetMessageType.StatusChanged: { if (propertyBag.netClient.Status == NetConnectionStatus.Disconnected) ChangeState("Infiniminer.States.ServerBrowserState"); } break; case NetMessageType.ConnectionApproval: anyPacketsReceived = true; break; case NetMessageType.ConnectionRejected: { anyPacketsReceived = false; try { string[] reason = msgBuffer.ReadString().Split(";".ToCharArray()); if (reason.Length < 2 || reason[0] == "VER") System.Windows.Forms.MessageBox.Show("Error: client/server version incompability!\r\nServer: " + msgBuffer.ReadString() + "\r\nClient: " + Defines.INFINIMINER_VERSION); else System.Windows.Forms.MessageBox.Show("Error: you are banned from this server!"); } catch { } ChangeState("Infiniminer.States.ServerBrowserState"); } break; case NetMessageType.Data: { try { InfiniminerMessage dataType = (InfiniminerMessage)msgBuffer.ReadByte(); switch (dataType) { case InfiniminerMessage.BlockBulkTransfer: { anyPacketsReceived = true; try { //This is either the compression flag or the x coordiante byte isCompressed = msgBuffer.ReadByte(); byte x; byte y; //255 was used because it exceeds the map size - of course, bytes won't work anyway if map sizes are allowed to be this big, so this method is a non-issue if (isCompressed == 255) { var compressed = msgBuffer.ReadBytes(msgBuffer.LengthBytes - msgBuffer.Position / 8); var compressedstream = new System.IO.MemoryStream(compressed); var decompresser = new System.IO.Compression.GZipStream(compressedstream, System.IO.Compression.CompressionMode.Decompress); x = (byte)decompresser.ReadByte(); y = (byte)decompresser.ReadByte(); propertyBag.mapLoadProgress[x, y] = true; for (byte dy = 0; dy < 16; dy++) for (byte z = 0; z < 64; z++) { BlockType blockType = (BlockType)decompresser.ReadByte(); if (blockType != BlockType.None) propertyBag.blockEngine.downloadList[x, y + dy, z] = blockType; } } else { x = isCompressed; y = msgBuffer.ReadByte(); propertyBag.mapLoadProgress[x, y] = true; for (byte dy = 0; dy < 16; dy++) for (byte z = 0; z < 64; z++) { BlockType blockType = (BlockType)msgBuffer.ReadByte(); if (blockType != BlockType.None) propertyBag.blockEngine.downloadList[x, y + dy, z] = blockType; } } bool downloadComplete = true; for (x = 0; x < 64; x++) for (y = 0; y < 64; y += 16) if (propertyBag.mapLoadProgress[x, y] == false) { downloadComplete = false; break; } if (downloadComplete) { ChangeState("Infiniminer.States.TeamSelectionState"); if (!NoSound) MediaPlayer.Stop(); propertyBag.blockEngine.DownloadComplete(); } } catch (Exception e) { Console.OpenStandardError(); Console.Error.WriteLine(e.Message); Console.Error.WriteLine(e.StackTrace); Console.Error.Close(); } } break; case InfiniminerMessage.SetBeacon: { Vector3 position = msgBuffer.ReadVector3(); string text = msgBuffer.ReadString(); PlayerTeam team = (PlayerTeam)msgBuffer.ReadByte(); if (text == "") { if (propertyBag.beaconList.ContainsKey(position)) propertyBag.beaconList.Remove(position); } else { Beacon newBeacon = new Beacon(); newBeacon.ID = text; newBeacon.Team = team; propertyBag.beaconList.Add(position, newBeacon); } } break; case InfiniminerMessage.TriggerConstructionGunAnimation: { propertyBag.constructionGunAnimation = msgBuffer.ReadFloat(); if (propertyBag.constructionGunAnimation <= -0.1) propertyBag.PlaySound(InfiniminerSound.RadarSwitch); } break; case InfiniminerMessage.ResourceUpdate: { // ore, cash, weight, max ore, max weight, team ore, red cash, blue cash, all uint propertyBag.playerOre = msgBuffer.ReadUInt32(); propertyBag.playerCash = msgBuffer.ReadUInt32(); propertyBag.playerWeight = msgBuffer.ReadUInt32(); propertyBag.playerOreMax = msgBuffer.ReadUInt32(); propertyBag.playerWeightMax = msgBuffer.ReadUInt32(); propertyBag.teamOre = msgBuffer.ReadUInt32(); propertyBag.teamRedCash = msgBuffer.ReadUInt32(); propertyBag.teamBlueCash = msgBuffer.ReadUInt32(); } break; case InfiniminerMessage.BlockSet: { // x, y, z, type, all bytes byte x = msgBuffer.ReadByte(); byte y = msgBuffer.ReadByte(); byte z = msgBuffer.ReadByte(); BlockType blockType = (BlockType)msgBuffer.ReadByte(); if (blockType == BlockType.None) { if (propertyBag.blockEngine.BlockAtPoint(new Vector3(x, y, z)) != BlockType.None) propertyBag.blockEngine.RemoveBlock(x, y, z); } else { if (propertyBag.blockEngine.BlockAtPoint(new Vector3(x, y, z)) != BlockType.None) propertyBag.blockEngine.RemoveBlock(x, y, z); propertyBag.blockEngine.AddBlock(x, y, z, blockType); CheckForStandingInLava(); } } break; case InfiniminerMessage.TriggerExplosion: { Vector3 blockPos = msgBuffer.ReadVector3(); // Play the explosion sound. propertyBag.PlaySound(InfiniminerSound.Explosion, blockPos); // Create some particles. propertyBag.particleEngine.CreateExplosionDebris(blockPos); // Figure out what the effect is. float distFromExplosive = (blockPos + 0.5f * Vector3.One - propertyBag.playerPosition).Length(); if (distFromExplosive < 3) propertyBag.KillPlayer(Defines.deathByExpl);//"WAS KILLED IN AN EXPLOSION!"); else if (distFromExplosive < 8) { // If we're not in explosion mode, turn it on with the minimum ammount of shakiness. if (propertyBag.screenEffect != ScreenEffect.Explosion) { propertyBag.screenEffect = ScreenEffect.Explosion; propertyBag.screenEffectCounter = 2; } // If this bomb would result in a bigger shake, use its value. propertyBag.screenEffectCounter = Math.Min(propertyBag.screenEffectCounter, (distFromExplosive - 2) / 5); } } break; case InfiniminerMessage.PlayerSetTeam: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { Player player = propertyBag.playerList[playerId]; player.Team = (PlayerTeam)msgBuffer.ReadByte(); } } break; case InfiniminerMessage.PlayerJoined: { uint playerId = msgBuffer.ReadUInt32(); string playerName = msgBuffer.ReadString(); bool thisIsMe = msgBuffer.ReadBoolean(); bool playerAlive = msgBuffer.ReadBoolean(); propertyBag.playerList[playerId] = new Player(null, (Game)this); propertyBag.playerList[playerId].Handle = playerName; propertyBag.playerList[playerId].ID = playerId; propertyBag.playerList[playerId].Alive = playerAlive; propertyBag.playerList[playerId].AltColours = customColours; propertyBag.playerList[playerId].redTeam = red; propertyBag.playerList[playerId].blueTeam = blue; if (thisIsMe) propertyBag.playerMyId = playerId; } break; case InfiniminerMessage.PlayerLeft: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) propertyBag.playerList.Remove(playerId); } break; case InfiniminerMessage.PlayerDead: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { Player player = propertyBag.playerList[playerId]; player.Alive = false; propertyBag.particleEngine.CreateBloodSplatter(player.Position, player.Team == PlayerTeam.Red ? Color.Red : Color.Blue); if (playerId != propertyBag.playerMyId) propertyBag.PlaySound(InfiniminerSound.Death, player.Position); } } break; case InfiniminerMessage.PlayerAlive: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { Player player = propertyBag.playerList[playerId]; player.Alive = true; } } break; case InfiniminerMessage.PlayerUpdate: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { Player player = propertyBag.playerList[playerId]; player.UpdatePosition(msgBuffer.ReadVector3(), gameTime.TotalGameTime.TotalSeconds); player.Heading = msgBuffer.ReadVector3(); player.Tool = (PlayerTools)msgBuffer.ReadByte(); player.UsingTool = msgBuffer.ReadBoolean(); player.Score = (uint)(msgBuffer.ReadUInt16() * 100); } } break; case InfiniminerMessage.GameOver: { propertyBag.teamWinners = (PlayerTeam)msgBuffer.ReadByte(); } break; case InfiniminerMessage.ChatMessage: { ChatMessageType chatType = (ChatMessageType)msgBuffer.ReadByte(); string chatString = Defines.Sanitize(msgBuffer.ReadString()); //Time to break it up into multiple lines propertyBag.addChatMessage(chatString, chatType, 10); } break; case InfiniminerMessage.PlayerPing: { uint playerId = (uint)msgBuffer.ReadInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { if (propertyBag.playerList[playerId].Team == propertyBag.playerTeam) { propertyBag.playerList[playerId].Ping = 1; propertyBag.PlaySound(InfiniminerSound.Ping); } } } break; case InfiniminerMessage.PlaySound: { InfiniminerSound sound = (InfiniminerSound)msgBuffer.ReadByte(); bool hasPosition = msgBuffer.ReadBoolean(); if (hasPosition) { Vector3 soundPosition = msgBuffer.ReadVector3(); propertyBag.PlaySound(sound, soundPosition); } else propertyBag.PlaySound(sound); } break; } } catch { } //Error in a received message } break; } } // Make sure our network thread actually gets to run. Thread.Sleep(1); }
public override int read() { return(delegateInstance.ReadByte()); }
/// <summary> /// UNCompress a byte[] using GZipStream /// /// Taken from: http://atakala.com/browser/Item.aspx?user_id=amos&dict_id=1980 /// </summary> /// <param name="input">byte[] to be uncompressed</param> /// <returns>Uncompressed representation of input</returns> public static byte[] Decompress(byte[] input) { System.Collections.Generic.List<byte> output = new List<byte>(); using (System.IO.MemoryStream ms = new System.IO.MemoryStream(input)) { using (System.IO.Compression.GZipStream gs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress)) { int readByte = gs.ReadByte(); while (readByte != -1) { output.Add((byte)readByte); readByte = gs.ReadByte(); } gs.Close(); } ms.Close(); } return output.ToArray(); }
static void Main(string[] args) { TMP.Work.Emcos.ViewModel.BalanceViewModel vm = new TMP.Work.Emcos.ViewModel.BalanceViewModel(null); SESSIONS_FOLDER = String.IsNullOrEmpty(vm.SESSIONS_FOLDER) ? "Sessions" : vm.SESSIONS_FOLDER; SESSION_FILE_EXTENSION = String.IsNullOrEmpty(vm.SESSION_FILE_EXTENSION) ? ".session-data" : vm.SESSION_FILE_EXTENSION; string outFolder = SESSIONS_FOLDER + @"\out"; if (System.IO.Directory.Exists(outFolder) == false) { System.IO.Directory.CreateDirectory(outFolder); } try { System.IO.DirectoryInfo di = new DirectoryInfo(SESSIONS_FOLDER); if (di.Exists == false) { throw new FileNotFoundException("Папка '" + SESSIONS_FOLDER + "' не найдена!"); } else { Console.WriteLine("Поиск файлов сессий програмы EmcosSiteWrapper в папке '" + di.FullName + "'."); } FileInfo[] files = di.GetFiles("*" + SESSION_FILE_EXTENSION).OrderByDescending(p => p.LastWriteTime).ToArray(); Console.WriteLine("Найдено " + files.Count() + " сессий."); foreach (FileInfo fi in files) { if (fi.Extension == SESSION_FILE_EXTENSION) { Console.Write("[Сессия - " + fi.Name + "] "); try { bool isOldVersion = false; DateTime? start = new Nullable <DateTime>(), end = new Nullable <DateTime>(); DatePeriod period = null; BalansSession session = null; using (FileStream fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read)) { string gzFileSignature = "1F 8B 08"; byte[] fileSignature = new byte[3]; int readed = fs.Read(fileSignature, 0, 3); if (readed == 3) { string hex = BitConverter.ToString(fileSignature).Replace("-", " "); if (hex == gzFileSignature) { Console.Write("\t* это gz архив"); } } else { } fs.Seek(0, SeekOrigin.Begin); char first = (char)0; using (System.IO.Compression.GZipStream temp = new System.IO.Compression.GZipStream(fs, System.IO.Compression.CompressionMode.Decompress, false)) { first = (char)temp.ReadByte(); fs.Seek(0, SeekOrigin.Begin); using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(fs, System.IO.Compression.CompressionMode.Decompress, false)) { if (first == '<') { Console.WriteLine("\t* это XML"); #region Parse XML using (XmlReader xmlReader = XmlReader.Create(gzip)) { XmlDocument xdoc = new XmlDocument(); xdoc.Load(xmlReader); XmlNamespaceManager nsmanager = new XmlNamespaceManager(xdoc.NameTable); nsmanager.AddNamespace("x", "http://tmp.work.balans-substations.com"); XmlNode node = xdoc.DocumentElement.SelectSingleNode("x:Period", nsmanager); if (node == null) // старая версия файла? { isOldVersion = true; node = xdoc.DocumentElement.SelectSingleNode("x:StartDate", nsmanager); if (node != null && String.IsNullOrWhiteSpace(node.InnerText) == false) { DateTime date; DateTime.TryParse(node.InnerText, out date); start = date; } else { start = null; } node = xdoc.DocumentElement.SelectSingleNode("x:EndDate", nsmanager); if (node != null && String.IsNullOrWhiteSpace(node.InnerText) == false) { DateTime date; DateTime.TryParse(node.InnerText, out date); end = date; } period = new DatePeriod(start, end); Console.WriteLine("\t* это старая версия сессии"); } else { Console.WriteLine("\t* это новая версия сессии"); } } #endregion session = TMP.Common.RepositoryCommon.BaseDeserializer <BalansSession> .GzXmlDataContractDeSerialize( fi.FullName, new Type[] { typeof(Substation), typeof(SubstationSection), typeof(SubstationPowerTransformers), typeof(SubstationAuxiliary), typeof(GroupItem), typeof(BalanceItem), typeof(Fider), typeof(PowerTransformer), typeof(UnitTransformer), typeof(UnitTransformerBus), typeof(DatePeriod) }, OnError); if (isOldVersion) { session.Period = period; } } else if (first == '{') { Console.WriteLine("\t* это JSON"); session = TMP.Common.RepositoryCommon.BaseDeserializer <BalansSession> .JsonDeSerializeFromStream(gzip, OnError); } else { Console.WriteLine("\t* неизвестный файл"); } } } if (session != null) { TMP.Common.RepositoryCommon.BaseDeserializer <BalansSession> .GzJsonSerialize( session, outFolder + @"\" + session.Period.GetFileNameForSaveSession() + vm.SESSION_FILE_EXTENSION); } } } catch (Exception e) { OnError(e); } } } } catch (IOException ioe) { OnError(ioe); } Console.WriteLine(); Console.WriteLine("Готово!"); Console.WriteLine(); Console.ReadKey(); }
public void UpdateNetwork(GameTime gameTime) { // Update the server with our status. timeSinceLastUpdate += gameTime.ElapsedGameTime.TotalSeconds; if (timeSinceLastUpdate > NETWORK_UPDATE_TIME) { timeSinceLastUpdate = 0; if (CurrentStateType == "Infiniminer.States.MainGameState") { propertyBag.SendPlayerUpdate(); } } // Recieve messages from the server. NetMessageType msgType; while (propertyBag.netClient.ReadMessage(msgBuffer, out msgType)) { switch (msgType) { case NetMessageType.StatusChanged: { if (propertyBag.netClient.Status == NetConnectionStatus.Disconnected) { ChangeState("Infiniminer.States.ServerBrowserState");//needed to reset Thread.Sleep(50); JoinGame(lastConnection);//attempts to reconnect ChangeState("Infiniminer.States.LoadingState"); } } break; case NetMessageType.ConnectionApproval: anyPacketsReceived = true; break; case NetMessageType.ConnectionRejected: { anyPacketsReceived = false; try { string[] reason = msgBuffer.ReadString().Split(";".ToCharArray()); if (reason.Length < 2 || reason[0] == "VER") System.Windows.Forms.MessageBox.Show("Error: client/server version incompability!\r\nServer: " + msgBuffer.ReadString() + "\r\nClient: " + Defines.INFINIMINER_VERSION); else System.Windows.Forms.MessageBox.Show("Error: you are banned from this server!"); } catch { } ChangeState("Infiniminer.States.ServerBrowserState"); } break; case NetMessageType.Data: { try { InfiniminerMessage dataType = (InfiniminerMessage)msgBuffer.ReadByte(); switch (dataType) { case InfiniminerMessage.BlockBulkTransfer: { anyPacketsReceived = true; try { //This is either the compression flag or the x coordiante byte isCompressed = msgBuffer.ReadByte(); byte x; byte y; //255 was used because it exceeds the map size - of course, bytes won't work anyway if map sizes are allowed to be this big, so this method is a non-issue if (isCompressed == 255) { var compressed = msgBuffer.ReadBytes(msgBuffer.LengthBytes - msgBuffer.Position / 8); var compressedstream = new System.IO.MemoryStream(compressed); var decompresser = new System.IO.Compression.GZipStream(compressedstream, System.IO.Compression.CompressionMode.Decompress); x = (byte)decompresser.ReadByte(); y = (byte)decompresser.ReadByte(); propertyBag.mapLoadProgress[x, y] = true; for (byte dy = 0; dy < 16; dy++) for (byte z = 0; z < 64; z++) { BlockType blockType = (BlockType)decompresser.ReadByte(); if (blockType != BlockType.None) propertyBag.blockEngine.downloadList[x, y + dy, z] = blockType; } } else { x = isCompressed; y = msgBuffer.ReadByte(); propertyBag.mapLoadProgress[x, y] = true; for (byte dy = 0; dy < 16; dy++) for (byte z = 0; z < 64; z++) { BlockType blockType = (BlockType)msgBuffer.ReadByte(); if (blockType != BlockType.None) propertyBag.blockEngine.downloadList[x, y + dy, z] = blockType; } } bool downloadComplete = true; for (x = 0; x < 64; x++) for (y = 0; y < 64; y += 16) if (propertyBag.mapLoadProgress[x, y] == false) { downloadComplete = false; break; } if (downloadComplete) { ChangeState("Infiniminer.States.TeamSelectionState"); if (!NoSound) MediaPlayer.Stop(); lastConnection = new IPEndPoint(propertyBag.netClient.ServerConnection.RemoteEndpoint.Address, 5565); propertyBag.blockEngine.DownloadComplete(); } } catch (Exception e) { Console.OpenStandardError(); Console.Error.WriteLine(e.Message); Console.Error.WriteLine(e.StackTrace); Console.Error.Close(); } } break; case InfiniminerMessage.SetBeacon: { Vector3 position = msgBuffer.ReadVector3(); string text = msgBuffer.ReadString(); PlayerTeam team = (PlayerTeam)msgBuffer.ReadByte(); if (text == "") { if (propertyBag.beaconList.ContainsKey(position)) propertyBag.beaconList.Remove(position); } else { Beacon newBeacon = new Beacon(); newBeacon.ID = text; newBeacon.Team = team; propertyBag.beaconList.Add(position, newBeacon); } } break; case InfiniminerMessage.SetItem: { ItemType iType = (ItemType)(msgBuffer.ReadByte()); Item newItem = new Item((Game)this,iType); newItem.ID = msgBuffer.ReadUInt32(); newItem.Position = msgBuffer.ReadVector3(); newItem.Team = (PlayerTeam)msgBuffer.ReadByte(); newItem.Heading = msgBuffer.ReadVector3(); newItem.deltaPosition = newItem.Position; newItem.Content[1] = msgBuffer.ReadInt32(); newItem.Content[2] = msgBuffer.ReadInt32(); newItem.Content[3] = msgBuffer.ReadInt32(); newItem.Content[10] = msgBuffer.ReadInt32(); propertyBag.itemList.Add(newItem.ID, newItem); } break; case InfiniminerMessage.ActiveArtifactUpdate: { propertyBag.artifactActive[msgBuffer.ReadByte(), msgBuffer.ReadInt32()] = msgBuffer.ReadInt32(); } break; case InfiniminerMessage.ItemUpdate: { uint id = msgBuffer.ReadUInt32(); //if (propertyBag.itemList.ContainsKey(id)) propertyBag.itemList[id].Position = msgBuffer.ReadVector3(); } break; case InfiniminerMessage.ItemScaleUpdate: { uint id = msgBuffer.ReadUInt32(); //if (propertyBag.itemList.ContainsKey(id)) propertyBag.itemList[id].Scale = msgBuffer.ReadFloat(); } break; case InfiniminerMessage.ItemContentSpecificUpdate: { uint id = msgBuffer.ReadUInt32(); uint cc = msgBuffer.ReadUInt32(); //if (propertyBag.itemList.ContainsKey(id)) propertyBag.itemList[id].Content[cc] = msgBuffer.ReadInt32(); } break; case InfiniminerMessage.SetItemRemove: { uint id = msgBuffer.ReadUInt32(); if (propertyBag.itemList.ContainsKey(id)) propertyBag.itemList.Remove(id); } break; case InfiniminerMessage.TriggerConstructionGunAnimation: { propertyBag.constructionGunAnimation = msgBuffer.ReadFloat(); if (propertyBag.constructionGunAnimation <= -0.1) propertyBag.PlaySound(InfiniminerSound.RadarSwitch); } break; case InfiniminerMessage.ScoreUpdate: { propertyBag.teamArtifactsRed = msgBuffer.ReadUInt32(); propertyBag.teamArtifactsBlue = msgBuffer.ReadUInt32(); break; } case InfiniminerMessage.ResourceUpdate: { // ore, cash, weight, max ore, max weight, team ore, red cash, blue cash, all uint propertyBag.playerOre = msgBuffer.ReadUInt32(); propertyBag.playerCash = msgBuffer.ReadUInt32(); propertyBag.playerWeight = msgBuffer.ReadUInt32(); propertyBag.playerOreMax = msgBuffer.ReadUInt32(); propertyBag.playerWeightMax = msgBuffer.ReadUInt32(); propertyBag.teamOre = msgBuffer.ReadUInt32(); propertyBag.teamRedCash = msgBuffer.ReadUInt32(); propertyBag.teamBlueCash = msgBuffer.ReadUInt32(); propertyBag.teamArtifactsRed = msgBuffer.ReadUInt32(); propertyBag.teamArtifactsBlue = msgBuffer.ReadUInt32(); propertyBag.winningCashAmount = msgBuffer.ReadUInt32(); propertyBag.playerHealth = msgBuffer.ReadUInt32(); propertyBag.playerHealthMax = msgBuffer.ReadUInt32(); } break; case InfiniminerMessage.TeamCashUpdate: { // ore, cash, weight, max ore, max weight, team ore, red cash, blue cash, all uint propertyBag.teamRedCash = msgBuffer.ReadUInt32(); propertyBag.teamBlueCash = msgBuffer.ReadUInt32(); } break; case InfiniminerMessage.TeamOreUpdate: { propertyBag.teamOre = msgBuffer.ReadUInt32(); } break; case InfiniminerMessage.HealthUpdate: { propertyBag.playerHealth = msgBuffer.ReadUInt32(); } break; case InfiniminerMessage.PlayerSlap: { uint pID = msgBuffer.ReadUInt32(); uint aID = msgBuffer.ReadUInt32(); if (pID == propertyBag.playerMyId) { propertyBag.screenEffect = ScreenEffect.Fall; propertyBag.screenEffectCounter = 2 - 0.5; if (aID == 0)//bomb or other hurt { propertyBag.particleEngine.CreateBloodSplatter(propertyBag.playerPosition, propertyBag.playerTeam == PlayerTeam.Red ? Color.Red : Color.Blue, 0.4f); } else//player attack { propertyBag.particleEngine.CreateBloodSplatter(propertyBag.playerPosition, propertyBag.playerTeam == PlayerTeam.Red ? Color.Red : Color.Blue, 0.2f); propertyBag.forceVector = propertyBag.playerList[aID].Heading; propertyBag.forceVector.Y = 0; //propertyBag.forceVector.Normalize(); if (propertyBag.artifactActive[(byte)propertyBag.playerTeam, 9] > 0)//stone artifact prevents kb { if (propertyBag.artifactActive[(byte)propertyBag.playerTeam, 9] < 4) propertyBag.forceStrength = 4.0f - (float)propertyBag.artifactActive[(byte)propertyBag.playerTeam, 9]; else propertyBag.forceStrength = 0; } else if (propertyBag.Content[10] == 9)//stone artifact { propertyBag.forceStrength = 0; } else { propertyBag.forceStrength = 4.0f; } } } else { if (aID == 0)//bomb or other hurt { propertyBag.particleEngine.CreateBloodSplatter(propertyBag.playerList[pID].Position, propertyBag.playerList[pID].Team == PlayerTeam.Red ? Color.Red : Color.Blue, 0.4f); } else { propertyBag.particleEngine.CreateBloodSplatter(propertyBag.playerList[pID].Position, propertyBag.playerList[pID].Team == PlayerTeam.Red ? Color.Red : Color.Blue, 0.2f); } } } break; case InfiniminerMessage.WeightUpdate: { propertyBag.playerWeight = msgBuffer.ReadUInt32(); } break; case InfiniminerMessage.OreUpdate: { propertyBag.playerOre = msgBuffer.ReadUInt32(); } break; case InfiniminerMessage.CashUpdate: { propertyBag.playerCash = msgBuffer.ReadUInt32(); } break; case InfiniminerMessage.ContentUpdate: { //update all player content values for (int a = 0; a < 50; a++) { propertyBag.Content[a] = msgBuffer.ReadInt32(); } } break; case InfiniminerMessage.ContentSpecificUpdate: { // update specific value int val = msgBuffer.ReadInt32(); propertyBag.Content[val] = msgBuffer.ReadInt32(); if (val == 10)//artifact change { switch(propertyBag.Content[val]) { case 1: propertyBag.addChatMessage("You now wield the " + ArtifactInformation.GetName(propertyBag.Content[val]) + ", granting 10 ore periodically!", ChatMessageType.SayAll, 10); break; case 2: propertyBag.addChatMessage("You now wield the " + ArtifactInformation.GetName(propertyBag.Content[val]) + ", granting life stealing attacks!", ChatMessageType.SayAll, 10); break; case 3: propertyBag.addChatMessage("You now wield the " + ArtifactInformation.GetName(propertyBag.Content[val]) + ", granting powerful life regeneration, and regenerating any nearby blocks when thrown!", ChatMessageType.SayAll, 10); break; case 4: propertyBag.addChatMessage("You now wield the " + ArtifactInformation.GetName(propertyBag.Content[val]) + ", granting water breathing and digging underwater!", ChatMessageType.SayAll, 10); break; case 5: propertyBag.addChatMessage("You now wield the " + ArtifactInformation.GetName(propertyBag.Content[val]) + ", transmuting every 100 ore into 10 gold!", ChatMessageType.SayAll, 10); break; case 6: propertyBag.addChatMessage("You now wield the " + ArtifactInformation.GetName(propertyBag.Content[val]) + ", shocking nearby enemies, and creating a torrential downpour when thrown!", ChatMessageType.SayAll, 10); break; case 7: propertyBag.addChatMessage("You now wield the " + ArtifactInformation.GetName(propertyBag.Content[val]) + ", reflecting half of damage taken!", ChatMessageType.SayAll, 10); break; case 8://medical propertyBag.addChatMessage("You now wield the " + ArtifactInformation.GetName(propertyBag.Content[val]) + ", healing friendlies with each swing; however you may no longer hit enemies!", ChatMessageType.SayAll, 10); break; case 9://stone propertyBag.addChatMessage("You now wield the " + ArtifactInformation.GetName(propertyBag.Content[val]) + ", making you immune to knockback and resistant to fall damage!", ChatMessageType.SayAll, 10); break; } } } break; case InfiniminerMessage.PlayerPosition: { // ore, cash, weight, max ore, max weight, team ore, red cash, blue cash, all uint propertyBag.playerPosition = msgBuffer.ReadVector3(); } break; case InfiniminerMessage.BlockSet: { // x, y, z, type, all bytes byte x = msgBuffer.ReadByte(); byte y = msgBuffer.ReadByte(); byte z = msgBuffer.ReadByte(); BlockType blockType = (BlockType)msgBuffer.ReadByte(); if (blockType == BlockType.None) { if (propertyBag.blockEngine.BlockAtPoint(new Vector3(x, y, z)) != BlockType.None) propertyBag.blockEngine.RemoveBlock(x, y, z); } else { if (propertyBag.blockEngine.BlockAtPoint(new Vector3(x, y, z)) != BlockType.None) { propertyBag.blockEngine.RemoveBlock(x, y, z); //propertyBag.particleEngine.CreateExplosionDebris(new Vector3(x, y, z)); } propertyBag.blockEngine.AddBlock(x, y, z, blockType); //if(!propertyBag.playerDead) //CheckForStandingInLava(); } } break; case InfiniminerMessage.BlockSetDebris: { // x, y, z, type, all bytes byte x = msgBuffer.ReadByte(); byte y = msgBuffer.ReadByte(); byte z = msgBuffer.ReadByte(); BlockType blockType = (BlockType)msgBuffer.ReadByte(); Vector3 tv = new Vector3(x, y, z); if (blockType == BlockType.None) { if (propertyBag.blockEngine.BlockAtPoint(tv) != BlockType.None) { float distFromDebris = (tv + 0.5f * Vector3.One - propertyBag.playerPosition).Length(); propertyBag.particleEngine.CreateBlockDebris(tv + 0.5f * Vector3.One, propertyBag.blockEngine.blockList[x, y, z], Math.Min(14.0f - distFromDebris, 10.0f)); propertyBag.blockEngine.RemoveBlock(x, y, z); } } } break; case InfiniminerMessage.TriggerEarthquake: { Vector3 blockPos = msgBuffer.ReadVector3(); uint expStrength = msgBuffer.ReadUInt32(); // Play the explosion sound. propertyBag.PlaySound(InfiniminerSound.Explosion, blockPos);//, (int)(expStrength/1.5)); // Create some particles. propertyBag.particleEngine.CreateExplosionDebris(blockPos); // Figure out what the effect is. float distFromExplosive = (blockPos + 0.5f * Vector3.One - propertyBag.playerPosition).Length(); propertyBag.screenEffectCounter = Math.Min(propertyBag.screenEffectCounter, 1 / 5); } break; case InfiniminerMessage.TriggerExplosion: { Vector3 blockPos = msgBuffer.ReadVector3(); uint expStrength = msgBuffer.ReadUInt32(); // Play the explosion sound. propertyBag.PlaySound(InfiniminerSound.Explosion, blockPos); // Create some particles. propertyBag.particleEngine.CreateExplosionDebris(blockPos); // Figure out what the effect is. float distFromExplosive = (blockPos + 0.5f * Vector3.One - propertyBag.playerPosition).Length(); //if (distFromExplosive < 3) // propertyBag.KillPlayer(Defines.deathByExpl);//"WAS KILLED IN AN EXPLOSION!"); //else if (distFromExplosive < 8) { // If we're not in explosion mode, turn it on with the minimum ammount of shakiness. if (propertyBag.screenEffect != ScreenEffect.Explosion) { propertyBag.screenEffect = ScreenEffect.Explosion; propertyBag.screenEffectCounter = 2; } // If this bomb would result in a bigger shake, use its value. propertyBag.screenEffectCounter = Math.Min(propertyBag.screenEffectCounter, (distFromExplosive - 2) / 5); } } break; case InfiniminerMessage.Effect: { Vector3 blockPos = msgBuffer.ReadVector3(); uint effectType = msgBuffer.ReadUInt32(); float distFromDebris = (blockPos + 0.5f * Vector3.One - propertyBag.playerPosition).Length(); if(distFromDebris < 14 && effectType == 1) propertyBag.particleEngine.CreateHidden(blockPos, Color.GhostWhite); } break; case InfiniminerMessage.TriggerDebris: { Vector3 blockPos = msgBuffer.ReadVector3(); BlockType blockType = (BlockType)msgBuffer.ReadByte(); uint debrisType = msgBuffer.ReadUInt32(); // Play the debris sound. //propertyBag.PlaySound(InfiniminerSound.Explosion, blockPos); // Create some particles. float distFromDebris = (blockPos + 0.5f * Vector3.One - propertyBag.playerPosition).Length(); if (debrisType == 1)//block was destroyed { propertyBag.particleEngine.CreateBlockDebris(blockPos, blockType, Math.Min(20.0f - distFromDebris, 10.0f)); } else if(debrisType == 0)//other players digging { if (distFromDebris < 24) propertyBag.particleEngine.CreateDiggingDebris(blockPos, blockType); } else if (debrisType == 2)//block dmg debris { if (distFromDebris < 16) if (blockType == BlockType.SolidRed) propertyBag.particleEngine.CreateBloodSplatter(blockPos, Color.Red, 1.0f); else propertyBag.particleEngine.CreateBloodSplatter(blockPos, Color.Blue, 1.0f); } else if (debrisType > 10)//anything over this determines damage intensity for hurt effect { if (distFromDebris < 15) { if (blockType == BlockType.SolidRed) propertyBag.particleEngine.CreateBloodSplatter(blockPos, Color.Red, (float)(debrisType)/100); else propertyBag.particleEngine.CreateBloodSplatter(blockPos, Color.Blue, (float)(debrisType)/100); } } } break; case InfiniminerMessage.PlayerSetTeam: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { Player player = propertyBag.playerList[playerId]; player.Team = (PlayerTeam)msgBuffer.ReadByte(); } } break; case InfiniminerMessage.PlayerSetClass: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { Player player = propertyBag.playerList[playerId]; player.Class = (PlayerClass)msgBuffer.ReadByte(); } } break; case InfiniminerMessage.PlayerJoined: { uint playerId = msgBuffer.ReadUInt32(); string playerName = msgBuffer.ReadString(); bool thisIsMe = msgBuffer.ReadBoolean(); bool playerAlive = msgBuffer.ReadBoolean(); propertyBag.playerList[playerId] = new Player(null, (Game)this); propertyBag.playerList[playerId].Handle = playerName; propertyBag.playerList[playerId].ID = playerId; propertyBag.playerList[playerId].Alive = playerAlive; propertyBag.playerList[playerId].AltColours = customColours; propertyBag.playerList[playerId].redTeam = red; propertyBag.playerList[playerId].blueTeam = blue; if (thisIsMe) propertyBag.playerMyId = playerId; } break; case InfiniminerMessage.PlayerContentUpdate: { uint playerId = msgBuffer.ReadUInt32(); uint cc = msgBuffer.ReadUInt32(); int val = msgBuffer.ReadInt32(); propertyBag.playerList[playerId].Content[cc] = val; } break; case InfiniminerMessage.PlayerLeft: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) propertyBag.playerList.Remove(playerId); } break; case InfiniminerMessage.PlayerDead: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { Player player = propertyBag.playerList[playerId]; player.Alive = false; propertyBag.particleEngine.CreateBloodSplatter(player.Position, player.Team == PlayerTeam.Red ? Color.Red : Color.Blue, 2.0f); if (playerId != propertyBag.playerMyId) propertyBag.PlaySound(InfiniminerSound.Death, player.Position); else if(propertyBag.playerDead == false) { propertyBag.PlaySound(InfiniminerSound.Death, player.Position); propertyBag.playerVelocity = Vector3.Zero; propertyBag.playerDead = true; propertyBag.allowRespawn = false; propertyBag.screenEffect = ScreenEffect.Death; propertyBag.screenEffectCounter = 0; propertyBag.Content[5] = 0; } } } break; case InfiniminerMessage.PlayerAlive: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { Player player = propertyBag.playerList[playerId]; player.Alive = true; } } break; case InfiniminerMessage.PlayerRespawn: { //propertyBag.playerList[propertyBag.playerMyId].UpdatePosition(msgBuffer.ReadVector3(), gameTime.TotalGameTime.TotalSeconds); propertyBag.playerPosition = msgBuffer.ReadVector3(); propertyBag.allowRespawn = true; } break; case InfiniminerMessage.PlayerUpdate: { uint playerId = msgBuffer.ReadUInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { Player player = propertyBag.playerList[playerId]; player.UpdatePosition(msgBuffer.ReadVector3(), gameTime.TotalGameTime.TotalSeconds); player.Heading = msgBuffer.ReadVector3(); player.Tool = (PlayerTools)msgBuffer.ReadByte(); player.UsingTool = msgBuffer.ReadBoolean(); player.Score = (uint)(msgBuffer.ReadUInt16() * 100); player.Health = (uint)(msgBuffer.ReadUInt16() * 100); } } break; case InfiniminerMessage.GameOver: { propertyBag.teamWinners = (PlayerTeam)msgBuffer.ReadByte(); } break; case InfiniminerMessage.ChatMessage: { ChatMessageType chatType = (ChatMessageType)msgBuffer.ReadByte(); string chatString = Defines.Sanitize(msgBuffer.ReadString()); //Time to break it up into multiple lines propertyBag.addChatMessage(chatString, chatType, 10); } break; case InfiniminerMessage.PlayerPing: { uint playerId = (uint)msgBuffer.ReadInt32(); if (propertyBag.playerList.ContainsKey(playerId)) { if (propertyBag.playerList[playerId].Team == propertyBag.playerTeam) { propertyBag.playerList[playerId].Ping = 1; propertyBag.PlaySound(InfiniminerSound.Ping); } } } break; case InfiniminerMessage.PlaySound: { InfiniminerSound sound = (InfiniminerSound)msgBuffer.ReadByte(); bool hasPosition = msgBuffer.ReadBoolean(); if (hasPosition) { Vector3 soundPosition = msgBuffer.ReadVector3(); propertyBag.PlaySound(sound, soundPosition); } else propertyBag.PlaySound(sound); } break; } } catch { } //Error in a received message } break; } } // Make sure our network thread actually gets to run. Thread.Sleep(1); }