public static void RenderSlice(ref BlockType[, ,] data, int z, Texture2D renderTexture) { for (int x = 0; x < 256; x++) { for (int y = 0; y < 256; y++) { uint c = 0xFF000000; if (data[x, y, z] == BlockType.Dirt) { c = 0xFFFFFFFF; } if (data[x, y, z] == BlockType.Ore) { c = 0xFF888888; } if (data[x, y, z] == BlockType.Gold) { c = 0xFFFF0000; } if (data[x, y, z] == BlockType.Rock) { c = 0xFF0000FF; } pixelData[y * 256 + x] = c; } } renderTexture.GraphicsDevice.Textures[0] = null; renderTexture.SetData(pixelData); }
public static void AddLava(ref BlockType[, ,] data, int size) { int numFlows = randGen.Next(size / 16, size / 2); while (numFlows > 0) { int x = randGen.Next(0, size); int y = randGen.Next(0, size); //switch (randGen.Next(0, 4)) //{ // case 0: x = 0; break; // case 1: x = size - 1; break; // case 2: y = 0; break; // case 3: y = size - 1; break; //} // generate a random z-value weighted toward a medium depth float zf = 0; for (int j = 0; j < 4; j++) { zf += (float)randGen.NextDouble(); } zf /= 2; zf = 1 - Math.Abs(zf - 1); int z = (int)(zf * size); if (data[x, y, z] == BlockType.None && z + 1 < size - 1) { data[x, y, z] = BlockType.Rock; data[x, y, z + 1] = BlockType.Lava; numFlows -= 1; } } }
public void SetLocs(BlockType[,,] blocks, TerrainChunk terrainChunk) { int y; var chunkHeight = SettingsHolder.Instance.currentGenerationSettings.chunkHeight; var seaLevel = SettingsHolder.Instance.currentGenerationSettings.seaLevel; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { locs[x, z] = 0; y = chunkHeight - 1; //find the ground while (y > 0 && blocks[x + 1, y, z + 1] == BlockType.Air) { y--; } if (y + 1 < seaLevel) { locs[x, z] = 1; //blocks[x+1, y+1, z+1] = BlockType.Water; while (y + 1 < seaLevel) { blocks[x + 1, y + 1, z + 1] = BlockType.Water; y++; } } } } }
//public static void AddStartingPosition(ref BlockType[, ,] data, int size, int x, int y, int z, BlockType blockType) //{ // for (int i = 0; i < size; i++) // for (int j = 0; j < size; j++) // for (int k = 0; k < size; k++) // { // double dist = Math.Sqrt(Math.Pow(x - i, 2) + Math.Pow(y - j, 2) + Math.Pow(z - k, 2)); // if (dist < 4) // { // if (k <= z) // data[i, j, k] = BlockType.None; // else if (k == z+1) // data[i, j, k] = BlockType.Metal; // else // data[i, j, k] = BlockType.Dirt; // } // } // data[x, y, z] = blockType; //} public static void AddRocks(ref BlockType[, ,] data, int size) { int numRocks = randGen.Next(size, 2 * size); CaveInfo += " numRocks=" + numRocks; for (int i = 0; i < numRocks; i++) { int x = randGen.Next(0, size); int y = randGen.Next(0, size); // generate a random z-value weighted toward a deep depth float zf = 0; for (int j = 0; j < 4; j++) { zf += (float)randGen.NextDouble(); } zf /= 2; zf = 1 - Math.Abs(zf - 1); int z = (int)(zf * size); int rockSize = (int)((randGen.NextDouble() + randGen.NextDouble() + randGen.NextDouble() + randGen.NextDouble()) / 4 * 8); PaintAtPoint(ref data, x, y, z, size, rockSize, BlockType.Rock); } }
public WorldData(int x, int y, int z, int s, BlockType[,,] d) { worldX = x; worldY = y; worldZ = z; chunkSize = s; data = d; }
void InitMap() { //初始化随机种子 Random.InitState(seed); offset0 = new Vector3(Random.value * 1000, Random.value * 1000, Random.value * 1000); offset1 = new Vector3(Random.value * 1000, Random.value * 1000, Random.value * 1000); offset2 = new Vector3(Random.value * 1000, Random.value * 1000, Random.value * 1000); //初始化Map map = new BlockType[width, height, width]; //遍历map,生成其中每个Block的信息 for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { for (int z = 0; z < width; z++) { map[x, y, z] = GenerateBlockType(new Vector3(x, y, z) + transform.position); } } } //根据生成的信息,Build出Chunk的网格 BuildChunk(); }
public void SetLocs(BlockType[,,] blocks, TerrainChunk terrainChunk) { int y; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { locs[x, z] = 0; y = TerrainChunk.chunkHeight - 1; //find the ground while (y > 0 && blocks[x + 1, y, z + 1] == BlockType.Air) { y--; } if (y + 1 < waterHeight) { locs[x, z] = 1; //blocks[x+1, y+1, z+1] = BlockType.Water; while (y + 1 < waterHeight) { blocks[x + 1, y + 1, z + 1] = BlockType.Water; y++; } } } } }
public static void Generate(BlockType[,,] blocks, int x, int y, int z, Random random) { var height = random.Next(3, 5); for (var i = 0; i < height; i++) { blocks[x, y + i, z] = BlockType.OAK_LOG; } blocks[x, y + height + 0, z] = BlockType.OAK_LEAVES; blocks[x, y + height + 1, z] = BlockType.OAK_LEAVES; blocks[x, y + height + 2, z] = BlockType.OAK_LEAVES; blocks[x, y + height + 3, z] = BlockType.OAK_LEAVES; blocks[x - 1, y + height + 0, z] = BlockType.OAK_LEAVES; blocks[x - 1, y + height + 1, z] = BlockType.OAK_LEAVES; blocks[x - 1, y + height + 2, z] = BlockType.OAK_LEAVES; blocks[x - 1, y + height + 3, z] = BlockType.OAK_LEAVES; blocks[x + 1, y + height + 0, z] = BlockType.OAK_LEAVES; blocks[x + 1, y + height + 1, z] = BlockType.OAK_LEAVES; blocks[x + 1, y + height + 2, z] = BlockType.OAK_LEAVES; blocks[x + 1, y + height + 3, z] = BlockType.OAK_LEAVES; blocks[x, y + height + 0, z - 1] = BlockType.OAK_LEAVES; blocks[x, y + height + 1, z - 1] = BlockType.OAK_LEAVES; blocks[x, y + height + 2, z - 1] = BlockType.OAK_LEAVES; blocks[x, y + height + 3, z - 1] = BlockType.OAK_LEAVES; blocks[x, y + height + 0, z + 1] = BlockType.OAK_LEAVES; blocks[x, y + height + 1, z + 1] = BlockType.OAK_LEAVES; blocks[x, y + height + 2, z + 1] = BlockType.OAK_LEAVES; blocks[x, y + height + 3, z + 1] = BlockType.OAK_LEAVES; }
/*public void ReadEnv() * { * List<BlockType[,]> blockTypes=new List<BlockType[,]>(); * //JsonMapper.ToJson(); * for (int i = 0; i < Chunk.ChunkNum; i++) * { * for (int j = 0; j < Chunk.ChunkNum; j++) * { * string Data = ""; * Data = JsonMapper.ToJson(Chunk.AllChunks[i, j].map); * string path = Saver.LevelPath + Level + "/MapData_" + i + "" + j + ".json"; * Saver.WriteJsonString(Data, path); * } * } * Debug.Log("已保存场景"); * }*/ public void ReadEnv() { List <int> blockTypes = new List <int>(); //JsonMapper.ToJson(); for (int i = 0; i < Chunk.ChunkNum; i++) { for (int j = 0; j < Chunk.ChunkNum; j++) { BlockType[,,] ss = Chunk.AllChunks[i, j].map; for (int x = 0; x < 10; x++) { for (int y = 0; y < 30; y++) { for (int z = 0; z < 10; z++) { blockTypes.Add((int)ss[x, y, z]); } } } } } string Data = ""; Data = JsonMapper.ToJson(blockTypes);; string path = Saver.LevelPath + Level + "/Leve1Data" + Level; Saver.WriteJsonString(Data, path); Debug.Log("已保存场景"); }
public static void updateChunk(ChunkPos cp, Action <BlockType[, , ], Action <int, int, int, BlockType> > cb) { TerrainChunkObject chunkObject = chunks[cp]; BlockType[,,] blocks = chunkObject.Chunk.blocks; HashSet <TerrainChunkObject> changed = new HashSet <TerrainChunkObject>(); cb(blocks, (x, y, z, block) => { updateChunkNearbyHelper(cp, changed, x, y, z, block); if (x == 1) { updateChunkNearbyHelper(new ChunkPos(cp.x - TerrainChunk.chunkWidth, cp.z), changed, TerrainChunk.chunkWidth + 1, y, z, block); } if (z == 1) { updateChunkNearbyHelper(new ChunkPos(cp.x, cp.z - TerrainChunk.chunkWidth), changed, x, y, TerrainChunk.chunkWidth + 1, block); } if (x == 1 + TerrainChunk.chunkWidth - 1) { updateChunkNearbyHelper(new ChunkPos(cp.x + TerrainChunk.chunkWidth, cp.z), changed, 0, y, z, block); } if (z == 1 + TerrainChunk.chunkWidth - 1) { updateChunkNearbyHelper(new ChunkPos(cp.x, cp.z + TerrainChunk.chunkWidth), changed, x, y, 0, block); } }); foreach (var chunk in changed) { chunk.UpdateChunk(); } }
// Gold appears in fairly numerous streaks, located at medium depths. public static void AddGold(ref BlockType[, ,] data, int size) { CaveInfo += "gold"; int numVeins = 16; for (int i = 0; i < numVeins; i++) { int fieldLength = randGen.Next(size / 3, size); float x = randGen.Next(0, size); float y = randGen.Next(0, size); // generate a random z-value weighted toward a medium depth float zf = 0; for (int j = 0; j < 4; j++) { zf += (float)randGen.NextDouble(); } zf /= 2; zf = 1 - Math.Abs(zf - 1); float z = zf * size; float dx = (float)randGen.NextDouble() * 2 - 1; float dy = (float)randGen.NextDouble() * 2 - 1; float dz = (float)randGen.NextDouble() * 2 - 1; float dl = (float)Math.Sqrt(dx * dx + dy * dy + dz * dz); dx /= dl; dy /= dl; dz /= dl; for (int j = 0; j < fieldLength; j++) { x += dx; y += dy; z += dz; if (x >= 0 && y >= 0 && z >= 0 && x < size && y < size && z < size) { data[(int)x, (int)y, (int)z] = BlockType.Gold; } int tx = 0, ty = 0, tz = 0; switch (randGen.Next(0, 3)) { case 0: tx += 1; break; case 1: ty += 1; break; case 2: tz += 1; break; } if (x + tx >= 0 && y + ty >= 0 && z + tz >= 0 && x + tx < size && y + ty < size && z + tz < size) { data[(int)x + tx, (int)y + ty, (int)z + tz] = BlockType.Gold; } } } }
public TerrainChunk(ChunkPos pos) { this.pos = pos; var chunkHeight = SettingsHolder.Instance.currentGenerationSettings.chunkHeight; blocks = new BlockType[chunkWidth + 2, chunkHeight, chunkWidth + 2]; }
void Awake() { map = new BlockType[width, height, width]; IsShowFace = new bool[width, height, width]; meshRenderer = GetComponent <MeshRenderer>(); meshCollider = GetComponent <MeshCollider>(); meshFilter = GetComponent <MeshFilter>(); }
//start loading a chunk of terrain public Chunk LoadChunk(Vector3 offset) { Chunk chunk = AllocateChunk(); chunk.offset = offset; BlockType[,,] chunkData = chunkGenerator.GenerateChunkData(offset, chunkSize); chunk.SetBlockTypes(chunkData); return(chunk); }
void Start() { cubeMeshMaker = GetComponent <ProcedureCubeMaker>(); terrain = new BlockType[length, height, width]; offset = new Vector3(0.5f, 0, 0.5f); PopulateFakeTerrainData(); MakeTerrain(); UpdateTerrain(); }
void GenerateTrees(BlockType[,,] blocks, int x, int z) { System.Random rand = new System.Random(x * 10000 + z); float simplex = noise.GetSimplex(x * .8f, z * .8f); if (simplex > 0) { simplex *= 2f; int treeCount = Mathf.FloorToInt((float)rand.NextDouble() * 5 * simplex); for (int i = 0; i < treeCount; i++) { int xPos = (int)(rand.NextDouble() * 14) + 1; int zPos = (int)(rand.NextDouble() * 14) + 1; int y = TerrainChunk.chunkHeight - 1; //find the ground while (y > 0 && blocks[xPos, y, zPos] == BlockType.Air) { y--; } y++; int treeHeight = 4 + (int)(rand.NextDouble() * 4); for (int j = 0; j < treeHeight; j++) { if (y + j < 64) { blocks[xPos, y + j, zPos] = BlockType.Trunk; } } int leavesWidth = 1 + (int)(rand.NextDouble() * 6); int leavesHeight = (int)(rand.NextDouble() * 3); int iter = 0; for (int m = y + treeHeight - 1; m <= y + treeHeight - 1 + treeHeight; m++) { for (int k = xPos - (int)(leavesWidth * .5) + iter / 2; k <= xPos + (int)(leavesWidth * .5) - iter / 2; k++) { for (int l = zPos - (int)(leavesWidth * .5) + iter / 2; l <= zPos + (int)(leavesWidth * .5) - iter / 2; l++) { if (k >= 0 && k < 16 && l >= 0 && l < 16 && m >= 0 && m < 64 && rand.NextDouble() < .8f) { blocks[k, m, l] = BlockType.Leaves; } } } iter++; } } } }
public void LoadChunk(Vector3i key, BlockType[,,] output) { for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { int wx = key.x * 16 + x; int wz = key.z * 16 + z; float foo; //float foo = Mathf.PerlinNoise(wx*0.1f, wz*0.1f); //foo = Mathf.Cos(foo*Mathf.PI)*0.5f + 0.5f; //foo *= foo; //foo *= 0.15f; foo = Mathf.PerlinNoise(123 + wx * 0.02f, 456 + wz * 0.02f) * 0.8f; foo *= 64; foo += 64; for (int y = 0; y < 16; y++) { BlockType block; int wy = key.y * 16 + y; if (wy > foo) { // Air above ground level block = BlockType.Empty; } else { // default to dirt block = new BlockType(1); if (wy < (foo - 1) * 0.95f) { // bottom is stone block = new BlockType(2); } else if (wy > (foo - 1)) { // top layer is grass block = new BlockType(3); } } if (block != BlockType.Empty) { float caves = _simplex.noise(wx * 0.05f, wy * 0.05f, wz * 0.05f); if (caves > 0.05f) { // hole block = BlockType.Empty; } } output[x, y, z] = block; } } } }
public void UpdateCollision(BlockType[,,] blocks, Point3D chunkPos, Transform transform) { if (useMeshCollider) { collider.sharedMesh = null; collider.sharedMesh = filter.sharedMesh; } else { Stack <Transform> newBoxes = new Stack <Transform>(); int cx = chunkPos.x * Chunk.BlockSize, cy = chunkPos.y * Chunk.BlockSize, cz = chunkPos.z * Chunk.BlockSize; for (int x = 1; x < Chunk.BlockSize + 1; x++) { for (int y = 1; y < Chunk.BlockSize + 1; y++) { for (int z = 1; z < Chunk.BlockSize + 1; z++) { if (blocks[x, y, z] != BlockType.Empty) { if (blocks[x + 1, y, z] == BlockType.Empty || blocks[x, y + 1, z] == BlockType.Empty || blocks[x, y, z + 1] == BlockType.Empty || blocks[x - 1, y, z] == BlockType.Empty || blocks[x, y - 1, z] == BlockType.Empty || blocks[x, y, z - 1] == BlockType.Empty) { Transform box; if (existingBoxes.Count > 0) { box = existingBoxes.Pop(); } else { BoxCollider collider = new GameObject("Collider").AddComponent <BoxCollider>(); collider.transform.parent = transform; collider.transform.localRotation = Quaternion.identity; collider.center = new Vector3(0.5f, 0.5f, 0.5f); box = collider.transform; } box.localPosition = new Vector3(cx + x - 1, cy + y - 1, cz + z - 1); newBoxes.Push(box); } } } } } while (existingBoxes.Count > 0) { GameObject.Destroy(existingBoxes.Pop().gameObject); } existingBoxes = newBoxes; } }
/// <summary> /// Creates a new terrain object. /// </summary> /// <param name="seed">The seed to use for terrain generation.</param> private Terrain( int seed ) { _densities = new TerrainDensityCollection(); _currentBlocks = new BlockType[ ChunkData.SizeXZ + 2, ChunkData.SizeY, ChunkData.SizeXZ + 2 ]; _noiseSeed = seed; _noiseModule = CreateNoiseModule( _noiseSeed ); _perlin = new Perlin() { Seed = _noiseSeed + 1 }; _hBias = 1.0f / 127; _vBias = 1.0f / 51; }
public static void Clear(BlockType[, ,] blocks, BlockType clearTo) { for (int x = 0; x < WorldSettings.MAPWIDTH; x++) { for (int y = 0; y < WorldSettings.MAPHEIGHT; y++) { for (int z = 0; z < WorldSettings.MAPLENGTH; z++) { blocks[x, y, z] = clearTo; } } } }
public void Generate(IChunkGenerator generator) { BlockType[,,] generatedBlocks = generator.Generate(ChunkPos); for (int x = 0; x < BlockSize; x++) { for (int y = 0; y < BlockSize; y++) { for (int z = 0; z < BlockSize; z++) { blocks[x + 1, y + 1, z + 1] = generatedBlocks[x, y, z]; } } } }
public BlockData(Block[,,] b) { this.matrix = new BlockType[World.chunkSize, World.chunkSize, World.chunkSize]; for (int z = 0; z < World.chunkSize; z++) { for (int y = 0; y < World.chunkSize; y++) { for (int x = 0; x < World.chunkSize; x++) { this.matrix[x, y, z] = b[x, y, z].Type; } } } }
public BlockType[, ,] GenerateMap() { _map = new BlockType[WorldSettings.MAPWIDTH, WorldSettings.MAPHEIGHT, WorldSettings.MAPLENGTH]; MapTools.Clear(_map, BlockType.None); GenerateRockLayer(); GenerateDirtLayer(15, false); CarveLandscape(); GenerateDirtLayer(10, true); GenerateSandLayer(); CarveTunnels(200); GenerateWaterLayer(); return(_map); }
/// <summary> /// Creates a new terrain object. /// </summary> /// <param name="seed">The seed to use for terrain generation.</param> private Terrain(int seed) { _densities = new TerrainDensityCollection(); _currentBlocks = new BlockType[ChunkData.SizeXZ + 2, ChunkData.SizeY, ChunkData.SizeXZ + 2]; _noiseSeed = seed; _noiseModule = CreateNoiseModule(_noiseSeed); _perlin = new Perlin() { Seed = _noiseSeed + 1 }; _hBias = 1.0f / 127; _vBias = 1.0f / 51; }
public void StoreChunk(Point3D chunkPos, BlockType[,,] blocks) { UnityEngine.Debug.Log("Store: " + chunkPos); int chunkIndex; if (!hashToFileOffset.TryGetValue(chunkPos.ToString(), out chunkIndex)) { chunkIndex = newChunkIndex++; hashToFileOffset.Add(chunkPos.ToString(), chunkIndex); hashToFileOffset.SaveDictionary(); UnityEngine.Debug.Log("New Chunk: " + chunkIndex); } chunkStorer.Save(chunkIndex, blocks); }
public bool LoadWorld() { if (File.Exists (Application.dataPath + "/Resources/" + worldName + "/" + worldName + ".dat")) { WorldData worldData; BinaryFormatter bf = new BinaryFormatter (); FileStream file = File.Open (Application.dataPath + "/Resources/" + worldName + "/" + worldName + ".dat", FileMode.Open, FileAccess.Read); worldData = (WorldData)bf.Deserialize (file); file.Close (); Debug.Log ("Loaded World: " + worldName); worldX = worldData.worldX; worldY = worldData.worldY; worldZ = worldData.worldZ; chunkSize = worldData.chunkSize; data = worldData.data; return true; } else { Debug.Log ("World \"" + worldName + "\" does not exist."); return false; } }
public static void PaintAtPoint(ref BlockType[, ,] caveData, int x, int y, int z, int size, int paintRadius, BlockType paintValue) { for (int dx = -paintRadius; dx <= paintRadius; dx++) { for (int dy = -paintRadius; dy <= paintRadius; dy++) { for (int dz = -paintRadius; dz <= paintRadius; dz++) { if (x + dx >= 0 && y + dy >= 0 && z + dz >= 0 && x + dx < size && y + dy < size && z + dz < size) { if (dx * dx + dy * dy + dz * dz < paintRadius * paintRadius) { caveData[x + dx, y + dy, z + dz] = paintValue; } } } } } }
/// <summary> /// Saves a chunk to the file. Block dimensions must be the Chunk.BlockSize. /// </summary> public void Save(int index, BlockType[,,] blocks) { if (blocks.Length != ChunkLength) { throw new ArgumentException("Chunk length != block length (" + ChunkLength + " != " + blocks.Length + ")"); } fileStream.Seek(index * ChunkLength, SeekOrigin.Begin); for (int x = 0; x < Chunk.BlockSize; x++) { for (int y = 0; y < Chunk.BlockSize; y++) { for (int z = 0; z < Chunk.BlockSize; z++) { fileStream.WriteByte((byte)blocks[x, y, z]); } } } }
public void BuildMap() { chunkData = new BlockType[World.Instance.chunkSize, World.Instance.chunkHeight, World.Instance.chunkSize]; blockData = new Block[World.Instance.chunkSize, World.Instance.chunkHeight, World.Instance.chunkSize]; //PerlinNoise Algoritm- generates a texture of float values that follow a specific pattern to render cubes for (int x = 0; x < World.Instance.chunkSize; x++) { for (int z = 0; z < World.Instance.chunkSize; z++) { bool prevair = true; for (int y = World.Instance.chunkHeight - 1; y > 0; y--) { if (y < World.Instance.n.GenerateHeight(x + transform.position.x, z + transform.position.z)) { if (prevair) { prevair = false; chunkData[x, y, z] = BlockType.GRASS; } else { chunkData[x, y, z] = BlockType.DIRT; } } else if (y < World.Instance.WaterHeight) { chunkData[x, y, z] = BlockType.STONE; } else { chunkData[x, y, z] = BlockType.AIR; } } } } }
public static void AddDiamond(ref BlockType[, ,] data, int size) { CaveInfo += "diamond"; int numDiamonds = 16; for (int i = 0; i < numDiamonds; i++) { int x = randGen.Next(0, size); int y = randGen.Next(0, size); // generate a random z-value weighted toward a deep depth float zf = 0; for (int j = 0; j < 4; j++) { zf += (float)randGen.NextDouble(); } zf /= 2; zf = 1 - Math.Abs(zf - 1); int z = (int)(zf * size); data[x, y, z] = BlockType.Diamond; } }
public BlockEngine(InfiniminerGame gameInstance) { this.gameInstance = gameInstance; // Initialize the block list. downloadList = new BlockType[MAPSIZE, MAPSIZE, MAPSIZE]; blockList = new BlockType[MAPSIZE, MAPSIZE, MAPSIZE]; for (ushort i = 0; i < MAPSIZE; i++) for (ushort j = 0; j < MAPSIZE; j++) for (ushort k = 0; k < MAPSIZE; k++) { downloadList[i, j, k] = BlockType.None; blockList[i, j, k] = BlockType.None; } // Initialize the face lists. faceMap = new Dictionary<uint,bool>[(byte)BlockTexture.MAXIMUM, NUMREGIONS]; for (BlockTexture blockTexture = BlockTexture.None; blockTexture < BlockTexture.MAXIMUM; blockTexture++) for (int r=0; r<NUMREGIONS; r++) faceMap[(byte)blockTexture, r] = new Dictionary<uint, bool>(); // Initialize the texture map. blockTextureMap = new BlockTexture[(byte)BlockType.MAXIMUM, 6]; for (BlockType blockType = BlockType.None; blockType < BlockType.MAXIMUM; blockType++) for (BlockFaceDirection faceDir = BlockFaceDirection.XIncreasing; faceDir < BlockFaceDirection.MAXIMUM; faceDir++) blockTextureMap[(byte)blockType,(byte)faceDir] = BlockInformation.GetTexture(blockType, faceDir); // Load the textures we'll use. blockTextures = new IMTexture[(byte)BlockTexture.MAXIMUM]; blockTextures[(byte)BlockTexture.None] = new IMTexture(null); blockTextures[(byte)BlockTexture.Dirt] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_dirt")); blockTextures[(byte)BlockTexture.Rock] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_rock")); blockTextures[(byte)BlockTexture.Ore] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_ore")); blockTextures[(byte)BlockTexture.Gold] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_silver")); blockTextures[(byte)BlockTexture.Diamond] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_diamond")); blockTextures[(byte)BlockTexture.HomeRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_home_red")); blockTextures[(byte)BlockTexture.HomeBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_home_blue")); blockTextures[(byte)BlockTexture.SolidRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_red")); blockTextures[(byte)BlockTexture.SolidBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_blue")); blockTextures[(byte)BlockTexture.Ladder] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_ladder")); blockTextures[(byte)BlockTexture.LadderTop] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_ladder_top")); blockTextures[(byte)BlockTexture.Spikes] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_spikes")); blockTextures[(byte)BlockTexture.Jump] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_jump")); blockTextures[(byte)BlockTexture.JumpTop] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_jump_top")); blockTextures[(byte)BlockTexture.Explosive] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_explosive")); blockTextures[(byte)BlockTexture.Metal] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_metal")); blockTextures[(byte)BlockTexture.DirtSign] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_dirt_sign")); blockTextures[(byte)BlockTexture.BankTopRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_top_red")); blockTextures[(byte)BlockTexture.BankLeftRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_left_red")); blockTextures[(byte)BlockTexture.BankFrontRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_front_red")); blockTextures[(byte)BlockTexture.BankRightRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_right_red")); blockTextures[(byte)BlockTexture.BankBackRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_back_red")); blockTextures[(byte)BlockTexture.BankTopBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_top_blue")); blockTextures[(byte)BlockTexture.BankLeftBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_left_blue")); blockTextures[(byte)BlockTexture.BankFrontBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_front_blue")); blockTextures[(byte)BlockTexture.BankRightBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_right_blue")); blockTextures[(byte)BlockTexture.BankBackBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_back_blue")); blockTextures[(byte)BlockTexture.TeleSideA] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_teleporter_a")); blockTextures[(byte)BlockTexture.TeleSideB] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_teleporter_b")); blockTextures[(byte)BlockTexture.TeleTop] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_teleporter_top")); blockTextures[(byte)BlockTexture.TeleBottom] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_teleporter_bottom")); blockTextures[(byte)BlockTexture.Lava] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_lava")); blockTextures[(byte)BlockTexture.Road] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_road")); blockTextures[(byte)BlockTexture.RoadTop] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_road_top")); blockTextures[(byte)BlockTexture.RoadBottom] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_road_bottom")); blockTextures[(byte)BlockTexture.BeaconRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_beacon_top_red")); blockTextures[(byte)BlockTexture.BeaconBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_beacon_top_blue")); blockTextures[(byte)BlockTexture.TransRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_trans_red")); blockTextures[(byte)BlockTexture.TransBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_trans_blue")); // Load our effects. basicEffect = gameInstance.Content.Load<Effect>("effect_basic"); // Build vertex lists. vertexBuffers = new DynamicVertexBuffer[(byte)BlockTexture.MAXIMUM, NUMREGIONS]; vertexListDirty = new bool[(byte)BlockTexture.MAXIMUM, NUMREGIONS]; for (int i = 0; i < (byte)BlockTexture.MAXIMUM; i++) for (int j = 0; j < NUMREGIONS; j++) vertexListDirty[i, j] = true; // Initialize any graphics stuff. vertexDeclaration = new VertexDeclaration(gameInstance.GraphicsDevice, VertexPositionTextureShade.VertexElements); // Initialize the bloom engine. if (gameInstance.RenderPretty) { bloomPosteffect = new BloomComponent(); bloomPosteffect.Load(gameInstance.GraphicsDevice, gameInstance.Content); } else bloomPosteffect = null; }
public bool Start() { //Setup the variable toggles varBindingsInitialize(); int tmpMaxPlayers = 16; // Read in from the config file. DatafileWriter dataFile = new DatafileWriter("server.config.txt"); if (dataFile.Data.ContainsKey("winningcash")) winningCashAmount = uint.Parse(dataFile.Data["winningcash"], System.Globalization.CultureInfo.InvariantCulture); if (dataFile.Data.ContainsKey("includelava")) includeLava = bool.Parse(dataFile.Data["includelava"]); if (dataFile.Data.ContainsKey("orefactor")) oreFactor = uint.Parse(dataFile.Data["orefactor"], System.Globalization.CultureInfo.InvariantCulture); if (dataFile.Data.ContainsKey("maxplayers")) tmpMaxPlayers = (int)Math.Min(32, uint.Parse(dataFile.Data["maxplayers"], System.Globalization.CultureInfo.InvariantCulture)); if (dataFile.Data.ContainsKey("public")) varSet("public", bool.Parse(dataFile.Data["public"]), true); if (dataFile.Data.ContainsKey("servername")) varSet("name", dataFile.Data["servername"], true); if (dataFile.Data.ContainsKey("sandbox")) varSet("sandbox", bool.Parse(dataFile.Data["sandbox"]), true); if (dataFile.Data.ContainsKey("notnt")) varSet("tnt", !bool.Parse(dataFile.Data["notnt"]), true); if (dataFile.Data.ContainsKey("sphericaltnt")) varSet("stnt", bool.Parse(dataFile.Data["sphericaltnt"]), true); if (dataFile.Data.ContainsKey("insanelava")) varSet("insanelava", bool.Parse(dataFile.Data["insanelava"]), true); if (dataFile.Data.ContainsKey("shockspreadslava")) varSet("sspreads", bool.Parse(dataFile.Data["shockspreadslava"]), true); if (dataFile.Data.ContainsKey("roadabsorbs")) varSet("roadabsorbs", bool.Parse(dataFile.Data["roadabsorbs"]), true); if (dataFile.Data.ContainsKey("minelava")) varSet("minelava", bool.Parse(dataFile.Data["minelava"]), true); if (dataFile.Data.ContainsKey("levelname")) levelToLoad = dataFile.Data["levelname"]; if (dataFile.Data.ContainsKey("greeter")) varSet("greeter", dataFile.Data["greeter"], true); bool autoannounce = true; if (dataFile.Data.ContainsKey("autoannounce")) autoannounce = bool.Parse(dataFile.Data["autoannounce"]); // Load the ban-list. banList = LoadBanList(); // Load the admin-list admins = LoadAdminList(); if (tmpMaxPlayers >= 0) varSet("maxplayers", tmpMaxPlayers, true); // Initialize the server. NetConfiguration netConfig = new NetConfiguration("InfiniminerPlus"); netConfig.MaxConnections = (int)varGetI("maxplayers"); netConfig.Port = 5565; netServer = new InfiniminerNetServer(netConfig); netServer.SetMessageTypeEnabled(NetMessageType.ConnectionApproval, true); //netServer.SimulatedMinimumLatency = 0.1f; //netServer.SimulatedLatencyVariance = 0.05f; //netServer.SimulatedLoss = 0.1f; //netServer.SimulatedDuplicates = 0.05f; netServer.Start(); // Initialize variables we'll use. NetBuffer msgBuffer = netServer.CreateBuffer(); NetMessageType msgType; NetConnection msgSender; // Store the last time that we did a flow calculation. DateTime lastFlowCalc = DateTime.Now; //Check if we should autoload a level if (dataFile.Data.ContainsKey("autoload") && bool.Parse(dataFile.Data["autoload"])) { blockList = new BlockType[MAPSIZE, MAPSIZE, MAPSIZE]; blockCreatorTeam = new PlayerTeam[MAPSIZE, MAPSIZE, MAPSIZE]; LoadLevel(levelToLoad); } else { // Calculate initial lava flows. ConsoleWrite("CALCULATING INITIAL LAVA FLOWS"); ConsoleWrite("TOTAL LAVA BLOCKS = " + newMap()); } //Caculate the shape of spherical tnt explosions CalculateExplosionPattern(); // Send the initial server list update. if (autoannounce) PublicServerListUpdate(true); lastMapBackup = DateTime.Now; // Main server loop! ConsoleWrite("SERVER READY"); while (keepRunning) { // Process any messages that are here. while (netServer.ReadMessage(msgBuffer, out msgType, out msgSender)) { try { switch (msgType) { case NetMessageType.ConnectionApproval: { Player newPlayer = new Player(msgSender, null); newPlayer.Handle = Defines.Sanitize(msgBuffer.ReadString()).Trim(); if (newPlayer.Handle.Length == 0) { newPlayer.Handle = "Player"; } string clientVersion = msgBuffer.ReadString(); if (clientVersion != Defines.INFINIMINER_VERSION) { msgSender.Disapprove("VER;" + Defines.INFINIMINER_VERSION); } else if (banList.Contains(newPlayer.IP)) { msgSender.Disapprove("BAN;"); }/* else if (playerList.Count == maxPlayers) { msgSender.Disapprove("FULL;"); }*/ else { if (admins.ContainsKey(newPlayer.IP)) newPlayer.admin = admins[newPlayer.IP]; playerList[msgSender] = newPlayer; //Check if we should compress the map for the client try { bool compression = msgBuffer.ReadBoolean(); if (compression) playerList[msgSender].compression = true; } catch { } toGreet.Add(msgSender); this.netServer.SanityCheck(msgSender); msgSender.Approve(); PublicServerListUpdate(true); } } break; case NetMessageType.StatusChanged: { if (!this.playerList.ContainsKey(msgSender)) { break; } Player player = playerList[msgSender]; if (msgSender.Status == NetConnectionStatus.Connected) { ConsoleWrite("CONNECT: " + playerList[msgSender].Handle + " ( " + playerList[msgSender].IP + " )"); SendCurrentMap(msgSender); SendPlayerJoined(player); PublicServerListUpdate(); } else if (msgSender.Status == NetConnectionStatus.Disconnected) { ConsoleWrite("DISCONNECT: " + playerList[msgSender].Handle); SendPlayerLeft(player, player.Kicked ? "WAS KICKED FROM THE GAME!" : "HAS ABANDONED THEIR DUTIES!"); if (playerList.ContainsKey(msgSender)) playerList.Remove(msgSender); PublicServerListUpdate(); } } break; case NetMessageType.Data: { if (!this.playerList.ContainsKey(msgSender)) { break; } Player player = playerList[msgSender]; //If player isnt arround we dont care anymore - Cbock //If player is suspected of modding ignore updates for this cycle - Cbock if (player.Kicked == true || player.Flagged == true) break; InfiniminerMessage dataType = (InfiniminerMessage)msgBuffer.ReadByte(); switch (dataType) { case InfiniminerMessage.ChatMessage: { // Read the data from the packet. ChatMessageType chatType = (ChatMessageType)msgBuffer.ReadByte(); string chatString = Defines.Sanitize(msgBuffer.ReadString()); if (!ProcessCommand(chatString, GetAdmin(playerList[msgSender].IP), playerList[msgSender])) { ConsoleWrite("CHAT: (" + player.Handle + ") " + chatString); // Append identifier information. if (chatType == ChatMessageType.SayAll) chatString = player.Handle + " (ALL): " + chatString; else chatString = player.Handle + " (TEAM): " + chatString; // Construct the message packet. NetBuffer chatPacket = netServer.CreateBuffer(); chatPacket.Write((byte)InfiniminerMessage.ChatMessage); chatPacket.Write((byte)((player.Team == PlayerTeam.Red) ? ChatMessageType.SayRedTeam : ChatMessageType.SayBlueTeam)); chatPacket.Write(chatString); // Send the packet to people who should recieve it. foreach (Player p in playerList.Values) { if (chatType == ChatMessageType.SayAll || chatType == ChatMessageType.SayBlueTeam && p.Team == PlayerTeam.Blue || chatType == ChatMessageType.SayRedTeam && p.Team == PlayerTeam.Red) if (p.NetConn.Status == NetConnectionStatus.Connected) netServer.SendMessage(chatPacket, p.NetConn, NetChannel.ReliableInOrder3); } } } break; case InfiniminerMessage.UseTool: { Vector3 playerPosition = msgBuffer.ReadVector3(); Vector3 playerHeading = msgBuffer.ReadVector3(); PlayerTools playerTool = (PlayerTools)msgBuffer.ReadByte(); BlockType blockType = (BlockType)msgBuffer.ReadByte(); switch (playerTool) { case PlayerTools.Pickaxe: //Modification to prevent client from ignoring axe cooldown times - Cbock updateTime = DateTime.Now - player.AxeUsed; if (updateTime.TotalSeconds < 0.1f) { player.Flagged = true; } else { player.AxeUsed = DateTime.Now; UsePickaxe(player, playerPosition, playerHeading); } break; case PlayerTools.ConstructionGun: //Modification to prevent client from ignoring gun cooldown times - Cbock updateTime = DateTime.Now - player.GunUsed; if (updateTime.TotalSeconds < 0.35f) { player.Flagged = true; } else { player.GunUsed = DateTime.Now; UseConstructionGun(player, playerPosition, playerHeading, blockType); } //End Mod break; case PlayerTools.DeconstructionGun: //Modification to prevent client from ignoring gun cooldown times - Cbock updateTime = DateTime.Now - player.GunUsed; if (updateTime.TotalSeconds < 0.35f) { player.Flagged = true; } else { player.GunUsed = DateTime.Now; UseDeconstructionGun(player, playerPosition, playerHeading); } //End Mod break; case PlayerTools.ProspectingRadar: UseSignPainter(player, playerPosition, playerHeading); break; case PlayerTools.Detonator: UseDetonator(player); break; } } break; case InfiniminerMessage.SelectClass: { PlayerClass playerClass = (PlayerClass)msgBuffer.ReadByte(); ConsoleWrite("SELECT_CLASS: " + player.Handle + ", " + playerClass.ToString()); switch (playerClass) { case PlayerClass.Engineer: player.OreMax = 350; player.WeightMax = 4; break; case PlayerClass.Miner: player.OreMax = 200; player.WeightMax = 8; break; case PlayerClass.Prospector: player.OreMax = 200; player.WeightMax = 4; break; case PlayerClass.Sapper: player.OreMax = 200; player.WeightMax = 4; break; } SendResourceUpdate(player); } break; case InfiniminerMessage.PlayerSetTeam: { PlayerTeam playerTeam = (PlayerTeam)msgBuffer.ReadByte(); ConsoleWrite("SELECT_TEAM: " + player.Handle + ", " + playerTeam.ToString()); player.Team = playerTeam; SendResourceUpdate(player); SendPlayerSetTeam(player); } break; case InfiniminerMessage.PlayerDead: { ConsoleWrite("PLAYER_DEAD: " + player.Handle); player.Ore = 0; player.Cash = 0; player.Weight = 0; player.Alive = false; SendResourceUpdate(player); SendPlayerDead(player); string deathMessage = msgBuffer.ReadString(); if (deathMessage != "") { msgBuffer = netServer.CreateBuffer(); msgBuffer.Write((byte)InfiniminerMessage.ChatMessage); msgBuffer.Write((byte)(player.Team == PlayerTeam.Red ? ChatMessageType.SayRedTeam : ChatMessageType.SayBlueTeam)); msgBuffer.Write(player.Handle + " " + deathMessage); foreach (NetConnection netConn in playerList.Keys) if (netConn.Status == NetConnectionStatus.Connected) netServer.SendMessage(msgBuffer, netConn, NetChannel.ReliableInOrder3); } } break; case InfiniminerMessage.PlayerAlive: { if (toGreet.Contains(msgSender)) { string greeting = varGetS("greeter"); greeting = greeting.Replace("[name]", playerList[msgSender].Handle); if (greeting != "") { NetBuffer greetBuffer = netServer.CreateBuffer(); greetBuffer.Write((byte)InfiniminerMessage.ChatMessage); greetBuffer.Write((byte)ChatMessageType.SayAll); greetBuffer.Write(Defines.Sanitize(greeting)); netServer.SendMessage(greetBuffer, msgSender, NetChannel.ReliableInOrder3); } toGreet.Remove(msgSender); } ConsoleWrite("PLAYER_ALIVE: " + player.Handle); player.Ore = 0; player.Cash = 0; player.Weight = 0; player.Alive = true; SendResourceUpdate(player); SendPlayerAlive(player); } break; case InfiniminerMessage.PlayerUpdate: { player.Position = msgBuffer.ReadVector3(); player.Heading = msgBuffer.ReadVector3(); // Code to pervent speed, no clipping, and flying mods - DCaudill // Find out if the player is in the air Vector3 footPosition = player.Position + new Vector3(0f, -1.5f, 0f); BlockType standingOnBlock = BlockAtPoint(new Vector3(footPosition.X, footPosition.Y, footPosition.Z)); bool inAir = false; if (standingOnBlock == BlockType.None && !CheckOnLadder(player)) inAir = true; // Update the players list of last 10 updates playerList[msgSender].UpdatePositionServer(player.Position, inAir, player.Alive, DateTime.Now); // Check for speed mods and kick if found if (CheckSpeed(player) && player.positionList.Count > 9) { KickPlayer(player.IP); SendServerMessage(player.Handle + " was kicked for speed mods, Sorry"); ConsoleWrite(player.Handle + " was kicked for speed mods, Sorry"); } // Check for flying mods and kick if found if (CheckFlying(player) && player.positionList.Count > 9) { KickPlayer(player.IP); SendServerMessage(player.Handle + " was kicked for flying, Sorry"); ConsoleWrite(player.Handle + " was kicked for flying mods, Sorry"); } // Check for no clipping mods and kick if found if (CheckNoClipping(player) && player.positionList.Count > 9) { KickPlayer(player.IP); SendServerMessage(player.Handle + " was kicked for no clipping, Sorry"); ConsoleWrite(player.Handle + " was kicked for no clipping, Sorry"); } player.Tool = (PlayerTools)msgBuffer.ReadByte(); player.UsingTool = msgBuffer.ReadBoolean(); SendPlayerUpdate(player); } break; case InfiniminerMessage.DepositOre: { DepositOre(player); foreach (Player p in playerList.Values) SendResourceUpdate(p); } break; case InfiniminerMessage.WithdrawOre: { WithdrawOre(player); foreach (Player p in playerList.Values) SendResourceUpdate(p); } break; case InfiniminerMessage.PlayerPing: { SendPlayerPing((uint)msgBuffer.ReadInt32()); } break; case InfiniminerMessage.PlaySound: { InfiniminerSound sound = (InfiniminerSound)msgBuffer.ReadByte(); Vector3 position = msgBuffer.ReadVector3(); PlaySound(sound, position); } break; } } break; } } catch { } } // Unflag all clients after data is finished being parsed - Cbock foreach (Player p in playerList.Values) { p.Flagged = false; } //Time to backup map? TimeSpan mapUpdateTimeSpan = DateTime.Now - lastMapBackup; if (mapUpdateTimeSpan.TotalMinutes > 5) { SaveLevel("autoBK.lvl"); } // Time to send a new server update? PublicServerListUpdate(); //It checks for public server / time span //Time to terminate finished map sending threads? TerminateFinishedThreads(); // Check for players who are in the zone to deposit. DepositForPlayers(); // Is it time to do a lava calculation? If so, do it! TimeSpan timeSpan = DateTime.Now - lastFlowCalc; if (timeSpan.TotalMilliseconds > 500) { DoLavaStuff(); lastFlowCalc = DateTime.Now; } // Handle console keypresses. while (Console.KeyAvailable) { ConsoleKeyInfo keyInfo = Console.ReadKey(); if (keyInfo.Key == ConsoleKey.Enter) ConsoleProcessInput(); else if (keyInfo.Key == ConsoleKey.Backspace) { if (consoleInput.Length > 0) consoleInput = consoleInput.Substring(0, consoleInput.Length - 1); ConsoleRedraw(); } else { consoleInput += keyInfo.KeyChar; ConsoleRedraw(); } } // Is the game over? if (winningTeam != PlayerTeam.None && !restartTriggered) { BroadcastGameOver(); restartTriggered = true; restartTime = DateTime.Now.AddSeconds(10); } // Restart the server? if (restartTriggered && DateTime.Now > restartTime) { SaveLevel("autosave_" + (UInt64)DateTime.Now.ToBinary() + ".lvl"); netServer.Shutdown("The server is restarting."); return true; } // Pass control over to waiting threads. Thread.Sleep(1); } MessageAll("Server going down NOW!"); netServer.Shutdown("The server was terminated."); return false; }
public int newMap() { // Create our block world, translating the coordinates out of the cave generator (where Z points down) BlockType[, ,] worldData = CaveGenerator.GenerateCaveSystem(MAPSIZE, includeLava, oreFactor); blockList = new BlockType[MAPSIZE, MAPSIZE, MAPSIZE]; blockCreatorTeam = new PlayerTeam[MAPSIZE, MAPSIZE, MAPSIZE]; for (ushort i = 0; i < MAPSIZE; i++) for (ushort j = 0; j < MAPSIZE; j++) for (ushort k = 0; k < MAPSIZE; k++) { blockList[i, (ushort)(MAPSIZE - 1 - k), j] = worldData[i, j, k]; blockCreatorTeam[i, j, k] = PlayerTeam.None; } for (int i = 0; i < MAPSIZE * 2; i++) DoLavaStuff(); return lavaBlockCount; }
public bool Start() { // Read in from the config file. DatafileLoader dataFile = new DatafileLoader("server.config.txt"); if (dataFile.Data.ContainsKey("winningcash")) winningCashAmount = uint.Parse(dataFile.Data["winningcash"], System.Globalization.CultureInfo.InvariantCulture); if (dataFile.Data.ContainsKey("includelava")) includeLava = bool.Parse(dataFile.Data["includelava"]); if (dataFile.Data.ContainsKey("orefactor")) oreFactor = uint.Parse(dataFile.Data["orefactor"], System.Globalization.CultureInfo.InvariantCulture); if (dataFile.Data.ContainsKey("maxplayers")) maxPlayers = Math.Min(32, uint.Parse(dataFile.Data["maxplayers"], System.Globalization.CultureInfo.InvariantCulture)); if (dataFile.Data.ContainsKey("public")) publicServer = bool.Parse(dataFile.Data["public"]); if (dataFile.Data.ContainsKey("servername")) serverName = dataFile.Data["servername"]; if (dataFile.Data.ContainsKey("sandbox")) sandboxMode = bool.Parse(dataFile.Data["sandbox"]); // Load the ban-list. banList = LoadBanList(); // Create our block world, translating the coordinates out of the cave generator (where Z points down) BlockType[, ,] worldData = CaveGenerator.GenerateCaveSystem(GlobalVariables.MAPSIZE, includeLava, oreFactor); blockList = new BlockType[GlobalVariables.MAPSIZE, GlobalVariables.MAPSIZE, GlobalVariables.MAPSIZE]; blockCreatorTeam = new PlayerTeam[GlobalVariables.MAPSIZE, GlobalVariables.MAPSIZE, GlobalVariables.MAPSIZE]; for (ushort i = 0; i < GlobalVariables.MAPSIZE; i++) for (ushort j = 0; j < GlobalVariables.MAPSIZE; j++) for (ushort k = 0; k < GlobalVariables.MAPSIZE; k++) { blockList[i, (ushort)(GlobalVariables.MAPSIZE - 1 - k), j] = worldData[i, j, k]; if(blockList[i, (ushort)(GlobalVariables.MAPSIZE - 1 - k), j] == BlockType.Lava) LavaBlocks.Add(new InfiniminerServer.Point3D() { X = (ushort)i, Y = (ushort)(GlobalVariables.MAPSIZE - 1 - k), Z = (ushort)j }, 0); blockCreatorTeam[i, j, k] = PlayerTeam.None; } // Initialize the server. NetConfiguration netConfig = new NetConfiguration("InfiniminerPlus"); netConfig.MaxConnections = (int)maxPlayers; netConfig.Port = 5565; netServer = new InfiniminerNetServer(netConfig); netServer.SetMessageTypeEnabled(NetMessageType.ConnectionApproval, true); //netServer.SimulatedMinimumLatency = 0.1f; //netServer.SimulatedLatencyVariance = 0.05f; //netServer.SimulatedLoss = 0.1f; //netServer.SimulatedDuplicates = 0.05f; netServer.Start(); // Initialize variables we'll use. NetBuffer msgBuffer = netServer.CreateBuffer(); NetMessageType msgType; NetConnection msgSender; // Store the last time that we did a flow calculation. DateTime lastFlowCalc = DateTime.Now; // Calculate initial lava flows. ConsoleWrite("CALCULATING INITIAL LAVA FLOWS"); while (DoLavaStuff()) ; ConsoleWrite("TOTAL LAVA BLOCKS = " + LavaBlocks.Count); // Send the initial server list update. PublicServerListUpdate(); // Main server loop! ConsoleWrite("SERVER READY"); while (keepRunning) { // Process any messages that are here. while (netServer.ReadMessage(msgBuffer, out msgType, out msgSender)) { switch (msgType) { case NetMessageType.ConnectionApproval: { Player newPlayer = new Player(msgSender, null); newPlayer.Handle = InfiniminerGame.Sanitize(msgBuffer.ReadString()).Trim(); if (newPlayer.Handle.Length == 0) { newPlayer.Handle = "Player"; } string clientVersion = msgBuffer.ReadString(); if (clientVersion != InfiniminerGame.INFINIMINER_VERSION) { msgSender.Disapprove("VER;" + InfiniminerGame.INFINIMINER_VERSION); } else if (banList.Contains(newPlayer.IP)) { msgSender.Disapprove("BAN;"); } else { playerList[msgSender] = newPlayer; this.netServer.SanityCheck(msgSender); msgSender.Approve(); } } break; case NetMessageType.StatusChanged: { if (!this.playerList.ContainsKey(msgSender)) { break; } Player player = playerList[msgSender]; if (msgSender.Status == NetConnectionStatus.Connected) { ConsoleWrite("CONNECT: " + playerList[msgSender].Handle); SendCurrentMap(msgSender); SendPlayerJoined(player); PublicServerListUpdate(); } else if (msgSender.Status == NetConnectionStatus.Disconnected) { ConsoleWrite("DISCONNECT: " + playerList[msgSender].Handle); SendPlayerLeft(player, player.Kicked ? "WAS KICKED FROM THE GAME!" : "HAS ABANDONED THEIR DUTIES!"); if (playerList.ContainsKey(msgSender)) playerList.Remove(msgSender); PublicServerListUpdate(); } } break; case NetMessageType.Data: { if (!this.playerList.ContainsKey(msgSender)) { break; } Player player = playerList[msgSender]; InfiniminerMessage dataType = (InfiniminerMessage)msgBuffer.ReadByte(); switch (dataType) { case InfiniminerMessage.ChatMessage: { // Read the data from the packet. ChatMessageType chatType = (ChatMessageType)msgBuffer.ReadByte(); string chatString = InfiniminerGame.Sanitize(msgBuffer.ReadString()); ConsoleWrite("CHAT: (" + player.Handle + ") " + chatString); // Append identifier information. if (chatType == ChatMessageType.SayAll) chatString = player.Handle + " (ALL): " + chatString; else chatString = player.Handle + " (TEAM): " + chatString; // Construct the message packet. NetBuffer chatPacket = netServer.CreateBuffer(); chatPacket.Write((byte)InfiniminerMessage.ChatMessage); chatPacket.Write((byte)((player.Team == PlayerTeam.Red) ? ChatMessageType.SayRedTeam : ChatMessageType.SayBlueTeam)); chatPacket.Write(chatString); // Send the packet to people who should recieve it. foreach (Player p in playerList.Values) { if (chatType == ChatMessageType.SayAll || chatType == ChatMessageType.SayBlueTeam && p.Team == PlayerTeam.Blue || chatType == ChatMessageType.SayRedTeam && p.Team == PlayerTeam.Red) if (p.NetConn.Status == NetConnectionStatus.Connected) netServer.SendMessage(chatPacket, p.NetConn, NetChannel.ReliableInOrder3); } } break; case InfiniminerMessage.UseTool: { Vector3 playerPosition = msgBuffer.ReadVector3(); Vector3 playerHeading = msgBuffer.ReadVector3(); PlayerTools playerTool = (PlayerTools)msgBuffer.ReadByte(); BlockType blockType = (BlockType)msgBuffer.ReadByte(); switch (playerTool) { case PlayerTools.Pickaxe: UsePickaxe(player, playerPosition, playerHeading); break; case PlayerTools.ConstructionGun: UseConstructionGun(player, playerPosition, playerHeading, blockType); break; case PlayerTools.DeconstructionGun: UseDeconstructionGun(player, playerPosition, playerHeading); break; case PlayerTools.ProspectingRadar: UseSignPainter(player, playerPosition, playerHeading); break; case PlayerTools.Detonator: UseDetonator(player); break; } } break; case InfiniminerMessage.SelectClass: { PlayerClass playerClass = (PlayerClass)msgBuffer.ReadByte(); ConsoleWrite("SELECT_CLASS: " + player.Handle + ", " + playerClass.ToString()); switch (playerClass) { case PlayerClass.Engineer: player.OreMax = 350; player.WeightMax = 4; break; case PlayerClass.Miner: player.OreMax = 200; player.WeightMax = 8; break; case PlayerClass.Prospector: player.OreMax = 200; player.WeightMax = 4; break; case PlayerClass.Sapper: player.OreMax = 200; player.WeightMax = 4; break; } SendResourceUpdate(player); } break; case InfiniminerMessage.PlayerSetTeam: { PlayerTeam playerTeam = (PlayerTeam)msgBuffer.ReadByte(); ConsoleWrite("SELECT_TEAM: " + player.Handle + ", " + playerTeam.ToString()); player.Team = playerTeam; SendResourceUpdate(player); SendPlayerSetTeam(player); } break; case InfiniminerMessage.PlayerDead: { ConsoleWrite("PLAYER_DEAD: " + player.Handle); player.Ore = 0; player.Cash = 0; player.Weight = 0; player.Alive = false; SendResourceUpdate(player); SendPlayerDead(player); string deathMessage = msgBuffer.ReadString(); if (deathMessage != "") { msgBuffer = netServer.CreateBuffer(); msgBuffer.Write((byte)InfiniminerMessage.ChatMessage); msgBuffer.Write((byte)(player.Team == PlayerTeam.Red ? ChatMessageType.SayRedTeam : ChatMessageType.SayBlueTeam)); msgBuffer.Write(player.Handle + " " + deathMessage); foreach (NetConnection netConn in playerList.Keys) if (netConn.Status == NetConnectionStatus.Connected) netServer.SendMessage(msgBuffer, netConn, NetChannel.ReliableInOrder3); } } break; case InfiniminerMessage.PlayerAlive: { ConsoleWrite("PLAYER_ALIVE: " + player.Handle); player.Ore = 0; player.Cash = 0; player.Weight = 0; player.Alive = true; SendResourceUpdate(player); SendPlayerAlive(player); } break; case InfiniminerMessage.PlayerUpdate: { player.Position = msgBuffer.ReadVector3(); player.Heading = msgBuffer.ReadVector3(); player.Tool = (PlayerTools)msgBuffer.ReadByte(); player.UsingTool = msgBuffer.ReadBoolean(); SendPlayerUpdate(player); } break; case InfiniminerMessage.DepositOre: { DepositOre(player); foreach (Player p in playerList.Values) SendResourceUpdate(p); } break; case InfiniminerMessage.WithdrawOre: { WithdrawOre(player); foreach (Player p in playerList.Values) SendResourceUpdate(p); } break; case InfiniminerMessage.PlayerPing: { SendPlayerPing((uint)msgBuffer.ReadInt32()); } break; case InfiniminerMessage.PlaySound: { InfiniminerSound sound = (InfiniminerSound)msgBuffer.ReadByte(); Vector3 position = msgBuffer.ReadVector3(); PlaySound(sound, position); } break; } } break; } } // Time to send a new server update? TimeSpan updateTimeSpan = DateTime.Now - lastServerListUpdate; if (updateTimeSpan.TotalMinutes > 5) PublicServerListUpdate(); // Check for players who are in the zone to deposit. DepositForPlayers(); // Is it time to do a lava calculation? If so, do it! TimeSpan timeSpan = DateTime.Now - lastFlowCalc; if (timeSpan.TotalMilliseconds > 500) { DoLavaStuff(); lastFlowCalc = DateTime.Now; } // Handle console keypresses. while (Console.KeyAvailable) { ConsoleKeyInfo keyInfo = Console.ReadKey(); if (keyInfo.Key == ConsoleKey.Enter) ConsoleProcessInput(); else if (keyInfo.Key == ConsoleKey.Backspace) { if (consoleInput.Length > 0) consoleInput = consoleInput.Substring(0, consoleInput.Length - 1); ConsoleRedraw(); } else { consoleInput += keyInfo.KeyChar; ConsoleRedraw(); } } // Is the game over? if (winningTeam != PlayerTeam.None && !restartTriggered) { BroadcastGameOver(); restartTriggered = true; restartTime = DateTime.Now.AddSeconds(10); } // Restart the server? if (restartTriggered && DateTime.Now > restartTime) { SaveLevel("autosave_" + (UInt64)DateTime.Now.ToBinary() + ".lvl"); netServer.Shutdown("The server is restarting."); return true; } // Pass control over to waiting threads. Thread.Sleep(1); } netServer.Shutdown("The server was terminated."); return false; }
// Does a random walk of noiseData, setting cells to 0 in caveData in the process. public static void PaintWithRandomWalk(ref BlockType[, ,] caveData, ref float[, ,] noiseData, int size, int paintRadius, BlockType paintValue, bool dontStopAtEdge) { int x = randGen.Next(0, size); int y = randGen.Next(0, size); int z = randGen.Next(0, size); if (z < size / 50) { z = 0; } int count = 0; while (dontStopAtEdge == false || count < size) { float oldNoise = noiseData[x, y, z]; PaintAtPoint(ref caveData, x, y, z, size, paintRadius + 1, paintValue); int dx = randGen.Next(0, paintRadius * 2 + 1) - paintRadius; int dy = randGen.Next(0, paintRadius * 2 + 1) - paintRadius; int dz = randGen.Next(0, paintRadius * 2 + 1) - paintRadius; x += dx; y += dy; z += dz; if (x < 0 || y < 0 || x >= size || y >= size || z >= size) { if (dontStopAtEdge) { count += 1; if (x < 0) { x = 0; } if (y < 0) { y = 0; } if (z < 0) { z = 0; } if (x >= size) { x = size - 1; } if (y >= size) { y = size - 1; } if (z >= size) { z = size - 1; } } else { break; } } if (z < 0) { z = 0; } float newNoise = noiseData[x, y, z]; // If we're jumping to a higher value on the noise gradient, move twice as far. if (newNoise > oldNoise) { PaintAtPoint(ref caveData, x, y, z, size, paintRadius + 1, paintValue); x += dx; y += dy; z += dz; if (x < 0 || y < 0 || x >= size || y >= size || z >= size) { if (dontStopAtEdge) { count += 1; if (x < 0) { x = 0; } if (y < 0) { y = 0; } if (z < 0) { z = 0; } if (x >= size) { x = size - 1; } if (y >= size) { y = size - 1; } if (z >= size) { z = size - 1; } } else { break; } } if (z < 0) { z = 0; } } } }
public int newMap() { physicsEnabled = false; Thread.Sleep(2); // Create our block world, translating the coordinates out of the cave generator (where Z points down) BlockType[, ,] worldData = CaveGenerator.GenerateCaveSystem(MAPSIZE, includeLava, oreFactor, includeWater); blockList = new BlockType[MAPSIZE, MAPSIZE, MAPSIZE]; blockListContent = new Int32[MAPSIZE, MAPSIZE, MAPSIZE,10]; blockCreatorTeam = new PlayerTeam[MAPSIZE, MAPSIZE, MAPSIZE]; for (ushort i = 0; i < MAPSIZE; i++) for (ushort j = 0; j < MAPSIZE; j++) for (ushort k = 0; k < MAPSIZE; k++) { flowSleep[i, j, k] = false; blockList[i, (ushort)(MAPSIZE - 1 - k), j] = worldData[i, j, k]; //if (blockList[i, (ushort)(MAPSIZE - 1 - k), j] == BlockType.Dirt) //{ // blockList[i, (ushort)(MAPSIZE - 1 - k), j] = BlockType.Sand;//covers map with block //} blockListContent[i,(ushort)(MAPSIZE - 1 - k), j, 0] = 0;//content data for blocks, such as pumps blockListContent[i,(ushort)(MAPSIZE - 1 - k), j, 1] = 0; blockListContent[i,(ushort)(MAPSIZE - 1 - k), j, 2] = 0; blockListContent[i,(ushort)(MAPSIZE - 1 - k), j, 3] = 0; blockCreatorTeam[i, j, k] = PlayerTeam.None; if (i < 1 || j < 1 || k < 1 || i > MAPSIZE - 2 || j > MAPSIZE - 2 || k > MAPSIZE - 2) { blockList[i, (ushort)(MAPSIZE - 1 - k), j] = BlockType.None; } } for (int i = 0; i < MAPSIZE * 2; i++) { DoStuff(); } physicsEnabled = true; return 1; }
public BlockEngine(InfiniminerGame gameInstance) { this.gameInstance = gameInstance; // Initialize the block list. downloadList = new BlockType[MAPSIZE, MAPSIZE, MAPSIZE]; blockList = new BlockType[MAPSIZE, MAPSIZE, MAPSIZE]; for (ushort i = 0; i < MAPSIZE; i++) for (ushort j = 0; j < MAPSIZE; j++) for (ushort k = 0; k < MAPSIZE; k++) { downloadList[i, j, k] = BlockType.None; blockList[i, j, k] = BlockType.None; } // Initialize the face lists. faceMap = new Dictionary<uint,bool>[(byte)BlockTexture.MAXIMUM, NUMREGIONS]; for (BlockTexture blockTexture = BlockTexture.None; blockTexture < BlockTexture.MAXIMUM; blockTexture++) for (int r=0; r<NUMREGIONS; r++) faceMap[(byte)blockTexture, r] = new Dictionary<uint, bool>(); // Initialize the texture map. blockTextureMap = new BlockTexture[(byte)BlockType.MAXIMUM, 6]; for (BlockType blockType = BlockType.None; blockType < BlockType.MAXIMUM; blockType++) for (BlockFaceDirection faceDir = BlockFaceDirection.XIncreasing; faceDir < BlockFaceDirection.MAXIMUM; faceDir++) blockTextureMap[(byte)blockType,(byte)faceDir] = BlockInformation.GetTexture(blockType, faceDir); // Load the textures we'll use. blockTextures = new IMTexture[(byte)BlockTexture.MAXIMUM]; blockTextures[(byte)BlockTexture.None] = new IMTexture(null); blockTextures[(byte)BlockTexture.Dirt] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_dirt")); blockTextures[(byte)BlockTexture.Mud] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_mud")); blockTextures[(byte)BlockTexture.Grass] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_grass")); blockTextures[(byte)BlockTexture.GrassSide] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_grass_side")); blockTextures[(byte)BlockTexture.Sand] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_sand")); blockTextures[(byte)BlockTexture.Rock] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_rock")); blockTextures[(byte)BlockTexture.Ore] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_ore")); blockTextures[(byte)BlockTexture.Gold] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_silver")); blockTextures[(byte)BlockTexture.Diamond] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_diamond")); blockTextures[(byte)BlockTexture.HomeRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_home_red")); blockTextures[(byte)BlockTexture.HomeBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_home_blue")); blockTextures[(byte)BlockTexture.SolidRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_red")); blockTextures[(byte)BlockTexture.SolidBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_blue")); blockTextures[(byte)BlockTexture.SolidRed2] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_red2"));//placeholder texture blockTextures[(byte)BlockTexture.SolidBlue2] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_blue2"));//placeholder texture blockTextures[(byte)BlockTexture.Ladder] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_ladder")); blockTextures[(byte)BlockTexture.LadderTop] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_ladder_top")); blockTextures[(byte)BlockTexture.Spikes] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_spikes")); blockTextures[(byte)BlockTexture.Jump] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_jump")); blockTextures[(byte)BlockTexture.JumpTop] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_jump_top")); blockTextures[(byte)BlockTexture.Explosive] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_explosive")); blockTextures[(byte)BlockTexture.Metal] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_metal")); blockTextures[(byte)BlockTexture.DirtSign] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_dirt_sign")); blockTextures[(byte)BlockTexture.BankTopRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_top_red")); blockTextures[(byte)BlockTexture.BankLeftRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_left_red")); blockTextures[(byte)BlockTexture.BankFrontRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_front_red")); blockTextures[(byte)BlockTexture.BankRightRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_right_red")); blockTextures[(byte)BlockTexture.BankBackRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_back_red")); blockTextures[(byte)BlockTexture.BankTopBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_top_blue")); blockTextures[(byte)BlockTexture.BankLeftBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_left_blue")); blockTextures[(byte)BlockTexture.BankFrontBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_front_blue")); blockTextures[(byte)BlockTexture.BankRightBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_right_blue")); blockTextures[(byte)BlockTexture.BankBackBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_back_blue")); blockTextures[(byte)BlockTexture.Forge] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_forge")); blockTextures[(byte)BlockTexture.ForgeSide] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_forge_side")); blockTextures[(byte)BlockTexture.ArtCaseR] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_artcase_red")); blockTextures[(byte)BlockTexture.ArtCaseB] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_artcase_blue")); //base block blockTextures[(byte)BlockTexture.BaseTopRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_top_red")); blockTextures[(byte)BlockTexture.BaseLeftRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_left_red")); blockTextures[(byte)BlockTexture.BaseFrontRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_front_red")); blockTextures[(byte)BlockTexture.BaseRightRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_right_red")); blockTextures[(byte)BlockTexture.BaseBackRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_back_red")); blockTextures[(byte)BlockTexture.BaseTopBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_top_blue")); blockTextures[(byte)BlockTexture.BaseLeftBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_left_blue")); blockTextures[(byte)BlockTexture.BaseFrontBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_front_blue")); blockTextures[(byte)BlockTexture.BaseRightBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_right_blue")); blockTextures[(byte)BlockTexture.BaseBackBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_bank_back_blue")); //base block blockTextures[(byte)BlockTexture.TeleSideA] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_teleporter_a")); blockTextures[(byte)BlockTexture.TeleSideB] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_teleporter_b")); blockTextures[(byte)BlockTexture.TeleTop] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_teleporter_top")); blockTextures[(byte)BlockTexture.TeleBottom] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_teleporter_bottom")); blockTextures[(byte)BlockTexture.Lava] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_lava")); blockTextures[(byte)BlockTexture.Water] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_trans_water")); blockTextures[(byte)BlockTexture.Road] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_road")); blockTextures[(byte)BlockTexture.RoadTop] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_road_top")); blockTextures[(byte)BlockTexture.RoadBottom] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_road_bottom")); blockTextures[(byte)BlockTexture.BeaconRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_beacon_top_red")); blockTextures[(byte)BlockTexture.BeaconBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_beacon_top_blue")); blockTextures[(byte)BlockTexture.TransRed] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_trans_red")); blockTextures[(byte)BlockTexture.TransBlue] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_trans_blue")); blockTextures[(byte)BlockTexture.GlassR] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_glass_red")); blockTextures[(byte)BlockTexture.GlassB] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_glass_blue")); blockTextures[(byte)BlockTexture.ForceR] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_force_red")); blockTextures[(byte)BlockTexture.ForceB] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_force_blue")); blockTextures[(byte)BlockTexture.Generator] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_generator")); blockTextures[(byte)BlockTexture.Controller] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_controller")); blockTextures[(byte)BlockTexture.Pipe] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_pipe")); blockTextures[(byte)BlockTexture.Pump] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_pump")); blockTextures[(byte)BlockTexture.Barrel] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_barrel_side")); blockTextures[(byte)BlockTexture.BarrelTop] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_barrel_top")); blockTextures[(byte)BlockTexture.Spring] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_spring")); blockTextures[(byte)BlockTexture.MagmaVent] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_magmavent")); blockTextures[(byte)BlockTexture.MagmaBurst] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_magma")); blockTextures[(byte)BlockTexture.Fire] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_fire")); blockTextures[(byte)BlockTexture.StealthBlockR] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_dirt_trans")); blockTextures[(byte)BlockTexture.StealthBlockB] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_dirt_trans")); blockTextures[(byte)BlockTexture.Trap] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_dirt")); blockTextures[(byte)BlockTexture.TrapB] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_dirt")); blockTextures[(byte)BlockTexture.TrapR] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_dirt")); blockTextures[(byte)BlockTexture.TrapVis] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_trapVis")); blockTextures[(byte)BlockTexture.Magma] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_magma")); blockTextures[(byte)BlockTexture.Lever] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_mechanism")); blockTextures[(byte)BlockTexture.Plate] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_metal")); blockTextures[(byte)BlockTexture.Hinge] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_hinge")); blockTextures[(byte)BlockTexture.Construction] = new IMTexture(gameInstance.Content.Load<Texture2D>("blocks/tex_block_construction")); // Load our effects. basicEffect = gameInstance.Content.Load<Effect>("effect_basic"); // Build vertex lists. vertexBuffers = new DynamicVertexBuffer[(byte)BlockTexture.MAXIMUM, NUMREGIONS]; vertexListDirty = new bool[(byte)BlockTexture.MAXIMUM, NUMREGIONS]; Light = new float[MAPSIZE, MAPSIZE, MAPSIZE]; for(int x = 0;x < MAPSIZE-1;x++) for (int y = 0; y < MAPSIZE - 1; y++) for (int z = 0; z < MAPSIZE - 1; z++) { Light[x, y, z] = 0.2f; } for (int i = 0; i < (byte)BlockTexture.MAXIMUM; i++) for (int j = 0; j < NUMREGIONS; j++) vertexListDirty[i, j] = true; // Initialize any graphics stuff. vertexDeclaration = new VertexDeclaration(gameInstance.GraphicsDevice, VertexPositionTextureShade.VertexElements); // Initialize the bloom engine. if (gameInstance.RenderPretty) { bloomPosteffect = new BloomComponent(); bloomPosteffect.Load(gameInstance.GraphicsDevice, gameInstance.Content); } else bloomPosteffect = null; }
public BlockEngine(InfiniminerGame gameInstance) { this.gameInstance = gameInstance; // Initialize the block list. downloadList = new BlockType[MAPSIZE, MAPSIZE, MAPSIZE]; blockList = new BlockType[MAPSIZE, MAPSIZE, MAPSIZE]; for (ushort i = 0; i < MAPSIZE; i++) { for (ushort j = 0; j < MAPSIZE; j++) { for (ushort k = 0; k < MAPSIZE; k++) { downloadList[i, j, k] = BlockType.None; blockList[i, j, k] = BlockType.None; } } } // Initialize the face lists. faceMap = new Dictionary <uint, bool> [(byte)BlockTexture.MAXIMUM, NUMREGIONS]; for (BlockTexture blockTexture = BlockTexture.None; blockTexture < BlockTexture.MAXIMUM; blockTexture++) { for (int r = 0; r < NUMREGIONS; r++) { faceMap[(byte)blockTexture, r] = new Dictionary <uint, bool>(); } } // Initialize the texture map. blockTextureMap = new BlockTexture[(byte)BlockType.MAXIMUM, 6]; for (BlockType blockType = BlockType.None; blockType < BlockType.MAXIMUM; blockType++) { for (BlockFaceDirection faceDir = BlockFaceDirection.XIncreasing; faceDir < BlockFaceDirection.MAXIMUM; faceDir++) { blockTextureMap[(byte)blockType, (byte)faceDir] = BlockInformation.GetTexture(blockType, faceDir); } } // Load the textures we'll use. blockTextures = new IMTexture[(byte)BlockTexture.MAXIMUM]; blockTextures[(byte)BlockTexture.None] = new IMTexture(null); blockTextures[(byte)BlockTexture.Dirt] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_dirt")); blockTextures[(byte)BlockTexture.Rock] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_rock")); blockTextures[(byte)BlockTexture.Ore] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_ore")); blockTextures[(byte)BlockTexture.Gold] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_silver")); blockTextures[(byte)BlockTexture.Diamond] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_diamond")); blockTextures[(byte)BlockTexture.HomeRed] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_home_red")); blockTextures[(byte)BlockTexture.HomeBlue] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_home_blue")); blockTextures[(byte)BlockTexture.SolidRed] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_red")); blockTextures[(byte)BlockTexture.SolidBlue] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_blue")); blockTextures[(byte)BlockTexture.Ladder] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_ladder")); blockTextures[(byte)BlockTexture.LadderTop] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_ladder_top")); blockTextures[(byte)BlockTexture.Spikes] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_spikes")); blockTextures[(byte)BlockTexture.Jump] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_jump")); blockTextures[(byte)BlockTexture.JumpTop] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_jump_top")); blockTextures[(byte)BlockTexture.Explosive] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_explosive")); blockTextures[(byte)BlockTexture.Metal] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_metal")); blockTextures[(byte)BlockTexture.DirtSign] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_dirt_sign")); blockTextures[(byte)BlockTexture.BankTopRed] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_bank_top_red")); blockTextures[(byte)BlockTexture.BankLeftRed] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_bank_left_red")); blockTextures[(byte)BlockTexture.BankFrontRed] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_bank_front_red")); blockTextures[(byte)BlockTexture.BankRightRed] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_bank_right_red")); blockTextures[(byte)BlockTexture.BankBackRed] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_bank_back_red")); blockTextures[(byte)BlockTexture.BankTopBlue] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_bank_top_blue")); blockTextures[(byte)BlockTexture.BankLeftBlue] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_bank_left_blue")); blockTextures[(byte)BlockTexture.BankFrontBlue] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_bank_front_blue")); blockTextures[(byte)BlockTexture.BankRightBlue] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_bank_right_blue")); blockTextures[(byte)BlockTexture.BankBackBlue] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_bank_back_blue")); blockTextures[(byte)BlockTexture.TeleSideA] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_teleporter_a")); blockTextures[(byte)BlockTexture.TeleSideB] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_teleporter_b")); blockTextures[(byte)BlockTexture.TeleTop] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_teleporter_top")); blockTextures[(byte)BlockTexture.TeleBottom] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_teleporter_bottom")); blockTextures[(byte)BlockTexture.Lava] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_lava")); blockTextures[(byte)BlockTexture.Road] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_road")); blockTextures[(byte)BlockTexture.RoadTop] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_road_top")); blockTextures[(byte)BlockTexture.RoadBottom] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_road_bottom")); blockTextures[(byte)BlockTexture.BeaconRed] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_beacon_top_red")); blockTextures[(byte)BlockTexture.BeaconBlue] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_beacon_top_blue")); blockTextures[(byte)BlockTexture.TransRed] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_trans_red")); blockTextures[(byte)BlockTexture.TransBlue] = new IMTexture(gameInstance.Content.Load <Texture2D>("blocks/tex_block_trans_blue")); // Load our effects. basicEffect = gameInstance.Content.Load <Effect>("effect_basic"); // Build vertex lists. vertexBuffers = new DynamicVertexBuffer[(byte)BlockTexture.MAXIMUM, NUMREGIONS]; vertexListDirty = new bool[(byte)BlockTexture.MAXIMUM, NUMREGIONS]; for (int i = 0; i < (byte)BlockTexture.MAXIMUM; i++) { for (int j = 0; j < NUMREGIONS; j++) { vertexListDirty[i, j] = true; } } // Initialize any graphics stuff. vertexDeclaration = new VertexDeclaration(VertexPositionTexture.VertexDeclaration.GetVertexElements()); // Initialize the bloom engine. if (gameInstance.RenderPretty) { bloomPosteffect = new BloomComponent(); bloomPosteffect.Load(gameInstance.GraphicsDevice, gameInstance.Content); } else { bloomPosteffect = null; } }
public bool GenWorldWithTerrain() { if (File.Exists (Application.dataPath + "/Resources/" + worldName + "/" + worldName + "_terrain.asset")) { TerrainData terrain = Resources.Load (worldName + "/" + worldName + "_terrain") as TerrainData; worldX = (int)terrain.size.x; //worldY = (int)terrain.size.y; worldY = 2*chunkSize; worldZ = (int)terrain.size.z; data = new BlockType[worldX, worldY, worldZ]; for (int x = 0; x < worldX; x++) { for (int z = 0; z < worldZ; z++) { int h = (int)terrain.GetHeight (x, z); data [x, 0, z] = BlockType.Stone_Black; for (int y = 1; y < worldY; y++) { if (y <= h) data [x, y, z] = BlockType.Stone; else data [x, y, z] = BlockType.Air; } } } return true; } else { print ("Could not find Terrain object with name: \"" + worldName + "_terrain.asset\"."); return false; } }
public void GenWorld() { worldX = 256; worldY = 64; worldZ = 256; data = new BlockType[worldX, worldY, worldZ]; for (int x = 0; x < worldX; x++) { for (int z = 0; z < worldZ; z++) { for (int y = 0; y < worldY; y++) { if (y == 0) { data[x,y,z] = BlockType.Stone_Black; } else { data[x,y,z] = BlockType.Air; } } } } }
public bool Start() { //Setup the variable toggles varBindingsInitialize(); int tmpMaxPlayers = 16; // Read in from the config file. DatafileWriter dataFile = new DatafileWriter("server.config.txt"); if (dataFile.Data.ContainsKey("winningcash")) winningCashAmount = uint.Parse(dataFile.Data["winningcash"], System.Globalization.CultureInfo.InvariantCulture); if (dataFile.Data.ContainsKey("includelava")) includeLava = bool.Parse(dataFile.Data["includelava"]); if (dataFile.Data.ContainsKey("includewater")) includeLava = bool.Parse(dataFile.Data["includewater"]); if (dataFile.Data.ContainsKey("orefactor")) oreFactor = uint.Parse(dataFile.Data["orefactor"], System.Globalization.CultureInfo.InvariantCulture); if (dataFile.Data.ContainsKey("maxplayers")) tmpMaxPlayers = (int)Math.Min(32, uint.Parse(dataFile.Data["maxplayers"], System.Globalization.CultureInfo.InvariantCulture)); if (dataFile.Data.ContainsKey("public")) varSet("public", bool.Parse(dataFile.Data["public"]), true); if (dataFile.Data.ContainsKey("servername")) varSet("name", dataFile.Data["servername"], true); if (dataFile.Data.ContainsKey("sandbox")) varSet("sandbox", bool.Parse(dataFile.Data["sandbox"]), true); if (dataFile.Data.ContainsKey("notnt")) varSet("tnt", !bool.Parse(dataFile.Data["notnt"]), true); if (dataFile.Data.ContainsKey("sphericaltnt")) varSet("stnt", bool.Parse(dataFile.Data["sphericaltnt"]), true); if (dataFile.Data.ContainsKey("insane")) varSet("insane", bool.Parse(dataFile.Data["insane"]), true); if (dataFile.Data.ContainsKey("roadabsorbs")) varSet("roadabsorbs", bool.Parse(dataFile.Data["roadabsorbs"]), true); if (dataFile.Data.ContainsKey("minelava")) varSet("minelava", bool.Parse(dataFile.Data["minelava"]), true); if (dataFile.Data.ContainsKey("levelname")) levelToLoad = dataFile.Data["levelname"]; if (dataFile.Data.ContainsKey("greeter")) varSet("greeter", dataFile.Data["greeter"],true); bool autoannounce = true; if (dataFile.Data.ContainsKey("autoannounce")) autoannounce = bool.Parse(dataFile.Data["autoannounce"]); // Load the ban-list. banList = LoadBanList(); // Load the admin-list admins = LoadAdminList(); if (tmpMaxPlayers>=0) varSet("maxplayers", tmpMaxPlayers, true); // Initialize the server. NetConfiguration netConfig = new NetConfiguration("InfiniminerPlus"); netConfig.MaxConnections = (int)varGetI("maxplayers"); netConfig.Port = 5565; netServer = new InfiniminerNetServer(netConfig); netServer.SetMessageTypeEnabled(NetMessageType.ConnectionApproval, true); //netServer.SimulatedMinimumLatency = 0.1f; //netServer.SimulatedLatencyVariance = 0.05f; //netServer.SimulatedLoss = 0.1f; //netServer.SimulatedDuplicates = 0.05f; //netServer.Configuration.SendBufferSize = 2048000; //netServer.Start();//starts too early // Initialize variables we'll use. NetBuffer msgBuffer = netServer.CreateBuffer(); NetMessageType msgType; NetConnection msgSender; // Store the last time that we did a flow calculation. DateTime lastFlowCalc = DateTime.Now; //Check if we should autoload a level if (dataFile.Data.ContainsKey("autoload") && bool.Parse(dataFile.Data["autoload"])) { blockList = new BlockType[MAPSIZE, MAPSIZE, MAPSIZE]; blockCreatorTeam = new PlayerTeam[MAPSIZE, MAPSIZE, MAPSIZE]; LoadLevel(levelToLoad); lavaBlockCount = 0; waterBlockCount = 0; for (ushort i = 0; i < MAPSIZE; i++) for (ushort j = 0; j < MAPSIZE; j++) for (ushort k = 0; k < MAPSIZE; k++) { if (blockList[i, j, k] == BlockType.Lava) { lavaBlockCount += 1; } else if (blockList[i, j, k] == BlockType.Water) { waterBlockCount += 1; } } ConsoleWrite(waterBlockCount + " water blocks, " + lavaBlockCount + " lava blocks."); } else { // Calculate initial lava flows. ConsoleWrite("CALCULATING INITIAL LIQUID BLOCKS"); newMap(); lavaBlockCount = 0; waterBlockCount = 0; for (ushort i = 0; i < MAPSIZE; i++) for (ushort j = 0; j < MAPSIZE; j++) for (ushort k = 0; k < MAPSIZE; k++) { if (blockList[i, j, k] == BlockType.Lava) { lavaBlockCount += 1; } else if (blockList[i, j, k] == BlockType.Water) { waterBlockCount += 1; } } ConsoleWrite(waterBlockCount + " water blocks, " + lavaBlockCount + " lava blocks."); } //Caculate the shape of spherical tnt explosions CalculateExplosionPattern(); // Send the initial server list update. if (autoannounce) PublicServerListUpdate(true); lastMapBackup = DateTime.Now; DateTime lastFPScheck = DateTime.Now; double frameRate = 0; // Main server loop! netServer.Start(); ConsoleWrite("SERVER READY"); if (!physics.IsAlive) { ConsoleWrite("Physics thread is limp."); } while (keepRunning) { if (!physics.IsAlive) { ConsoleWrite("Physics thread died."); // physics.Abort(); // physics.Join(); //physics.Start(); } frameCount = frameCount + 1; if (lastFPScheck <= DateTime.Now - TimeSpan.FromMilliseconds(1000)) { lastFPScheck = DateTime.Now; frameRate = frameCount;// / gameTime.ElapsedTotalTime.TotalSeconds; if (sleeping == false && frameCount < 20) { ConsoleWrite("Heavy load: " + frameCount + " FPS"); } frameCount = 0; } // Process any messages that are here. while (netServer.ReadMessage(msgBuffer, out msgType, out msgSender)) { try { switch (msgType) { case NetMessageType.ConnectionApproval: { Player newPlayer = new Player(msgSender, null); newPlayer.Handle = Defines.Sanitize(msgBuffer.ReadString()).Trim(); if (newPlayer.Handle.Length == 0) { newPlayer.Handle = "Player"; } string clientVersion = msgBuffer.ReadString(); if (clientVersion != Defines.INFINIMINER_VERSION) { msgSender.Disapprove("VER;" + Defines.INFINIMINER_VERSION); } else if (banList.Contains(newPlayer.IP)) { msgSender.Disapprove("BAN;"); }/* else if (playerList.Count == maxPlayers) { msgSender.Disapprove("FULL;"); }*/ else { if (admins.ContainsKey(newPlayer.IP)) newPlayer.admin = admins[newPlayer.IP]; playerList[msgSender] = newPlayer; //Check if we should compress the map for the client try { bool compression = msgBuffer.ReadBoolean(); if (compression) playerList[msgSender].compression = true; } catch { } toGreet.Add(msgSender); this.netServer.SanityCheck(msgSender); msgSender.Approve(); PublicServerListUpdate(true); } } break; case NetMessageType.StatusChanged: { if (!this.playerList.ContainsKey(msgSender)) { break; } Player player = playerList[msgSender]; if (msgSender.Status == NetConnectionStatus.Connected) { if (sleeping == true) { sleeping = false; physicsEnabled = true; } ConsoleWrite("CONNECT: " + playerList[msgSender].Handle + " ( " + playerList[msgSender].IP + " )"); SendCurrentMap(msgSender); SendPlayerJoined(player); PublicServerListUpdate(); } else if (msgSender.Status == NetConnectionStatus.Disconnected) { ConsoleWrite("DISCONNECT: " + playerList[msgSender].Handle); SendPlayerLeft(player, player.Kicked ? "WAS KICKED FROM THE GAME!" : "HAS ABANDONED THEIR DUTIES!"); if (playerList.ContainsKey(msgSender)) playerList.Remove(msgSender); sleeping = true; foreach (Player p in playerList.Values) { sleeping = false; } if (sleeping == true) { ConsoleWrite("HIBERNATING"); physicsEnabled = false; } PublicServerListUpdate(); } } break; case NetMessageType.Data: { if (!this.playerList.ContainsKey(msgSender)) { break; } Player player = playerList[msgSender]; InfiniminerMessage dataType = (InfiniminerMessage)msgBuffer.ReadByte(); switch (dataType) { case InfiniminerMessage.ChatMessage: { // Read the data from the packet. ChatMessageType chatType = (ChatMessageType)msgBuffer.ReadByte(); string chatString = Defines.Sanitize(msgBuffer.ReadString()); if (!ProcessCommand(chatString,GetAdmin(playerList[msgSender].IP),playerList[msgSender])) { ConsoleWrite("CHAT: (" + player.Handle + ") " + chatString); // Append identifier information. if (chatType == ChatMessageType.SayAll) chatString = player.Handle + " (ALL): " + chatString; else chatString = player.Handle + " (TEAM): " + chatString; // Construct the message packet. NetBuffer chatPacket = netServer.CreateBuffer(); chatPacket.Write((byte)InfiniminerMessage.ChatMessage); chatPacket.Write((byte)((player.Team == PlayerTeam.Red) ? ChatMessageType.SayRedTeam : ChatMessageType.SayBlueTeam)); chatPacket.Write(chatString); // Send the packet to people who should recieve it. foreach (Player p in playerList.Values) { if (chatType == ChatMessageType.SayAll || chatType == ChatMessageType.SayBlueTeam && p.Team == PlayerTeam.Blue || chatType == ChatMessageType.SayRedTeam && p.Team == PlayerTeam.Red) if (p.NetConn.Status == NetConnectionStatus.Connected) netServer.SendMessage(chatPacket, p.NetConn, NetChannel.ReliableInOrder3); } } } break; case InfiniminerMessage.UseTool: { Vector3 playerPosition = msgBuffer.ReadVector3(); Vector3 playerHeading = msgBuffer.ReadVector3(); PlayerTools playerTool = (PlayerTools)msgBuffer.ReadByte(); BlockType blockType = (BlockType)msgBuffer.ReadByte(); switch (playerTool) { case PlayerTools.Pickaxe: UsePickaxe(player, playerPosition, playerHeading); break; case PlayerTools.ConstructionGun: UseConstructionGun(player, playerPosition, playerHeading, blockType); break; case PlayerTools.DeconstructionGun: UseDeconstructionGun(player, playerPosition, playerHeading); break; case PlayerTools.ProspectingRadar: UseSignPainter(player, playerPosition, playerHeading); break; case PlayerTools.Detonator: UseDetonator(player); break; case PlayerTools.SpawnItem: SpawnItem(player, playerPosition, playerHeading); break; } } break; case InfiniminerMessage.SelectClass: { PlayerClass playerClass = (PlayerClass)msgBuffer.ReadByte(); player.Alive = false; ConsoleWrite("SELECT_CLASS: " + player.Handle + ", " + playerClass.ToString()); switch (playerClass) { case PlayerClass.Engineer://strong arm/throws blocks player.OreMax = 350; player.WeightMax = 4; player.HealthMax = 400; player.Health = player.HealthMax; break; case PlayerClass.Miner: player.OreMax = 200; player.WeightMax = 8; player.HealthMax = 400; player.Health = player.HealthMax; break; case PlayerClass.Prospector: player.OreMax = 200; player.WeightMax = 4; player.HealthMax = 400; player.Health = player.HealthMax; break; case PlayerClass.Sapper: player.OreMax = 200; player.WeightMax = 4; player.HealthMax = 400; player.Health = player.HealthMax; break; } SendResourceUpdate(player); } break; case InfiniminerMessage.PlayerSetTeam: { PlayerTeam playerTeam = (PlayerTeam)msgBuffer.ReadByte(); ConsoleWrite("SELECT_TEAM: " + player.Handle + ", " + playerTeam.ToString()); player.Team = playerTeam; player.Health = 0; player.Alive = false; SendResourceUpdate(player); SendPlayerSetTeam(player); } break; case InfiniminerMessage.PlayerDead: { ConsoleWrite("PLAYER_DEAD: " + player.Handle); player.Ore = 0; player.Cash = 0; player.Weight = 0; player.Health = 0; player.Alive = false; SendResourceUpdate(player); SendPlayerDead(player); string deathMessage = msgBuffer.ReadString(); if (deathMessage != "") { msgBuffer = netServer.CreateBuffer(); msgBuffer.Write((byte)InfiniminerMessage.ChatMessage); msgBuffer.Write((byte)(player.Team == PlayerTeam.Red ? ChatMessageType.SayRedTeam : ChatMessageType.SayBlueTeam)); msgBuffer.Write(player.Handle + " " + deathMessage); foreach (NetConnection netConn in playerList.Keys) if (netConn.Status == NetConnectionStatus.Connected) netServer.SendMessage(msgBuffer, netConn, NetChannel.ReliableInOrder3); } SendPlayerRespawn(player);//allow this player to instantly respawn } break; case InfiniminerMessage.PlayerAlive: { if (toGreet.Contains(msgSender)) { string greeting = varGetS("greeter"); greeting = greeting.Replace("[name]", playerList[msgSender].Handle); if (greeting != "") { NetBuffer greetBuffer = netServer.CreateBuffer(); greetBuffer.Write((byte)InfiniminerMessage.ChatMessage); greetBuffer.Write((byte)ChatMessageType.SayAll); greetBuffer.Write(Defines.Sanitize(greeting)); netServer.SendMessage(greetBuffer, msgSender, NetChannel.ReliableInOrder3); } toGreet.Remove(msgSender); } ConsoleWrite("PLAYER_ALIVE: " + player.Handle); player.Ore = 0; player.Cash = 0; player.Weight = 0; player.Health = player.HealthMax; player.Alive = true; SendResourceUpdate(player); SendPlayerAlive(player); } break; case InfiniminerMessage.PlayerRespawn: { SendPlayerRespawn(player);//new respawn } break; case InfiniminerMessage.PlayerUpdate: { player.Position = Auth_Position(msgBuffer.ReadVector3(),player); player.Heading = Auth_Heading(msgBuffer.ReadVector3()); player.Tool = (PlayerTools)msgBuffer.ReadByte(); player.UsingTool = msgBuffer.ReadBoolean(); SendPlayerUpdate(player); } break; case InfiniminerMessage.PlayerUpdate1://minus position { player.Heading = Auth_Heading(msgBuffer.ReadVector3()); player.Tool = (PlayerTools)msgBuffer.ReadByte(); player.UsingTool = msgBuffer.ReadBoolean(); SendPlayerUpdate(player); } break; case InfiniminerMessage.PlayerUpdate2://minus position and heading { player.Tool = (PlayerTools)msgBuffer.ReadByte(); player.UsingTool = msgBuffer.ReadBoolean(); SendPlayerUpdate(player); } break; case InfiniminerMessage.PlayerHurt://client speaks of fall damage { uint newhp = msgBuffer.ReadUInt32(); if (newhp < player.Health) { player.Health = newhp; if (player.Health < 1) { player.Ore = 0;//should be calling death function for player player.Cash = 0; player.Weight = 0; player.Health = 0; player.Alive = false; SendResourceUpdate(player); SendPlayerDead(player); } } } break; case InfiniminerMessage.PlayerPosition://server not interested in clients complaints about position { } break; case InfiniminerMessage.PlayerInteract://client speaks of mashing on block { player.Position = Auth_Position(msgBuffer.ReadVector3(), player); uint btn = msgBuffer.ReadUInt32(); uint btnx = msgBuffer.ReadUInt32(); uint btny = msgBuffer.ReadUInt32(); uint btnz = msgBuffer.ReadUInt32(); if (blockList[btnx, btny, btnz] == BlockType.Pump || blockList[btnx, btny, btnz] == BlockType.Pipe || blockList[btnx, btny, btnz] == BlockType.Generator || blockList[btnx, btny, btnz] == BlockType.Compressor) { if (Get3DDistance((int)btnx, (int)btny, (int)btnz, (int)player.Position.X, (int)player.Position.Y, (int)player.Position.Z) < 4) { PlayerInteract(player,btn, btnx, btny, btnz); } } } break; case InfiniminerMessage.DepositOre: { DepositOre(player); foreach (Player p in playerList.Values) SendResourceUpdate(p); } break; case InfiniminerMessage.WithdrawOre: { WithdrawOre(player); foreach (Player p in playerList.Values) SendResourceUpdate(p); } break; case InfiniminerMessage.PlayerPing: { SendPlayerPing((uint)msgBuffer.ReadInt32()); } break; case InfiniminerMessage.PlaySound: { InfiniminerSound sound = (InfiniminerSound)msgBuffer.ReadByte(); Vector3 position = msgBuffer.ReadVector3(); PlaySound(sound, position); } break; case InfiniminerMessage.GetItem: { //verify players position before get player.Position = Auth_Position(msgBuffer.ReadVector3(), player); GetItem(player,msgBuffer.ReadString()); } break; } } break; } } catch { } } //Time to backup map? TimeSpan mapUpdateTimeSpan = DateTime.Now - lastMapBackup; if (mapUpdateTimeSpan.TotalMinutes > 5) { lastMapBackup = DateTime.Now; SaveLevel("autoBK.lvl"); } // Time to send a new server update? PublicServerListUpdate(); //It checks for public server / time span //Time to terminate finished map sending threads? TerminateFinishedThreads(); // Check for players who are in the zone to deposit. DepositForPlayers(); // Is it time to do a lava calculation? If so, do it! TimeSpan timeSpan = DateTime.Now - lastFlowCalc; if (timeSpan.TotalMilliseconds > 250)//needs separate timer for each substance { lastFlowCalc = DateTime.Now; //secondflow += 1; //if (secondflow > 2)//every 2nd flow, remove the vacuum that prevent re-spread //{ // EraseVacuum(); // secondflow = 0; //} foreach (Player p in playerList.Values)//regeneration { if (p.Alive) if (p.Health >= p.HealthMax) { p.Health = p.HealthMax; } else { p.Health = p.Health + 1; SendResourceUpdate(p); } } //physics = new Thread(new ThreadStart(this.DoStuff)); //DoStuff(); } // Handle console keypresses. while (Console.KeyAvailable) { ConsoleKeyInfo keyInfo = Console.ReadKey(); if (keyInfo.Key == ConsoleKey.Enter) ConsoleProcessInput(); else if (keyInfo.Key == ConsoleKey.Backspace) { if (consoleInput.Length > 0) consoleInput = consoleInput.Substring(0, consoleInput.Length - 1); ConsoleRedraw(); } else { consoleInput += keyInfo.KeyChar; ConsoleRedraw(); } } // Is the game over? if (winningTeam != PlayerTeam.None && !restartTriggered) { BroadcastGameOver(); restartTriggered = true; restartTime = DateTime.Now.AddSeconds(10); } // Restart the server? if (restartTriggered && DateTime.Now > restartTime) { SaveLevel("autosave_" + (UInt64)DateTime.Now.ToBinary() + ".lvl"); netServer.Shutdown("The server is restarting."); Thread.Sleep(100); physics.Abort(); return true;//terminates server thread completely } // Pass control over to waiting threads. if(sleeping == true) { Thread.Sleep(50); } else { Thread.Sleep(1); } } MessageAll("Server going down NOW!"); netServer.Shutdown("The server was terminated."); return false; }
public int newMap() { physicsEnabled = false; Thread.Sleep(2); // Create our block world, translating the coordinates out of the cave generator (where Z points down) BlockType[, ,] worldData = CaveGenerator.GenerateCaveSystem(MAPSIZE, includeLava, oreFactor, includeWater); blockList = new BlockType[MAPSIZE, MAPSIZE, MAPSIZE]; blockListContent = new Int32[MAPSIZE, MAPSIZE, MAPSIZE, 50]; blockListHP = new Int32[MAPSIZE, MAPSIZE, MAPSIZE]; blockCreatorTeam = new PlayerTeam[MAPSIZE, MAPSIZE, MAPSIZE]; ResearchComplete = new Int32[3, 20]; ResearchProgress = new Int32[3, 20]; artifactActive = new Int32[3, 20]; allowBlock = new bool[3, 6, (byte)BlockType.MAXIMUM]; for (int cr = 0; cr < 20; cr++)//clear artifact stores { artifactActive[0, cr] = 0; artifactActive[1, cr] = 0; artifactActive[2, cr] = 0; } for (ushort ct = 0; ct < 3; ct++) { for (ushort ca = 0; ca < 6; ca++) { for (ushort cb = 0; cb < (byte)BlockType.MAXIMUM; cb++) { allowBlock[ct, ca, cb] = false; } } } allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.SolidRed] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.ArtCaseR] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.BankRed] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.BeaconRed] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.Barrel] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.GlassR] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.Hinge] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.Jump] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.Ladder] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.Lever] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.Metal] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.Pipe] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.Pump] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.RadarRed] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.ResearchR] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.Shock] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.StealthBlockR] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.TrapR] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Engineer, (byte)BlockType.Plate] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.SolidBlue] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.ArtCaseB] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.BankBlue] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.BeaconBlue] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.Barrel] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.GlassB] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.Hinge] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.Jump] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.Ladder] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.Lever] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.Metal] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.Pipe] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.Pump] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.RadarBlue] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.ResearchB] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.Shock] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.StealthBlockB] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.TrapR] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Engineer, (byte)BlockType.Plate] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Miner, (byte)BlockType.SolidRed] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Miner, (byte)BlockType.BeaconRed] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Miner, (byte)BlockType.Hinge] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Miner, (byte)BlockType.Lever] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Miner, (byte)BlockType.Shock] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Miner, (byte)BlockType.Plate] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Miner, (byte)BlockType.SolidBlue] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Miner, (byte)BlockType.BeaconBlue] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Miner, (byte)BlockType.Hinge] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Miner, (byte)BlockType.Lever] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Miner, (byte)BlockType.Shock] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Miner, (byte)BlockType.Plate] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Prospector, (byte)BlockType.SolidRed] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Prospector, (byte)BlockType.BeaconRed] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Prospector, (byte)BlockType.Hinge] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Prospector, (byte)BlockType.Lever] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Prospector, (byte)BlockType.Shock] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Prospector, (byte)BlockType.Plate] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Prospector, (byte)BlockType.SolidBlue] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Prospector, (byte)BlockType.BeaconBlue] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Prospector, (byte)BlockType.Hinge] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Prospector, (byte)BlockType.Lever] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Prospector, (byte)BlockType.Shock] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Prospector, (byte)BlockType.Plate] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Sapper, (byte)BlockType.SolidRed] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Sapper, (byte)BlockType.BeaconRed] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Sapper, (byte)BlockType.Hinge] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Sapper, (byte)BlockType.Lever] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Sapper, (byte)BlockType.Shock] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Sapper, (byte)BlockType.Explosive] = true; allowBlock[(byte)PlayerTeam.Red, (byte)PlayerClass.Sapper, (byte)BlockType.Plate] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Sapper, (byte)BlockType.SolidBlue] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Sapper, (byte)BlockType.BeaconBlue] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Sapper, (byte)BlockType.Hinge] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Sapper, (byte)BlockType.Lever] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Sapper, (byte)BlockType.Shock] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Sapper, (byte)BlockType.Explosive] = true; allowBlock[(byte)PlayerTeam.Blue, (byte)PlayerClass.Sapper, (byte)BlockType.Plate] = true; for (ushort c = 0; c < 10; c++) { ResearchComplete[1, c] = 0; ResearchProgress[1, c] = ResearchInformation.GetCost((Research)c); ResearchComplete[2, c] = 0; ResearchProgress[2, c] = ResearchInformation.GetCost((Research)c); } for (ushort i = 0; i < MAPSIZE; i++) for (ushort j = 0; j < MAPSIZE; j++) for (ushort k = 0; k < MAPSIZE; k++) { flowSleep[i, j, k] = false; blockList[i, (ushort)(MAPSIZE - 1 - k), j] = worldData[i, j, k]; //if (blockList[i, (ushort)(MAPSIZE - 1 - k), j] == BlockType.Dirt) //{ // blockList[i, (ushort)(MAPSIZE - 1 - k), j] = BlockType.Sand;//covers map with block //} for (ushort c = 0; c < 20; c++) { blockListContent[i, (ushort)(MAPSIZE - 1 - k), k, c] = 0;//content data for blocks, such as pumps } blockListHP[i, (ushort)(MAPSIZE - 1 - k), j] = BlockInformation.GetHP(blockList[i, (ushort)(MAPSIZE - 1 - k), j]); if (blockList[i, (ushort)(MAPSIZE - 1 - k), j] == BlockType.Gold) { blockListHP[i, (ushort)(MAPSIZE - 1 - k), j] = 40; } else if (blockList[i, (ushort)(MAPSIZE - 1 - k), j] == BlockType.Diamond) { blockListHP[i, (ushort)(MAPSIZE - 1 - k), j] = 120; } else { } blockCreatorTeam[i, j, k] = PlayerTeam.None; if (i < 1 || j < 1 || k < 1 || i > MAPSIZE - 2 || j > MAPSIZE - 2 || k > MAPSIZE - 2) { blockList[i, (ushort)(MAPSIZE - 1 - k), j] = BlockType.None; } } for (ushort i = 0; i < MAPSIZE; i++) for (ushort j = 0; j < MAPSIZE; j++) for (ushort k = 0; k < MAPSIZE; k++) { if (blockList[i, (ushort)(MAPSIZE - 1 - k), j] != BlockType.MagmaVent && blockList[i, (ushort)(MAPSIZE - 1 - k), j] != BlockType.Spring) if (randGen.Next(500) == 1) { if (i < 1 || j < 1 || k < 1 || i > MAPSIZE - 2 || j > MAPSIZE - 2 || k > MAPSIZE - 2) { } else { if (blockList[i - 1, (ushort)(MAPSIZE - 1 - k), j] != BlockType.None) if (blockList[i + 1, (ushort)(MAPSIZE - 1 - k), j] != BlockType.None) if (blockList[i, (ushort)(MAPSIZE - k), j] != BlockType.None) if (blockList[i, (ushort)(MAPSIZE + 1 - k), j] != BlockType.None) if (blockList[i, (ushort)(MAPSIZE - 1 - k), j - 1] != BlockType.None) if (blockList[i, (ushort)(MAPSIZE - 1 - k), j + 1] != BlockType.None) blockList[i, (ushort)(MAPSIZE - 1 - k), j] = BlockType.MagmaBurst; } } } //add bases createBase(PlayerTeam.Red); createBase(PlayerTeam.Blue); for (ushort i = 0; i < MAPSIZE; i++) for (ushort k = 0; k < MAPSIZE; k++) for (ushort j = (ushort)(MAPSIZE-1); j > 0; j--) { if (blockList[i, j, k] == BlockType.Dirt || blockList[i, j, k] == BlockType.Grass) { blockList[i, j, k] = BlockType.Grass; blockListContent[i, j, k, 0] = 300;//greenery may reside here break; } else if (blockList[i, j, k] != BlockType.None) { break; } } for (int i = 0; i < MAPSIZE * 2; i++) { DoStuff(); } physicsEnabled = true; return 1; }
public static void GenerateTrees(ChunkPos pos, BlockType[,,] blocks) { FastNoise.FastNoise noise1 = Chunk.noise1; int x = pos.x; int z = pos.z; System.Random rand = new System.Random(x * 10000 + z); float simplex = noise1.GetSimplex(x * .8f, z * .8f); if (simplex > 0) { simplex *= 2f; int treeCount = Mathf.FloorToInt((float)rand.NextDouble() * 5 * simplex); for (int i = 0; i < treeCount; i++) { int xPos = (int)(rand.NextDouble() * 14) + 1; int zPos = (int)(rand.NextDouble() * 14) + 1; int y = Chunk.chunkHeight - 1; //find the ground while (y > WaterChunkObject.waterHeight && blocks[xPos, y, zPos] == BlockType.Air) { y--; } if (blocks[xPos, y, zPos] == BlockType.Leaves || blocks[xPos, y, zPos] == BlockType.Air) { return; } //dirt under tree if (blocks[xPos, y, zPos] == BlockType.Grass) { blocks[xPos, y, zPos] = BlockType.Dirt; } y++; int treeHeight = 4 + (int)(rand.NextDouble() * 4); for (int j = 0; j < treeHeight; j++) { if (y + j < chunkHeight) { blocks[xPos, y + j, zPos] = BlockType.Wood; } } int leavesWidth = 1 + (int)(rand.NextDouble() * 6); int leavesHeight = (int)(rand.NextDouble() * 3); if (leavesHeight + leavesWidth < 5) { leavesHeight += 2; leavesWidth += 2; } int iter = 0; for (int y_t = y + treeHeight - 1; y_t <= y + treeHeight - 1 + treeHeight; y_t++) { for (int x_t = xPos - (int)(leavesWidth * .5f) + iter / 2; x_t <= xPos + (int)(leavesWidth * .5f) - iter / 2; x_t++) { for (int z_t = zPos - (int)(leavesWidth * .5f) + iter / 2; z_t <= zPos + (int)(leavesWidth * .5f) - iter / 2; z_t++) { if (y_t >= 0 && y_t < chunkHeight && rand.NextDouble() < .8f) { if (x_t >= chunkWidth || z_t >= chunkWidth || x_t <= 0 || z_t <= 0) { Vector3 blockPos = new Vector3(); ChunkPos cpNextTo = new ChunkPos(); if (z_t > chunkWidth && x_t < 0) { cpNextTo = new ChunkPos(pos.x - chunkWidth, pos.z + chunkWidth); blockPos = new Vector3(x_t + chunkWidth + 1, y_t, z_t - chunkWidth - 1); } else if (z_t < 0 && x_t > chunkWidth) { cpNextTo = new ChunkPos(pos.x + chunkWidth, pos.z - chunkWidth); blockPos = new Vector3(x_t - chunkWidth - 1, y_t, z_t + chunkWidth + 1); } else if (z_t > chunkWidth && x_t > chunkWidth) { cpNextTo = new ChunkPos(pos.x + chunkWidth, pos.z + chunkWidth); blockPos = new Vector3(x_t - chunkWidth - 1, y_t, z_t - chunkWidth - 1); } else if (z_t < 0 && x_t < 0) { cpNextTo = new ChunkPos(pos.x - chunkWidth, pos.z - chunkWidth); blockPos = new Vector3(x_t + chunkWidth + 1, y_t, z_t + chunkWidth + 1); } else if (x_t > chunkWidth) { cpNextTo = new ChunkPos(pos.x + chunkWidth, pos.z); blockPos = new Vector3(x_t - chunkWidth - 1, y_t, z_t); } else if (x_t < 0) { cpNextTo = new ChunkPos(pos.x - chunkWidth, pos.z); blockPos = new Vector3(x_t + chunkWidth + 1, y_t, z_t); } else if (z_t > chunkWidth) { cpNextTo = new ChunkPos(pos.x, pos.z + chunkWidth); blockPos = new Vector3(x_t, y_t, z_t - chunkWidth - 1); } else if (z_t < 0) { cpNextTo = new ChunkPos(pos.x, pos.z - chunkWidth); blockPos = new Vector3(x_t, y_t, z_t + chunkWidth + 1); } if (TerrainGenerator.holdsToGenerate.ContainsKey(cpNextTo)) { if (!TerrainGenerator.holdsToGenerate[cpNextTo].ContainsKey(blockPos)) { TerrainGenerator.holdsToGenerate[cpNextTo].Add(blockPos, BlockType.Leaves); } } else { TerrainGenerator.holdsToGenerate.Add(cpNextTo, new Dictionary <Vector3, BlockType>() { { blockPos, BlockType.Leaves } }); } } else { blocks[x_t, y_t, z_t] = BlockType.Leaves; } } } } iter++; } } } }
public bool Start() { //Setup the variable toggles varBindingsInitialize(); int tmpMaxPlayers = 16; // Read in from the config file. DatafileWriter dataFile = new DatafileWriter("server.config.txt"); if (dataFile.Data.ContainsKey("winningcash")) winningCashAmount = uint.Parse(dataFile.Data["winningcash"], System.Globalization.CultureInfo.InvariantCulture); if (dataFile.Data.ContainsKey("includelava")) includeLava = bool.Parse(dataFile.Data["includelava"]); if (dataFile.Data.ContainsKey("includewater")) includeLava = bool.Parse(dataFile.Data["includewater"]); if (dataFile.Data.ContainsKey("orefactor")) oreFactor = uint.Parse(dataFile.Data["orefactor"], System.Globalization.CultureInfo.InvariantCulture); if (dataFile.Data.ContainsKey("maxplayers")) tmpMaxPlayers = (int)Math.Min(32, uint.Parse(dataFile.Data["maxplayers"], System.Globalization.CultureInfo.InvariantCulture)); if (dataFile.Data.ContainsKey("public")) varSet("public", bool.Parse(dataFile.Data["public"]), true); if (dataFile.Data.ContainsKey("servername")) varSet("name", dataFile.Data["servername"], true); if (dataFile.Data.ContainsKey("sandbox")) varSet("sandbox", bool.Parse(dataFile.Data["sandbox"]), true); if (dataFile.Data.ContainsKey("notnt")) varSet("tnt", !bool.Parse(dataFile.Data["notnt"]), true); if (dataFile.Data.ContainsKey("sphericaltnt")) varSet("stnt", bool.Parse(dataFile.Data["sphericaltnt"]), true); if (dataFile.Data.ContainsKey("insane")) varSet("insane", bool.Parse(dataFile.Data["insane"]), true); if (dataFile.Data.ContainsKey("roadabsorbs")) varSet("roadabsorbs", bool.Parse(dataFile.Data["roadabsorbs"]), true); if (dataFile.Data.ContainsKey("minelava")) varSet("minelava", bool.Parse(dataFile.Data["minelava"]), true); if (dataFile.Data.ContainsKey("levelname")) levelToLoad = dataFile.Data["levelname"]; if (dataFile.Data.ContainsKey("greeter")) varSet("greeter", dataFile.Data["greeter"],true); bool autoannounce = true; if (dataFile.Data.ContainsKey("autoannounce")) autoannounce = bool.Parse(dataFile.Data["autoannounce"]); // Load the ban-list. banList = LoadBanList(); // Load the admin-list admins = LoadAdminList(); if (tmpMaxPlayers>=0) varSet("maxplayers", tmpMaxPlayers, true); // Initialize the server. NetConfiguration netConfig = new NetConfiguration("InfiniminerPlus"); netConfig.MaxConnections = (int)varGetI("maxplayers"); netConfig.Port = 5565; netServer = new InfiniminerNetServer(netConfig); netServer.SetMessageTypeEnabled(NetMessageType.ConnectionApproval, true); //netServer.SimulatedMinimumLatency = 0.5f; // netServer.SimulatedLatencyVariance = 0.05f; // netServer.SimulatedLoss = 0.2f; // netServer.SimulatedDuplicates = 0.05f; //netServer.Configuration.SendBufferSize = 2048000; //netServer.Start();//starts too early // Initialize variables we'll use. NetBuffer msgBuffer = netServer.CreateBuffer(); NetMessageType msgType; NetConnection msgSender; // Store the last time that we did a flow calculation. DateTime lastFlowCalc = DateTime.Now; DateTime lastFlowCalcZ = DateTime.Now;//temporary DateTime sysTimer = DateTime.Now; //Check if we should autoload a level if (dataFile.Data.ContainsKey("autoload") && bool.Parse(dataFile.Data["autoload"])) { blockList = new BlockType[MAPSIZE, MAPSIZE, MAPSIZE]; blockCreatorTeam = new PlayerTeam[MAPSIZE, MAPSIZE, MAPSIZE]; LoadLevel(levelToLoad); lavaBlockCount = 0; waterBlockCount = 0; int burstBlockCount = 0; for (ushort i = 0; i < MAPSIZE; i++) for (ushort j = 0; j < MAPSIZE; j++) for (ushort k = 0; k < MAPSIZE; k++) { if (blockList[i, j, k] == BlockType.Lava) { lavaBlockCount += 1; } else if (blockList[i, j, k] == BlockType.Water) { waterBlockCount += 1; } else if (blockList[i, j, k] == BlockType.MagmaBurst) { burstBlockCount += 1; } } ConsoleWrite(waterBlockCount + " water blocks, " + lavaBlockCount + " lava blocks, " + burstBlockCount + " possible bursts." ); } else { // Calculate initial lava flows. ConsoleWrite("CALCULATING INITIAL LIQUID BLOCKS"); newMap(); lavaBlockCount = 0; waterBlockCount = 0; int burstBlockCount = 0; for (ushort i = 0; i < MAPSIZE; i++) for (ushort j = 0; j < MAPSIZE; j++) for (ushort k = 0; k < MAPSIZE; k++) { if (blockList[i, j, k] == BlockType.Lava) { lavaBlockCount += 1; } else if (blockList[i, j, k] == BlockType.Water) { waterBlockCount += 1; } else if (blockList[i, j, k] == BlockType.MagmaBurst) { burstBlockCount += 1; } } ConsoleWrite(waterBlockCount + " water blocks, " + lavaBlockCount + " lava blocks, " + burstBlockCount + " possible bursts."); } //Caculate the shape of spherical tnt explosions CalculateExplosionPattern(); // Send the initial server list update. if (autoannounce) PublicServerListUpdate(true); lastMapBackup = DateTime.Now; DateTime lastFPScheck = DateTime.Now; double frameRate = 0; // Main server loop! netServer.Start(); ConsoleWrite("SERVER READY"); if (!physics.IsAlive) { ConsoleWrite("Physics thread is limp."); } while (keepRunning) { if (!physics.IsAlive) { ConsoleWrite("Physics thread died."); // physics.Abort(); // physics.Join(); //physics.Start(); } frameCount = frameCount + 1; if (lastFPScheck <= DateTime.Now - TimeSpan.FromMilliseconds(1000)) { lastFPScheck = DateTime.Now; frameRate = frameCount;// / gameTime.ElapsedTotalTime.TotalSeconds; if (sleeping == false && frameCount < 20) { ConsoleWrite("Heavy load: " + frameCount + " FPS"); } frameCount = 0; } // Process any messages that are here. while (netServer.ReadMessage(msgBuffer, out msgType, out msgSender)) { try { switch (msgType) { case NetMessageType.ConnectionApproval: { Player newPlayer = new Player(msgSender, null); newPlayer.Handle = Defines.Sanitize(msgBuffer.ReadString()).Trim(); if (newPlayer.Handle.Length == 0) { newPlayer.Handle = "Player"; } string clientVersion = msgBuffer.ReadString(); if (clientVersion != Defines.INFINIMINER_VERSION) { msgSender.Disapprove("VER;" + Defines.INFINIMINER_VERSION); } else if (banList.Contains(newPlayer.IP)) { msgSender.Disapprove("BAN;"); }/* else if (playerList.Count == maxPlayers) { msgSender.Disapprove("FULL;"); }*/ else { if (admins.ContainsKey(newPlayer.IP)) newPlayer.admin = admins[newPlayer.IP]; playerList[msgSender] = newPlayer; //Check if we should compress the map for the client try { bool compression = msgBuffer.ReadBoolean(); if (compression) playerList[msgSender].compression = true; } catch { } toGreet.Add(msgSender); this.netServer.SanityCheck(msgSender); msgSender.Approve(); PublicServerListUpdate(true); } } break; case NetMessageType.StatusChanged: { if (!this.playerList.ContainsKey(msgSender)) { break; } Player player = playerList[msgSender]; if (msgSender.Status == NetConnectionStatus.Connected) { if (sleeping == true) { sleeping = false; physicsEnabled = true; } ConsoleWrite("CONNECT: " + playerList[msgSender].Handle + " ( " + playerList[msgSender].IP + " )"); SendCurrentMap(msgSender); SendPlayerJoined(player); PublicServerListUpdate(); } else if (msgSender.Status == NetConnectionStatus.Disconnected) { ConsoleWrite("DISCONNECT: " + playerList[msgSender].Handle); SendPlayerLeft(player, player.Kicked ? "WAS KICKED FROM THE GAME!" : "HAS ABANDONED THEIR DUTIES!"); if (playerList.ContainsKey(msgSender)) playerList.Remove(msgSender); sleeping = true; foreach (Player p in playerList.Values) { sleeping = false; } if (sleeping == true) { ConsoleWrite("HIBERNATING"); physicsEnabled = false; } PublicServerListUpdate(); } } break; case NetMessageType.Data: { if (!this.playerList.ContainsKey(msgSender)) { break; } Player player = playerList[msgSender]; InfiniminerMessage dataType = (InfiniminerMessage)msgBuffer.ReadByte(); switch (dataType) { case InfiniminerMessage.ChatMessage: { // Read the data from the packet. ChatMessageType chatType = (ChatMessageType)msgBuffer.ReadByte(); string chatString = Defines.Sanitize(msgBuffer.ReadString()); if (!ProcessCommand(chatString,GetAdmin(playerList[msgSender].IP),playerList[msgSender])) { if (chatType == ChatMessageType.SayAll) ConsoleWrite("CHAT: (" + player.Handle + ") " + chatString); // Append identifier information. if (chatType == ChatMessageType.SayAll) chatString = player.Handle + " (ALL): " + chatString; else chatString = player.Handle + " (TEAM): " + chatString; // Construct the message packet. NetBuffer chatPacket = netServer.CreateBuffer(); chatPacket.Write((byte)InfiniminerMessage.ChatMessage); chatPacket.Write((byte)((player.Team == PlayerTeam.Red) ? ChatMessageType.SayRedTeam : ChatMessageType.SayBlueTeam)); chatPacket.Write(chatString); // Send the packet to people who should recieve it. foreach (Player p in playerList.Values) { if (chatType == ChatMessageType.SayAll || chatType == ChatMessageType.SayBlueTeam && p.Team == PlayerTeam.Blue || chatType == ChatMessageType.SayRedTeam && p.Team == PlayerTeam.Red) if (p.NetConn.Status == NetConnectionStatus.Connected) netServer.SendMessage(chatPacket, p.NetConn, NetChannel.ReliableInOrder3); } } } break; case InfiniminerMessage.UseTool: { Vector3 playerPosition = msgBuffer.ReadVector3(); Vector3 playerHeading = msgBuffer.ReadVector3(); PlayerTools playerTool = (PlayerTools)msgBuffer.ReadByte(); BlockType blockType = (BlockType)msgBuffer.ReadByte(); //getTo switch (playerTool) { case PlayerTools.Pickaxe: UsePickaxe(player, playerPosition, playerHeading); break; case PlayerTools.StrongArm: if (player.Class == PlayerClass.Miner) UseStrongArm(player, playerPosition, playerHeading); break; case PlayerTools.Smash: //if(player.Class == PlayerClass.Sapper) //UseSmash(player, playerPosition, playerHeading); break; case PlayerTools.ConstructionGun: UseConstructionGun(player, playerPosition, playerHeading, blockType); break; case PlayerTools.DeconstructionGun: UseDeconstructionGun(player, playerPosition, playerHeading); break; case PlayerTools.ProspectingRadar: UseSignPainter(player, playerPosition, playerHeading); break; case PlayerTools.Detonator: if (player.Class == PlayerClass.Sapper) UseDetonator(player); break; case PlayerTools.Remote: if (player.Class == PlayerClass.Engineer) UseRemote(player); break; case PlayerTools.SetRemote: if (player.Class == PlayerClass.Engineer) SetRemote(player); break; case PlayerTools.ThrowBomb: if (player.Class == PlayerClass.Sapper) ThrowBomb(player, playerPosition, playerHeading); break; case PlayerTools.ThrowRope: if (player.Class == PlayerClass.Prospector) ThrowRope(player, playerPosition, playerHeading); break; case PlayerTools.Hide: if (player.Class == PlayerClass.Prospector) Hide(player); break; } } break; case InfiniminerMessage.SelectClass: { PlayerClass playerClass = (PlayerClass)msgBuffer.ReadByte(); player.Alive = false; ConsoleWrite("SELECT_CLASS: " + player.Handle + ", " + playerClass.ToString()); switch (playerClass) { case PlayerClass.Engineer: player.Class = playerClass; player.OreMax = 200 + (uint)(ResearchComplete[(byte)player.Team, 2] * 20); player.WeightMax = 4 + (uint)(ResearchComplete[(byte)player.Team, 2]); player.HealthMax = 100 + (uint)(ResearchComplete[(byte)player.Team,1]*20); player.Health = player.HealthMax; for (int a = 0; a < 100; a++) { player.Content[a] = 0; } break; case PlayerClass.Miner://strong arm/throws blocks player.Class = playerClass; player.OreMax = 100 + (uint)(ResearchComplete[(byte)player.Team, 2] * 20); player.WeightMax = 10 + (uint)(ResearchComplete[(byte)player.Team, 2]); player.HealthMax = 100 + (uint)(ResearchComplete[(byte)player.Team, 1] * 20); player.Health = player.HealthMax; for (int a = 0; a < 100; a++) { player.Content[a] = 0; } break; case PlayerClass.Prospector://profiteer/has prospectron/stealth/climb/traps player.Class = playerClass; player.OreMax = 100 + (uint)(ResearchComplete[(byte)player.Team, 2] * 20); player.WeightMax = 6 + (uint)(ResearchComplete[(byte)player.Team, 2]); player.HealthMax = 100 + (uint)(ResearchComplete[(byte)player.Team, 1] * 20); player.Health = player.HealthMax; for (int a = 0; a < 100; a++) { player.Content[a] = 0; } break; case PlayerClass.Sapper://berserker/charge that knocks people and blocks away/repairs block player.Class = playerClass; player.OreMax = 100 + (uint)(ResearchComplete[(byte)player.Team, 2] * 20); player.WeightMax = 4 + (uint)(ResearchComplete[(byte)player.Team, 2]); player.HealthMax = 100 + (uint)(ResearchComplete[(byte)player.Team, 1] * 20); player.Health = player.HealthMax; for (int a = 0; a < 100; a++) { player.Content[a] = 0; } break; } SendResourceUpdate(player); SendContentUpdate(player); SendPlayerSetClass(player); } break; case InfiniminerMessage.PlayerSetTeam: { PlayerTeam playerTeam = (PlayerTeam)msgBuffer.ReadByte(); ConsoleWrite("SELECT_TEAM: " + player.Handle + ", " + playerTeam.ToString()); player.Team = playerTeam; player.Health = 0; player.Alive = false; Player_Dead(player, ""); SendResourceUpdate(player); SendPlayerSetTeam(player); } break; case InfiniminerMessage.PlayerDead: { string deathMessage = msgBuffer.ReadString(); if (player.Alive) { Player_Dead(player, deathMessage); } } break; case InfiniminerMessage.PlayerAlive: { if (toGreet.Contains(msgSender)) { string greeting = varGetS("greeter"); greeting = greeting.Replace("[name]", playerList[msgSender].Handle); if (greeting != "") { NetBuffer greetBuffer = netServer.CreateBuffer(); greetBuffer.Write((byte)InfiniminerMessage.ChatMessage); greetBuffer.Write((byte)ChatMessageType.SayAll); greetBuffer.Write(Defines.Sanitize(greeting)); netServer.SendMessage(greetBuffer, msgSender, NetChannel.ReliableInOrder3); } toGreet.Remove(msgSender); } ConsoleWrite("PLAYER_ALIVE: " + player.Handle); player.Ore = 0; player.Cash = 0; player.Weight = 0; player.Health = player.HealthMax; player.Alive = true; player.respawnTimer = DateTime.Now + TimeSpan.FromSeconds(5); SendResourceUpdate(player); SendPlayerAlive(player); } break; case InfiniminerMessage.PlayerRespawn: { SendPlayerRespawn(player);//new respawn } break; case InfiniminerMessage.PlayerUpdate: { if (player.Alive) { player.Position = Auth_Position(msgBuffer.ReadVector3(), player, true); player.Heading = Auth_Heading(msgBuffer.ReadVector3()); player.Tool = (PlayerTools)msgBuffer.ReadByte(); player.UsingTool = msgBuffer.ReadBoolean(); SendPlayerUpdate(player); } } break; case InfiniminerMessage.PlayerSlap: { if (player.Alive) { if (player.playerToolCooldown > DateTime.Now) { break;//discard fast packet } player.Position = Auth_Position(msgBuffer.ReadVector3(), player, true); player.Heading = Auth_Heading(msgBuffer.ReadVector3()); player.Tool = (PlayerTools)msgBuffer.ReadByte(); player.UsingTool = true; Auth_Slap(player, msgBuffer.ReadUInt32()); SendPlayerUpdate(player); player.playerToolCooldown = DateTime.Now + TimeSpan.FromSeconds((float)(player.GetToolCooldown(PlayerTools.Pickaxe))); if (player.Class == PlayerClass.Prospector && player.Content[5] > 0)//reveal when hit { player.Content[6] = 0;//uncharge player.Content[1] = 0;//reappear on radar SendPlayerContentUpdate(player, 1); player.Content[5] = 0;//sight SendContentSpecificUpdate(player, 5); SendContentSpecificUpdate(player, 6); SendPlayerContentUpdate(player, 5); SendServerMessageToPlayer("You have been revealed!", player.NetConn); EffectAtPoint(player.Position - Vector3.UnitY * 1.5f, 1); } } } break; case InfiniminerMessage.PlayerUpdate1://minus position { if (player.Alive) { player.Heading = Auth_Heading(msgBuffer.ReadVector3()); player.Tool = (PlayerTools)msgBuffer.ReadByte(); player.UsingTool = msgBuffer.ReadBoolean(); SendPlayerUpdate(player); } } break; case InfiniminerMessage.PlayerUpdate2://minus position and heading { if (player.Alive) { player.Tool = (PlayerTools)msgBuffer.ReadByte(); player.UsingTool = msgBuffer.ReadBoolean(); SendPlayerUpdate(player); } } break; case InfiniminerMessage.PlayerHurt://client speaks of fall damage { uint newhp = msgBuffer.ReadUInt32(); if (newhp < player.Health) { if (player.Team == PlayerTeam.Red) { DebrisEffectAtPoint((int)(player.Position.X), (int)(player.Position.Y), (int)(player.Position.Z), BlockType.SolidRed, 10 + (int)(player.Health - newhp)); } else { DebrisEffectAtPoint((int)(player.Position.X), (int)(player.Position.Y), (int)(player.Position.Z), BlockType.SolidBlue, 10 + (int)(player.Health - newhp)); } player.Health = newhp; if (player.Health < 1) { Player_Dead(player, "FELL TO THEIR DEATH!"); } } } break; case InfiniminerMessage.PlayerPosition://server not interested in clients complaints about position { } break; case InfiniminerMessage.PlayerInteract://client speaks of mashing on block { player.Position = Auth_Position(msgBuffer.ReadVector3(), player, true); uint btn = msgBuffer.ReadUInt32(); uint btnx = msgBuffer.ReadUInt32(); uint btny = msgBuffer.ReadUInt32(); uint btnz = msgBuffer.ReadUInt32(); //if (blockList[btnx, btny, btnz] == BlockType.Pump || blockList[btnx, btny, btnz] == BlockType.Pipe || blockList[btnx, btny, btnz] == BlockType.Generator || blockList[btnx, btny, btnz] == BlockType.Barrel || blockList[btnx, btny, btnz] == BlockType.Switch) //{ if (Get3DDistance((int)btnx, (int)btny, (int)btnz, (int)player.Position.X, (int)player.Position.Y, (int)player.Position.Z) < 4) { PlayerInteract(player,btn, btnx, btny, btnz); } //} } break; case InfiniminerMessage.DepositOre: { DepositOre(player); foreach (Player p in playerList.Values) SendResourceUpdate(p); } break; case InfiniminerMessage.WithdrawOre: { WithdrawOre(player); foreach (Player p in playerList.Values) SendResourceUpdate(p); } break; case InfiniminerMessage.PlayerPing: { if (player.Ping == 0) { SendPlayerPing((uint)msgBuffer.ReadInt32()); player.Ping = 2; } } break; case InfiniminerMessage.PlaySound: { InfiniminerSound sound = (InfiniminerSound)msgBuffer.ReadByte(); Vector3 position = msgBuffer.ReadVector3(); PlaySoundForEveryoneElse(sound, position,player); } break; case InfiniminerMessage.DropItem: { DropItem(player, msgBuffer.ReadUInt32()); } break; case InfiniminerMessage.GetItem: { //verify players position before get player.Position = Auth_Position(msgBuffer.ReadVector3(), player, false); GetItem(player,msgBuffer.ReadUInt32()); } break; } } break; } } catch { } } //Time to backup map? TimeSpan mapUpdateTimeSpan = DateTime.Now - lastMapBackup; if (mapUpdateTimeSpan.TotalMinutes > 5) { lastMapBackup = DateTime.Now; SaveLevel("autoBK.lvl"); } // Time to send a new server update? PublicServerListUpdate(); //It checks for public server / time span //Time to terminate finished map sending threads? TerminateFinishedThreads(); // Check for players who are in the zone to deposit. VictoryCheck(); // Is it time to do a lava calculation? If so, do it! TimeSpan timeSpan = DateTime.Now - sysTimer; if (timeSpan.TotalMilliseconds > 2000) { //ConsoleWrite("" + delta); sysTimer = DateTime.Now; //secondflow += 1; //if (secondflow > 2)//every 2nd flow, remove the vacuum that prevent re-spread //{ // EraseVacuum(); // secondflow = 0; //} if (randGen.Next(1, 4) == 3) { bool isUpdateOre = false; bool isUpdateCash = false; for (int a = 1; a < 3; a++) { if (artifactActive[a, 1] > 0)//material artifact { isUpdateOre = true; if (a == 1) { teamOreRed = teamOreRed + (uint)(10 * artifactActive[a, 1]); } else if (a == 2) { teamOreBlue = teamOreBlue + (uint)(10 * artifactActive[a, 1]); } } if (artifactActive[a, 5] > 0)//golden artifact { isUpdateCash = true; if (a == 1) { teamCashRed = teamCashRed + (uint)(2 * artifactActive[a, 5]); } else if (a == 2) { teamCashBlue = teamCashBlue + (uint)(2 * artifactActive[a, 5]); } } } if (isUpdateOre) foreach (Player p in playerList.Values) SendTeamOreUpdate(p); if(isUpdateCash) foreach (Player p in playerList.Values) SendTeamCashUpdate(p); } foreach (Player p in playerList.Values)//regeneration { if (p.Ping > 0) p.Ping--; if (p.Alive) { if (p.Content[10] == 1)//material artifact personal { if (randGen.Next(1, 4) == 3) { if (p.Ore < p.OreMax) { p.Ore += 10; if (p.Ore >= p.OreMax) p.Ore = p.OreMax; SendOreUpdate(p); } } } else if (p.Content[10] == 5)//golden artifact personal { if (p.Ore > 99) { if (p.Weight < p.WeightMax) { p.Weight++; p.Cash += 10; p.Ore -= 100; SendCashUpdate(p); SendWeightUpdate(p); SendOreUpdate(p); PlaySound(InfiniminerSound.CashDeposit, p.Position); } } } else if (p.Content[10] == 6)//storm artifact personal { if(artifactActive[(byte)((p.Team == PlayerTeam.Red) ? PlayerTeam.Blue : PlayerTeam.Red),6] == 0)//stored storm artifact makes team immune foreach (Player pt in playerList.Values) { if (p.Team != pt.Team && pt.Alive) { float distfromPlayer = (p.Position - pt.Position).Length(); if (distfromPlayer < 5) { pt.Health -= 5; if (pt.Health <= 0) { Player_Dead(pt,"WAS SHOCKED!"); } else SendHealthUpdate(pt); EffectAtPoint(pt.Position, 1); } } } } if (p.Health >= p.HealthMax) { p.Health = p.HealthMax; } else { p.Health = (uint)(p.Health + teamRegeneration[(byte)p.Team]); if (p.Content[10] == 3)//regeneration artifact { p.Health += 4; } if (p.Health >= p.HealthMax) { p.Health = p.HealthMax; } SendHealthUpdate(p); } if (p.Class == PlayerClass.Prospector) { if (p.Content[5] == 1) { p.Content[6]--; if (p.Content[6] < 1) { p.Content[1] = 0; SendPlayerContentUpdate(p, 1); p.Content[5] = 0;//sight SendContentSpecificUpdate(p, 5); SendPlayerContentUpdate(p, 5); SendServerMessageToPlayer("Hide must now recharge!", p.NetConn); EffectAtPoint(p.Position - Vector3.UnitY * 1.5f, 1); } } else { if(p.Content[6] < 4) p.Content[6]++; } } //if (p.Class == PlayerClass.Prospector)//temperature data//giving everyone //{ // p.Content[6] = 0; // for(int a = -5;a < 6;a++) // for(int b = -5;b < 6;b++) // for (int c = -5; c < 6; c++) // { // int nx = a + (int)p.Position.X; // int ny = b + (int)p.Position.Y; // int nz = c + (int)p.Position.Z; // if (nx < MAPSIZE - 1 && ny < MAPSIZE - 1 && nz < MAPSIZE - 1 && nx > 0 && ny > 0 && nz > 0) // { // BlockType block = blockList[nx,ny,nz]; // if (block == BlockType.Lava || block == BlockType.MagmaBurst || block == BlockType.MagmaVent) // { // p.Content[6] += 5 - Math.Abs(a) + 5 - Math.Abs(b) + 5 - Math.Abs(c); // } // } // } // if (p.Content[6] > 0) // SendContentSpecificUpdate(p, 6); //} } } } TimeSpan timeSpanZ = DateTime.Now - lastFlowCalcZ; serverTime[timeQueue] = DateTime.Now - lastTime;//timeQueue timeQueue += 1; if (timeQueue > 19) timeQueue = 0; lastTime = DateTime.Now; delta = (float)((serverTime[0].TotalSeconds + serverTime[1].TotalSeconds + serverTime[2].TotalSeconds + serverTime[3].TotalSeconds + serverTime[4].TotalSeconds + serverTime[5].TotalSeconds + serverTime[6].TotalSeconds + serverTime[7].TotalSeconds + serverTime[8].TotalSeconds + serverTime[9].TotalSeconds + serverTime[10].TotalSeconds + serverTime[11].TotalSeconds + serverTime[12].TotalSeconds + serverTime[13].TotalSeconds + serverTime[14].TotalSeconds + serverTime[15].TotalSeconds + serverTime[16].TotalSeconds + serverTime[17].TotalSeconds + serverTime[18].TotalSeconds + serverTime[19].TotalSeconds) / 20); Sunray(); if (timeSpanZ.TotalMilliseconds > 50) { lastFlowCalcZ = DateTime.Now; DoItems(); } //random diamond appearance if (sleeping == false) if (randGen.Next(1, 100000) == 2) { ushort diamondx = (ushort)randGen.Next(4, 57); ushort diamondy = (ushort)randGen.Next(3, 30); ushort diamondz = (ushort)randGen.Next(4, 57); if (blockList[diamondx, diamondy, diamondz] == BlockType.Dirt) { // ConsoleWrite("diamond spawned at " + diamondx + "/" + diamondy + "/" + diamondz); SetBlock(diamondx, diamondy, diamondz, BlockType.Diamond, PlayerTeam.None); blockListHP[diamondx, diamondy, diamondz] = BlockInformation.GetMaxHP(BlockType.Diamond); } } // Handle console keypresses. while (Console.KeyAvailable) { ConsoleKeyInfo keyInfo = Console.ReadKey(); if (keyInfo.Key == ConsoleKey.Enter) { if (consoleInput.Length > 0) ConsoleProcessInput(); } else if (keyInfo.Key == ConsoleKey.Backspace) { if (consoleInput.Length > 0) consoleInput = consoleInput.Substring(0, consoleInput.Length - 1); ConsoleRedraw(); } else { consoleInput += keyInfo.KeyChar; ConsoleRedraw(); } } // Is the game over? if (winningTeam != PlayerTeam.None && !restartTriggered) { BroadcastGameOver(); restartTriggered = true; restartTime = DateTime.Now.AddSeconds(10); } // Restart the server? if (restartTriggered && DateTime.Now > restartTime) { SaveLevel("autosave_" + (UInt64)DateTime.Now.ToBinary() + ".lvl"); netServer.Shutdown("The server is restarting."); Thread.Sleep(100); physics.Abort(); // mechanics.Abort(); return true;//terminates server thread completely } // Pass control over to waiting threads. if(sleeping == true) { Thread.Sleep(50); } else { Thread.Sleep(1); } } MessageAll("Server going down NOW!"); netServer.Shutdown("The server was terminated."); return false; }