Пример #1
0
 static void ExplorePosition(int x, int y, BlockMap closeList, List <Vector2Int> openList)
 {
     if (closeList.Get(x, y) == null)
     {
         openList.Add(new Vector2Int(x, y));
     }
 }
Пример #2
0
        public BinaryMap Binarize(float[,] input, float[,] baseline, BinaryMap mask, BlockMap blocks)
        {
            BinaryMap binarized = new BinaryMap(input.GetLength(1), input.GetLength(0));

            Parallel.For(0, blocks.AllBlocks.Height, delegate(int blockY)
            {
                for (int blockX = 0; blockX < blocks.AllBlocks.Width; ++blockX)
                {
                    if (mask.GetBit(blockX, blockY))
                    {
                        RectangleC rect = blocks.BlockAreas[blockY, blockX];
                        for (int y = rect.Bottom; y < rect.Top; ++y)
                        {
                            for (int x = rect.Left; x < rect.Right; ++x)
                            {
                                if (input[y, x] - baseline[y, x] > 0)
                                {
                                    binarized.SetBitOne(x, y);
                                }
                            }
                        }
                    }
                }
            });
            Logger.Log(binarized);
            return(binarized);
        }
Пример #3
0
    /// <summary>
    /// 预处理地形的函数
    /// 通过不同的算法产生地形数据
    /// </summary>
    private void CalculateMap()
    {
        _mesh      = new Mesh();
        _mesh.name = "Chunck";

        _map = new Block[length, height, width];
        for (int x = 0; x < length; x++)
        {
            for (int y = 0; y < height; y++)
            {
                for (int z = 0; z < width; z++)
                {
                    if (y == height - 1)
                    {
                        if (Random.value > 0.7f)
                        {
                            _map[x, y, z] = BlockMap.GetBlock("Grass");
                        }
                        else
                        {
                            _map[x, y, z] = null;
                        }
                    }
                    else
                    {
                        _map[x, y, z] = BlockMap.GetBlock("Dirt");
                    }
                }
            }
        }
        CalculateMesh();
    }
            private static BlockMap ToBlockMap(bool[] model)
            {
                var result = new BlockMap(model.Length);

                var currentOffset = -1;
                var currentLength = 0;

                for (int i = 0; i < model.Length; ++i)
                {
                    if (model[i])
                    {
                        if (currentOffset < 0)
                        {
                            currentOffset = i;
                        }
                        ++currentLength;
                    }
                    else
                    {
                        if (currentOffset >= 0)
                        {
                            result.AssignBytes(currentOffset, currentLength);
                            currentOffset = -1;
                            currentLength = 0;
                        }
                    }
                }
                if (currentOffset >= 0)
                {
                    result.AssignBytes(currentOffset, currentLength);
                }

                return(result);
            }
Пример #5
0
        float[,] PerformEqualization(BlockMap blocks, byte[,] image, float[, ,] equalization, BinaryMap blockMask)
        {
            float[,] result = new float[blocks.PixelCount.Height, blocks.PixelCount.Width];
            Parallel.ForEach(blocks.AllBlocks, delegate(Point block)
            {
                if (blockMask.GetBit(block))
                {
                    RectangleC area = blocks.BlockAreas[block];
                    for (int y = area.Bottom; y < area.Top; ++y)
                    {
                        for (int x = area.Left; x < area.Right; ++x)
                        {
                            byte pixel = image[y, x];

                            float bottomLeft  = equalization[block.Y, block.X, pixel];
                            float bottomRight = equalization[block.Y, block.X + 1, pixel];
                            float topLeft     = equalization[block.Y + 1, block.X, pixel];
                            float topRight    = equalization[block.Y + 1, block.X + 1, pixel];

                            PointF fraction = area.GetFraction(new Point(x, y));
                            result[y, x]    = Calc.Interpolate(topLeft, topRight, bottomLeft, bottomRight, fraction);
                        }
                    }
                }
            });
            Logger.Log(result);
            return(result);
        }
Пример #6
0
        /// <summary>
        /// Create a blockmap containing linedefs. This is used to speed up determining the closest line
        /// to the mouse cursor
        /// </summary>
        private void CreateBlockmap()
        {
            RectangleF area = MapSet.CreateArea(General.Map.Map.Vertices);

            blockmap = new BlockMap <BlockEntry>(area);
            blockmap.AddLinedefsSet(General.Map.Map.Linedefs);
        }
Пример #7
0
    void Awake()
    {
        //First we will create our map using the parameters we have set
        createdMap = BlockUtilities.CreateBlockMap(mapName, tileSize, chunkWidth, chunkHeight, growthAxis);

        //Now we will create a big old block of cubes, according to the dimensions we've set above
        for (int x = 0; x < levelWidth; x++)
        {
            for (int y = 0; y < levelWidth; y++)
            {
                for (int z = 0; z < levelDepth; z++)
                {
                    //We instantiate the block outside of the BlockUtilites library
                    //I've made it this way to allow you to pool GameObjects or anything you like
                    //So you have control over where your blocks come from
                    Block b = GameObject.Instantiate(blockPrefab) as Block;

                    //Now we add the block to the map at the desired coordinates
                    //We won't randomise or refresh at this point, as we're creating a large map
                    //We will do that as one call later
                    BlockUtilities.AddBlockToMap(createdMap, b, false, 0, false, x, y, z, false, true);
                }
            }
        }

        //Now that our map has been created, we will refresh it
        //Refreshing your map sets your blocks to orient correctly
        //And gives you an opportunity to randomise your variants en'masse
        BlockUtilities.RefreshMap(createdMap, randomiseInitialMap);
    }
Пример #8
0
        // This stops checking (only called from the checking management thread)
        private void StopChecking()
        {
            if (this.InvokeRequired)
            {
                CallVoidMethodDeletage d = new CallVoidMethodDeletage(StopChecking);
                this.Invoke(d);
            }
            else
            {
                checksthread     = null;
                progress.Value   = 0;
                buttoncheck.Text = "Start Analysis";
                Cursor.Current   = Cursors.Default;
                running          = false;
                blockmap.Dispose();
                blockmap = null;

                // When no results found, show "no results" and disable the list
                if (results.Items.Count == 0)
                {
                    results.Items.Add(new ResultNoErrors());
                    results.Enabled = false;
                }
            }
        }
Пример #9
0
 public float[,] Smooth(float[,] input, byte[,] orientation, BinaryMap mask, BlockMap blocks)
 {
     Point[][] lines = Lines.Construct();
     float[,] output = new float[input.GetLength(0), input.GetLength(1)];
     Parallel.ForEach(blocks.AllBlocks, delegate(Point block)
     {
         if (mask.GetBit(block))
         {
             Point[] line = lines[Angle.Quantize(Angle.Add(orientation[block.Y, block.X], AngleOffset), lines.Length)];
             foreach (Point linePoint in line)
             {
                 RectangleC target = blocks.BlockAreas[block];
                 RectangleC source = target.GetShifted(linePoint);
                 source.Clip(new RectangleC(blocks.PixelCount));
                 target = source.GetShifted(Calc.Negate(linePoint));
                 for (int y = target.Bottom; y < target.Top; ++y)
                     for (int x = target.Left; x < target.Right; ++x)
                         output[y, x] += input[y + linePoint.Y, x + linePoint.X];
             }
             RectangleC blockArea = blocks.BlockAreas[block];
             for (int y = blockArea.Bottom; y < blockArea.Top; ++y)
                 for (int x = blockArea.Left; x < blockArea.Right; ++x)
                     output[y, x] *= 1f / line.Length;
         }
     });
     Logger.Log(output);
     return output;
 }
            private static BlockMap.Block[] GetFreeBlocks(BlockMap blockMap)
            {
                var blocks     = blockMap.Blocks;
                var freeBlocks = new List <BlockMap.Block>();

                if (blocks.Any())
                {
                    if (blocks.First().Offset > 0)
                    {
                        freeBlocks.Add(new BlockMap.Block(0, blocks[0].Offset));
                    }
                    for (int i = 0; i < blocks.Count - 1; ++i)
                    {
                        var freeBlockOffset = blocks[i].Offset + blocks[i].Count;
                        freeBlocks.Add(new BlockMap.Block(freeBlockOffset, blocks[i + 1].Offset - freeBlockOffset));
                    }
                    var lastByteIndex = blocks.Last().Offset + blocks.Last().Count;
                    if (lastByteIndex < blockMap.Capacity)
                    {
                        freeBlocks.Add(new BlockMap.Block(lastByteIndex, blockMap.Capacity - lastByteIndex));
                    }
                }
                else
                {
                    freeBlocks.Add(new BlockMap.Block(0, blockMap.Capacity));
                }

                return(freeBlocks.ToArray());
            }
Пример #11
0
        private BlockMap CreateBlockMap(Point worldDimensions, List <Block> tiles)
        {
            BlockMap map = new BlockMap(
                worldDimensions.X / Definitions.Grid_Cell_Pixel_Size,
                worldDimensions.Y / Definitions.Grid_Cell_Pixel_Size,
                Definitions.Grid_Cell_Pixel_Size,
                Definitions.Grid_Cell_Pixel_Size,
                Map_Render_Layer);

            for (int i = 0; i < tiles.Count; i++)
            {
                map.SetTile(
                    (int)(tiles[i].WorldPosition.X / Definitions.Grid_Cell_Pixel_Size),
                    (int)(tiles[i].WorldPosition.Y / Definitions.Grid_Cell_Pixel_Size),
                    tiles[i]);
            }

            for (int i = 0; i < _bombs.Count; i++)
            {
                _bombs[i].Map         = map;
                _bombs[i].MapLocation = new Point(
                    (int)(_bombs[i].WorldPosition.X / Definitions.Grid_Cell_Pixel_Size),
                    (int)(_bombs[i].WorldPosition.Y / Definitions.Grid_Cell_Pixel_Size));
            }

            return(map);
        }
Пример #12
0
        // Mode engages
        public override void OnEngage()
        {
            base.OnEngage();

            // Nothing highlighted
            highlighted = null;
            hx          = -1;
            hy          = -1;

            // Custom presentation to hide the grid
            CustomPresentation p = new CustomPresentation();

            p.AddLayer(new PresentLayer(RendererLayer.Background, BlendingMode.Mask, General.Settings.BackgroundAlpha));
            p.AddLayer(new PresentLayer(RendererLayer.Surface, BlendingMode.Mask));
            p.AddLayer(new PresentLayer(RendererLayer.Overlay, BlendingMode.Alpha, 1f, true));
            p.AddLayer(new PresentLayer(RendererLayer.Things, BlendingMode.Alpha, 1.0f));
            p.AddLayer(new PresentLayer(RendererLayer.Geometry, BlendingMode.Alpha, 1f, true));
            renderer.SetPresentation(p);

            // Make the blockmap
            RectangleF area = MapSet.CreateArea(General.Map.Map.Vertices);

            area     = MapSet.IncreaseArea(area, General.Map.Map.Things);
            blockmap = new BlockMap <BlockEntry>(area);
            blockmap.AddLinedefsSet(General.Map.Map.Linedefs);
            blockmap.AddSectorsSet(General.Map.Map.Sectors);
            blockmap.AddThingsSet(General.Map.Map.Things);
        }
Пример #13
0
    public bool CheckSatisfied(BlockMap existingBlocks)
    {
        if (blocks.Count == 0)
        {
            return(true);
        }
        bool result = false;

        foreach (var existing in existingBlocks)
        {
            bool satisfied = true;
            foreach (var block in blocks)
            {
                var mappedToBlock = existingBlocks.Get(existing.X + block.X, existing.Y + block.Y);
                if (mappedToBlock == null ||
                    mappedToBlock.Color != block.Color ||
                    mappedToBlock.OnFire)
                {
                    satisfied = false;
                    break;
                }
            }
            if (satisfied)
            {
                result = true;
                foreach (var block in blocks)
                {
                    var mappedToBlock = existingBlocks.Get(existing.X + block.X, existing.Y + block.Y);
                    mappedToBlock.Satisfied = true;
                }
            }
        }
        return(result);
    }
Пример #14
0
    public void BindToMap(BlockMap map, Block b)
    {
        this.parentMap   = map;
        this.parentBlock = b;

        OnBindToMap(map, b);
    }
Пример #15
0
        public List <Vector2D> GetRelocatePositions(int numsectors)
        {
            List <Vector2D>       positions = new List <Vector2D>();
            BlockMap <BlockEntry> blockmap  = CreateBlockmap(true);
            int margin = (int)((gridsize - sectorsize) / 2);

            for (int x = (int)outerleft; x < (int)outerright; x += (int)gridsize)
            {
                for (int y = (int)outertop; y > (int)outerbottom; y -= (int)gridsize)
                {
                    List <BlockEntry> blocks = blockmap.GetLineBlocks(
                        new Vector2D(x + 1, y - 1),
                        new Vector2D(x + gridsize - 1, y - gridsize + 1)
                        );

                    // The way our blockmap is built and queried we will always get exactly one block
                    if (blocks[0].Sectors.Count == 0)
                    {
                        positions.Add(new Vector2D(x + margin, y - margin));
                        numsectors--;
                    }

                    if (numsectors == 0)
                    {
                        return(positions);
                    }
                }
            }

            throw new Exception("Not enough space for control sector relocation");
        }
Пример #16
0
    private void BlockContrller()
    {
        RaycastHit hitInfo;

        if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hitInfo, 10f))
        {
            Vector3 pos = hitInfo.point - hitInfo.normal / 2;
            //Vector3 pos = new Vector3(hitX, hitY, hitZ);
            _hightBlock.transform.position = DataUtil.CeilToInt(pos);

            if (Input.GetMouseButton(0))
            {
                Chunk6Load chunk = GetChunkByWorldPos(DataUtil.CeilToInt(pos));
                chunk.SetBlock(pos, null);
            }
            else if (Input.GetKeyDown(KeyCode.Q))
            {
                pos = hitInfo.point + hitInfo.normal / 2;
                Chunk6Load chunk = GetChunkByWorldPos(DataUtil.CeilToInt(pos));
                chunk.SetBlock(pos, BlockMap.GetBlock("TNT"));
            }
        }
        else
        {
            _hightBlock.transform.position = new Vector3(10000, 10000, 10000);
        }
    }
Пример #17
0
        public List <DrawnVertex> GetNewControlSectorVertices()
        {
            BlockMap <BlockEntry> blockmap = CreateBlockmap();

            int margin = (int)((gridsize - sectorsize) / 2);

            // find position for new control sector
            for (int x = (int)outerleft; x < (int)outerright; x += (int)gridsize)
            {
                for (int y = (int)outertop; y > (int)outerbottom; y -= (int)gridsize)
                {
                    List <BlockEntry> blocks = blockmap.GetLineBlocks(
                        new Vector2D(x + 1, y - 1),
                        new Vector2D(x + gridsize - 1, y - gridsize + 1)
                        );

                    // The way our blockmap is built and queried we will always get exactly one block
                    if (blocks[0].Sectors.Count == 0)
                    {
                        List <DrawnVertex> dv = new List <DrawnVertex>();
                        Point p = new Point(x + margin, y - margin);

                        dv.Add(SectorVertex(p.X, p.Y));
                        dv.Add(SectorVertex(p.X + BuilderPlug.Me.ControlSectorArea.SectorSize, p.Y));
                        dv.Add(SectorVertex(p.X + BuilderPlug.Me.ControlSectorArea.SectorSize, p.Y - BuilderPlug.Me.ControlSectorArea.SectorSize));
                        dv.Add(SectorVertex(p.X, p.Y - BuilderPlug.Me.ControlSectorArea.SectorSize));
                        dv.Add(SectorVertex(p.X, p.Y));

                        return(dv);
                    }
                }
            }

            throw new Exception("No space left for control sectors");
        }
Пример #18
0
		/// <summary>
		///Returns an empty block (useful for deleting blocks but retaining trigger functionality) 
		/// </summary>
		/// <param name="map">
		/// The map to which this block will be added (required in order to correctly size the trigger of the block)
		/// </param>
		/// <returns>
		/// Returns an empty block
		/// </returns>
		public static Block GetEmptyBlock(BlockMap map){
			
			GameObject o = null;
			
			if(AssetPool.IsPoolingEnabled()){
				
				o = AssetPool.Instantiate("Void");
				
				if(o != null){
					return o.GetComponent<Block>();
				}
				
			}
			
			o = new GameObject("Void");
			OrientedBlock ob = o.AddComponent<OrientedBlock>();
			BoxCollider b = o.AddComponent<BoxCollider>();
			b.isTrigger = true;
			b.size = map.tileScale;
			ob.isNullBlock = true;
			ob.actAsEmptyBlock = true;
			return ob as Block;
		
			
		}
Пример #19
0
        private BlockMap <BlockEntry> CreateBlockmap(bool ignorecontrolsectors)
        {
            // Make blockmap
            RectangleF area = MapSet.CreateArea(General.Map.Map.Vertices);

            area = MapSet.IncreaseArea(area, new Vector2D(outerleft, outertop));
            area = MapSet.IncreaseArea(area, new Vector2D(outerright, outerbottom));
            area = AlignAreaToGrid(area);

            BlockMap <BlockEntry> blockmap = new BlockMap <BlockEntry>(area, (int)gridsize);

            if (ignorecontrolsectors)
            {
                foreach (Sector s in General.Map.Map.Sectors)
                {
                    // Managed control sectors have the custom UDMF field "user_managed_3d_floor" set to true
                    // So if the field is NOT set, add the sector to the blockmap
                    if (s.Fields.GetValue("user_managed_3d_floor", false) == false)
                    {
                        blockmap.AddSector(s);
                    }
                }
            }
            else
            {
                blockmap.AddSectorsSet(General.Map.Map.Sectors);
            }

            return(blockmap);
        }
Пример #20
0
 /// <summary>
 /// 预处理地形的函数
 /// 通过不同的算法产生地形数据
 /// </summary>
 private void CalculateMap()
 {
     _map = new Block[length, height, width];
     for (int x = 0; x < length; x++)
     {
         for (int y = 0; y < height; y++)
         {
             for (int z = 0; z < width; z++)
             {
                 Block block = GetTheoreticalBlock(new Vector3(x, y, z) + transform.position);
                 if (block != null)
                 {
                     if (GetTheoreticalBlock(new Vector3(x, y + 1, z) + transform.position) == null)
                     {
                         _map[x, y, z] = BlockMap.GetBlock("Grass");
                     }
                     else
                     {
                         _map[x, y, z] = BlockMap.GetBlock("Dirt");
                     }
                 }
             }
         }
     }
     //yield return null;
     StartCoroutine(CalculateMesh());
 }
Пример #21
0
	void Awake(){
		
		//First we will create our map using the parameters we have set
		createdMap = BlockUtilities.CreateBlockMap(mapName,tileSize,chunkWidth,chunkHeight,growthAxis);
		
		//Now we will create a big old block of cubes, according to the dimensions we've set above
		for(int x = 0; x < levelWidth; x++){
			for(int y = 0; y < levelWidth; y++){
				for(int z = 0; z < levelDepth; z++){
					
					//We instantiate the block outside of the BlockUtilites library
					//I've made it this way to allow you to pool GameObjects or anything you like 
					//So you have control over where your blocks come from
					Block b = GameObject.Instantiate(blockPrefab) as Block;
					
					//Now we add the block to the map at the desired coordinates
					//We won't randomise or refresh at this point, as we're creating a large map
					//We will do that as one call later
					BlockUtilities.AddBlockToMap(createdMap,b,false,0,false,x,y,z,false,true);
				}
			}
		}
		
		//Now that our map has been created, we will refresh it
		//Refreshing your map sets your blocks to orient correctly
		//And gives you an opportunity to randomise your variants en'masse
		BlockUtilities.RefreshMap(createdMap,randomiseInitialMap);
		
		
	}
Пример #22
0
        private static int[,,] ComputeSmoothedHistogram(BlockMap blocks, int[,,] input)
        {
            var blocksAround = new[] { new Point(0, 0), new Point(-1, 0), new Point(0, -1), new Point(-1, -1) };
            var output       = new int[blocks.CornerCount.Y, blocks.CornerCount.X, 256];

            foreach (var corner in blocks.AllCorners)
            {
                foreach (var relative in blocksAround)
                {
                    var block = corner + relative;

                    if (!blocks.AllBlocks.Contains(block))
                    {
                        continue;
                    }

                    for (var i = 0; i < 256; ++i)
                    {
                        output[corner.Y, corner.X, i] += input[block.Y, block.X, i];
                    }
                }
            }

            return(output);
        }
Пример #23
0
    private void BlockContrllre()
    {
        RaycastHit hitInfo;

        if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hitInfo, 10f))
        {
            Vector3 pos = hitInfo.point - hitInfo.normal / 2;
            //Vector3 pos = new Vector3(hitX, hitY, hitZ);
            _hightBlock.transform.position = new Vector3(
                Mathf.FloorToInt(pos.x), Mathf.FloorToInt(pos.y), Mathf.FloorToInt(pos.z));

            if (Input.GetMouseButtonDown(0))
            {
                Chunk5Ctrl chunk = Chunk5Ctrl.GetChunk(FloorToIntVector3(pos));
                chunk.SetChunk(pos, null);
            }
            else if (Input.GetKeyDown(KeyCode.Q))
            {
                pos = hitInfo.point + hitInfo.normal / 2;
                Chunk5Ctrl chunk = Chunk5Ctrl.GetChunk(FloorToIntVector3(pos));
                chunk.SetChunk(pos, BlockMap.GetBlock("TNT"));
            }
        }
        else
        {
            _hightBlock.transform.position = new Vector3(10000, 10000, 10000);
        }
    }
Пример #24
0
 /// <summary>
 /// 预处理地形的函数
 /// 通过不同的算法产生地形数据
 /// </summary>
 private void CalcuateMap()
 {
     for (int x = 0; x < length; x++)
     {
         for (int y = 0; y < height; y++)
         {
             for (int z = 0; z < width; z++)
             {
                 Block block = GetTheoreticalBlock(new Vector3(x, y, z) + _selfPos);
                 if (block != null)
                 {
                     if (GetTheoreticalBlock(new Vector3(x, y + 1, z) + _selfPos) == null &&
                         block == BlockMap.GetBlock("Dirt"))
                     {
                         _map[x, y, z] = BlockMap.GetBlock("Grass");
                     }
                     else
                     {
                         _map[x, y, z] = block;
                     }
                 }
             }
         }
     }
 }
Пример #25
0
        /// <summary>
        /// Cleans a single block
        /// </summary>
        /// <param name="map">
        /// The map containing the target block
        /// </param>
        /// <param name="x">
        /// The x coordinate of the target block
        /// </param>
        /// <param name="y">
        /// The y coordinate of the target block
        /// </param>
        /// <param name="depth">
        /// The depth coordinate of the target block
        /// </param>
        public static void CleanBlock(BlockMap map, int x, int y, int depth)
        {
            Block b = map.GetBlockAt(x, y, depth);

            if (b != null)
            {
                OrientedBlock ob = (OrientedBlock)b;

                if (ob == null)
                {
                    return;
                }

                BlockSet[] bs = ob.GetBlockSetsAsArray();

                BlockSet currentSet = ob.GetCurrentBlockSet();

                for (int k = 0; k < bs.Length; k++)
                {
                    if (bs[k] == currentSet)
                    {
                        continue;
                    }

                    BlockSet bSet = bs[k];

                    for (int l = 0; l < bSet.blockSet.Length; l++)
                    {
                        GameObject.Destroy(bSet.blockSet[l].gameObject);
                    }
                }
            }
        }
Пример #26
0
        /// <summary>
        /// Is this point within the bounds of the map?
        /// </summary>
        /// <param name="map">
        /// The map we wish to query
        /// </param>
        /// <param name="x">
        /// The test X coordinate
        /// </param>
        /// <param name="y">
        /// The test Y coordinate
        /// </param>
        /// <param name="z">
        /// The test z coordinate
        /// </param>
        /// <returns>
        /// True if the point lies within the bounds of the map, false if otherwise.
        /// </returns>
        public static bool IsWithinMapBounds(BlockMap map, int x, int y, int z)
        {
            int lowerXBound = 0;
            int lowerYBound = 0;

            int upperXBound = GetMapWidth(map);
            int upperYBound = GetMapHeight(map);

            if (map.editorMap)
            {
                lowerXBound = map.chunkWidth;
                lowerYBound = map.chunkHeight;
                upperXBound = upperXBound - map.chunkWidth;
                upperYBound = upperYBound - map.chunkHeight;
            }

            if (x < lowerXBound || (x >= upperXBound))
            {
                return(false);
            }

            if (y < lowerYBound || (y >= upperYBound))
            {
                return(false);
            }

            if (z < GetMapLowerDepth(map) || z > GetMapUpperDepth(map))
            {
                return(false);
            }

            return(true);
        }
Пример #27
0
        private static byte[,] ComputeOrientationMap(double[,] image, bool[,] mask, BlockMap blocks)
        {
            var accumulated = ComputePixelwiseOrientation(image, mask, blocks);
            var byBlock     = AverageBlockOrientations(accumulated, blocks, mask);
            var smooth      = SmoothOutOrientationMap(byBlock, mask);

            return(ConvertOrientationVectorsToAngles(smooth, mask));
        }
Пример #28
0
 private BlockMap(BlockMap other)
 {
     id        = other.id;
     minimized = other.minimized;
     texture   = other.texture;
     exitColor = other.exitColor;
     //unshareableColors = new List<Color>(other.unshareableColors);
 }
Пример #29
0
 public void Unload()
 {
     if (mapInstance != null)
     {
         GameObject.Destroy(mapInstance.gameObject);
         mapInstance = null;
     }
 }
Пример #30
0
 public void Unload()
 {
     if( mapInstance != null )
     {
         GameObject.Destroy( mapInstance.gameObject );
         mapInstance = null;
     }
 }
    //We must initialize the entity to the map that we wish to use, if it's not been
    //done via parameters
    public void InitializeEntity(BlockMap map)
    {
        this.parentMap = map;

        InitializeEntity();

        OnInitializeEntity();
    }
Пример #32
0
    void TickSLA()
    {
        foreach (var block in board.GetBlocks())
        {
            block.Satisfied = false;
        }
        BlockMap blocks           = new BlockMap(board.GetBlocks());
        bool     everythingIsFine = true;

        foreach (var feature in featureManager.GetFeatures())
        {
            var satisfied = feature.CheckSatisfied(blocks);
            if (!satisfied)
            {
                if (!feature.Beta)
                {
                    sla -= feature.SLAEffect;
                    everythingIsFine = false;
                }
                feature.MarkAsUnSatisfied();
            }
            else
            {
                if (feature.Beta)
                {
                    feature.Beta = false;
                }
                money += feature.Income;
                if (!feature.LastSatisfied)
                {
                    feature.MarkAsSatisfied();
                    tadaSound.Play();
                }
            }
            feature.LastSatisfied = satisfied;
        }
        if (everythingIsFine)
        {
            sla += slaRecoverSpeed;
        }
        sla = Mathf.Clamp(sla, 0, maxSLA);
        var slaPercent = 100 * sla / maxSLA;

        slaPercentText.text = string.Format("{0}%", slaPercent);

        var blockCount = blocks.Count();

        if (state == State.Begun)
        {
            blockCount--;
        }
        money -= blockCount;
        if (money < 0)
        {
            money = 0;
        }
        moneyText.text = string.Format("${0}", money);
    }
Пример #33
0
 public byte[,] Detect(float[,] image, BinaryMap mask, BlockMap blocks)
 {
     PointF[,] accumulated = AccumulateOrientations(image, mask, blocks);
     PointF[,] byBlock     = SumBlocks(accumulated, blocks, mask);
     PointF[,] smooth      = Smooth(byBlock, mask);
     byte[,] angles        = ToAngles(smooth, mask);
     Logger.Log(angles);
     return(angles);
 }
Пример #34
0
	//We must initialize the entity to the map that we wish to use, if it's not been
	//done via parameters
	public void InitializeEntity(BlockMap map){
		
		this.parentMap = map;
		
		InitializeEntity();
		
		OnInitializeEntity();
		
	}
Пример #35
0
    void Awake()
    {
        //Make the map, it still needs to be populated
        map = BlockUtilities.CreateBlockMap(mapName, tileScale, 5, 5, growthAxis);

        //Performance: Pooling allows blocks to be disabled/enabled instead of destroyed/created
        AssetPool.EnablePooling();

        GenerateMap();
    }
Пример #36
0
    /// <summary>
    ///Binds this block to its parent map, and sets its initial x,y coords. 
    /// </summary>
    /// <param name="x">
    /// Initial x coordinate for this block
    /// </param>
    /// <param name="y">
    /// Initial y coordinate for this block
    /// </param>
    /// <param name="blockMap">
    /// The blockmap to which this block will be bound
    /// </param>
    public void BindToMap(int x, int y, int depth, BlockMap blockMap)
    {
        this.x = x;
        this.y = y;
        this.depth = depth;
        this.blockMap = blockMap;

        OnBindToMap(x,y,depth,blockMap);

        BindChildrenToBlock();
    }
        public void CreateScatterGatherStreams(int capacity, TimeSpan timeout, out Stream scatterStream, out Stream gatherStream)
        {
            if (capacity <= 0)
                throw new ArgumentOutOfRangeException(nameof(capacity), $"{nameof(capacity)} must be positive.");
            if (timeout < defaultTimeout)
                throw new ArgumentOutOfRangeException(nameof(timeout), $"{nameof(timeout)} must be greater than {defaultTimeout:c}.");

            var buffer = new byte[capacity];
            var assignedBlocks = new BlockMap(capacity);
            scatterStream = new ScatterStream(buffer, assignedBlocks, timeout);
            gatherStream = new GatherStream(buffer, assignedBlocks, timeout);
        }
Пример #38
0
		/// <summary>
		///Create a new Block Map  
		/// </summary>
		/// <param name="mapName">
		/// The name of your new block map
		/// </param>
		/// <param name="tileScale">
		/// The scale of the tiles within your new blockmap
		/// </param>
		/// <param name="chunkWidth">
		/// The width of the chunks within your new blockmap (Recommend: 5)
		/// </param>
		/// <param name="chunkHeight">
		/// The height of the chunks within your new blockmap (Recommend: 5)
		/// </param>
		/// <param name="growthAxis">
		/// The direction in which your new blockmap will grow when blocks are added to it
		/// </param>
		/// <returns>
		/// Your shiny, new blockmap
		/// </returns>
		public static BlockMap CreateBlockMap(string mapName, Vector3 tileScale, int chunkWidth, int chunkHeight, BlockMap.GrowthAxis growthAxis){
			
			GameObject o = new GameObject(mapName);
			
			BlockMap bm = o.AddComponent<BlockMap>();
			
			bm.tileScale = tileScale;
			bm.chunkWidth = chunkWidth;
			bm.chunkHeight = chunkHeight;
			bm.growthAxis = growthAxis;
						
			bm.editorMap = false;
			bm.hasBeenPublished = true;
			
			return bm;
			
		}
Пример #39
0
	//We'll construct the map here
	void ConstructLevel(){
		
		bool[,] map = GetLevelMap(levelWidth, levelHeight);
				
		//We'll go ahead and create our map now
		createdMap = BlockUtilities.CreateBlockMap(mapName,tileSize,chunkWidth,chunkHeight,growthAxis);
		
		//We're just going to iterate through the level we got back from the
		//function (trusting that it's correctly sized)
		for(int x = 0; x < levelWidth; x++){
			for(int y = 0; y < levelHeight; y++){
				
				if(map[x,y]){
					
					Block b = GameObject.Instantiate(blockPrefab) as Block;
					
					//We'll add our instantiated block here
					//And we will not refresh just yet -
					//it's better to refresh and clean at the end
					BlockUtilities.AddBlockToMap(createdMap,b,false,0,false,x,y,0,false,false);
					
				}
				else{
					
					if(useEmptyBlocks){
						BlockUtilities.AddBlockToMap(createdMap,null,false,0,false,x,y,0,false,true);
					}
					
				}
				
			}
		}
		
		//And now we refresh our map
		BlockUtilities.RefreshMap(createdMap,randomiseInitialMap);
				
		//Done!
		//Enjoy!
		
	}
Пример #40
0
		public void SetEntireMapDirty(BlockMap map){
			
			if(map.functionalOverlay != null){
				EditorUtility.SetDirty(map.functionalOverlay);
			}
			
			for(int i = 0; i < map.map.Length; i++){
				
				ChunkSet cs = map.map[i];
				
				if(cs != null){
					
					if(cs.HasChunks()){
						
						for(int j = 0; j < cs.chunkSet.Length; j++){
							
							MapChunk m = cs.chunkSet[j].chunk;
							
							if(m != null){
							
								EditorUtility.SetDirty(m);
								
								if(m.chunkPieces != null){
								
									for(int k = 0; k < m.chunkPieces.Length; k++){
										
										Block b = m.chunkPieces[k];
										
										if(b != null){
											EditorUtility.SetDirty(b);
										}
										
									}
									
								}
								
							}
							
						}
						
					}
					
				}
				
			}
			
		}
Пример #41
0
		void DrawVisibilityForMap(BlockMap map){
			
			Color c = GUI.color;
			
			bool viewAll = mapViewAll[map.name];
			
			if(viewAll){
				GUI.color = Color.green;
			}
			
			EditorGUILayout.BeginHorizontal();
			
			if(GUILayout.Button("View All Layers")){
				if(!viewAll){
					map.ShowAllLayers();
					mapViewAll[map.name] = true;
				}
			}
			
			GUI.color = c;
			
			if(!mapUnlockAll.ContainsKey(map.name)){
				mapUnlockAll.Add(map.name,true);
			}
			
			mapUnlockAll[map.name] = EditorGUILayout.Toggle(mapUnlockAll[map.name]);
			
			if(mapUnlockAll[map.name]){
				mapLayerLock.Clear();
			}
			
			EditorGUILayout.EndHorizontal();
			
			if(!mapLayerVisibility.ContainsKey(map.name)){
				mapLayerVisibility.Add(map.name,0);
			}
			
			int viewedLayer = mapLayerVisibility[map.name];
			
			for(int i = map.mapLowerDepth; i <= map.mapUpperDepth; i++){
				
				if(!viewAll && viewedLayer == i){
					GUI.color = Color.green;
				}
			
				EditorGUILayout.BeginHorizontal();
				
				if(GUILayout.Button("Layer " + i)){
					if(viewedLayer != i || viewAll){
						map.ShowLayer(i);
						mapLayerVisibility[map.name] = i;
						mapViewAll[map.name] = false;
					}
				}
				
				GUI.color = c;
				
				if(!mapLayerLock.ContainsKey(map.name + "_" + i)){
					mapLayerLock.Add(map.name + "_" + i,false);
				}
				
				mapLayerLock[map.name + "_" + i] = EditorGUILayout.Toggle(mapLayerLock[map.name + "_" + i]);
				
				if(mapLayerLock[map.name + "_" + i]){
					
					
					mapUnlockAll[map.name] = false;
				}
				
				EditorGUILayout.EndHorizontal();
				
			}
			
		}
Пример #42
0
		void CleanMap(BlockMap blockMap){
			
			ChunkSet[] map = blockMap.map;
			
			//Strip empty blocks and such
			for(int i = 0; i < map.Length; i++){
				
				if(map[i] != null){
					
					for(int c = 0; c < map[i].chunkSet.Length; c++){
					
						MapChunk m = map[i].chunkSet[c].chunk;
						
						//Delete empty chunks
						if(m.chunkPieces == null || m.chunkPieces.Length <= 0){
							
							if(selectedStrippingLevel == StrippingLevel.Strip_All){
								Editor.DestroyImmediate(m.gameObject);
							}
							else{
								if(m.GetComponent<Renderer>() != null){
									Editor.DestroyImmediate(m.GetComponent<Renderer>());
								}
								
								MeshFilter mf = m.GetComponent<MeshFilter>();
								
								if(mf != null){
									Editor.DestroyImmediate(mf);
								}
								
								if(m.GetComponent<Collider>() != null){
									Editor.DestroyImmediate(m.GetComponent<Collider>());
								}
							}
							
							continue;
						}
						
						if(m.chunkPieces != null){
							
							for(int j = 0; j < m.chunkPieces.Length; j++){
							
								if(m.chunkPieces[j].isNullBlock){
									
									Block mb = m.chunkPieces[j];
									
									//Debug.Log("Hiding " + mb.x + "," + mb.y);
									mb.Hide();
									
									//Delete things below it on the hierarchy
									for(int d = 0; d < mb.transform.childCount; d++){
										
										GameObject o = mb.transform.GetChild(d).gameObject;
										
										Editor.DestroyImmediate(o);
										
									}
									
									if(selectedStrippingLevel == StrippingLevel.Working_Blocks_Only){
										m.chunkPieces[j].GetComponent<Collider>().isTrigger = true;
									}
									else{
										Editor.DestroyImmediate(m.chunkPieces[j].gameObject);
										continue;
									}
									
									continue;
								}
								else if(!m.chunkPieces[j].retainCollider){
									
									m.chunkPieces[j].GetComponent<Collider>().isTrigger = true;
									
								}
								
							}
							
						}
					}
					
				}
		
			
			}
			
			if(selectedStrippingLevel == StrippingLevel.Strip_All){
				
				OrientedBlock[] blocks = blockMap.GetComponentsInChildren<OrientedBlock>();
				MapChunk[] chunks = blockMap.GetComponentsInChildren<MapChunk>();
				
				for(int i = 0; i < blocks.Length; i++){
					Editor.DestroyImmediate(blocks[i]);
				}
				
				for(int i = 0; i < chunks.Length; i++){
					Editor.DestroyImmediate(chunks[i]);
				}
				
				Editor.DestroyImmediate(blockMap);
				
			}
		}
Пример #43
0
		public void PrePublishMap(BlockMap map){
			
			if(map == null){
				return;
			}
			
			publishOverwrite = false;
			
			if(TidyEditorUtility.DoesMapPrefabExist(map.gameObject)){
				
				if(EditorUtility.DisplayDialog(TidyMessages.MAP_CREATOR_PUBLISH_MAP_EXISTS_TITLE,
				                               TidyMessages.MAP_CREATOR_PUBLISH_MAP_EXISTS_INFO,
				                               TidyMessages.MAP_CREATOR_PUBLISH_MAP_EXISTS_OVERWRITE,
				                               TidyMessages.MAP_CREATOR_PUBLISH_MAP_EXISTS_DONT_OVERWRITE
				                               )){
					//overwrite
					publishOverwrite = true;
				}
				else{
					//don't overwrite
					publishOverwrite = false;
				}
			}
			else{
				publishOverwrite = true;
			}
			
			publishMap = map;
			
			shouldPublish = true;
			hasUpdated = false;
			
			mapPublishStatus = TidyMessages.PUBLISH_UTILITY_BUILDING;
			
			parentWindow.ShowNotification(new GUIContent(TidyMessages.PUBLISH_UTILITY_NOTIFICATION));
			
			parentWindow.Repaint();
		}
	public void BindToMap(BlockMap map, Block b){
		this.parentMap = map;
		this.parentBlock = b;
		
		OnBindToMap(map,b);
	}
Пример #45
0
		/// <summary>
		/// Returns the local position of the given coordinate (useful for character movement) 
		/// </summary>
		/// <param name="map">
		/// The map from which you wish to retrieve the position
		/// </param>
		/// <param name="x">
		/// The block x coordinate
		/// </param>
		/// <param name="y">
		/// The block y coordinate
		/// </param>
		/// <param name="depth">
		/// The block depth coordinate
		/// </param>
		/// <returns>
		/// The local position that is central to this block coordinate
		/// </returns>
		public static Vector3 GetMathematicalPosition(BlockMap map, int x, int y, int depth){
			
			Vector3 position = Vector3.zero;
						
			float halfChunk_x = (float)(map.chunkWidth) * map.tileScale.x * 0.5f;
			
			if(map.editorMap){
				MapChunk c = map.GetLeftMostMapChunk();
				if(c != null){
					halfChunk_x += c.transform.localPosition.x;
				}
				
			}
			
			float halfChunk_y = 0.0f;
			
			//Vector3 upperLeft = Vector3.zero;
			
			if(map.growthAxis == BlockMap.GrowthAxis.Up){
				halfChunk_y = (float)(map.chunkHeight) * map.tileScale.y * 0.5f;
				
				MapChunk c = map.GetTopMostMapChunk();
				if(c != null){
					
					halfChunk_y += c.transform.localPosition.y;
					
				}
				
				position.y = -(y * map.tileScale.y + (0.5f * map.tileScale.y) - halfChunk_y);
				position.z = depth * map.tileScale.z;
			}
			else{
				halfChunk_y = (float)(map.chunkHeight) * map.tileScale.z * 0.5f;
				
				MapChunk c = map.GetTopMostMapChunk();
				if(c != null){
					halfChunk_y += c.transform.localPosition.z;
				}
				
				position.z = -(y * map.tileScale.z + (0.5f * map.tileScale.z) - halfChunk_y);
				position.y = depth * map.tileScale.y;
			}
			
			position.x = -((x * map.tileScale.x) + (0.5f * map.tileScale.x) - halfChunk_x);
			
			
			return position;
			
		}
Пример #46
0
		/// <summary>
		/// Create a save string from the provided BlockMap 
		/// </summary>
		/// <param name="map">
		/// The BlockMap from which to create a save string.
		/// </param>
		/// <returns>
		/// The save string representing this BlockMap.
		/// </returns>
		public static string BlockmapToString(BlockMap map){
			
			string mapString = "";
			
			//Add the map name
			mapString += map.name + MAP_STRING_FIELD_DELIM;
			//Add the tile scale			
			mapString += map.tileScale.x + "," + map.tileScale.y + "," + map.tileScale.z + MAP_STRING_FIELD_DELIM;
			//Add the chunk width
			mapString += map.chunkWidth + ""+ MAP_STRING_FIELD_DELIM;
			//Add the chunk height
			mapString += map.chunkHeight + ""+ MAP_STRING_FIELD_DELIM;
			//Add the growth axis
			mapString += ((int)map.growthAxis) + ""+ MAP_STRING_FIELD_DELIM;
						
			int lowerDepth = BlockUtilities.GetMapLowerDepth(map);
			int upperDepth = BlockUtilities.GetMapUpperDepth(map);
			int width = BlockUtilities.GetMapWidth(map);
			int height = BlockUtilities.GetMapHeight(map);
			
			//Now add the map height and width and upper and lower depth
			mapString += width + ""+ MAP_STRING_FIELD_DELIM + ""+ height + ""+MAP_STRING_FIELD_DELIM;
			mapString += lowerDepth + ""+ MAP_STRING_FIELD_DELIM + ""+ upperDepth + ""+ MAP_STRING_FIELD_DELIM;
			
			//Now we need to populate our block library
			List<string> blockLibrary = new List<string>();
						
			for(int z = lowerDepth; z <= upperDepth; z++){
				
				for(int x = 0; x < width; x++){
					
					for(int y = 0; y < height; y++){
					
						Block b = BlockUtilities.GetBlockAt(map,x,y,z);
						
						if(b != null && !b.isNullBlock){
							
							if(!blockLibrary.Contains(b.name)){
								blockLibrary.Add(b.name);
							}
							
						}
					}
					
				}				
			}
			
			//Debug only
			string blockStr = "Populated block library: ";
			
			for(int i = 0; i < blockLibrary.Count; i++){
				
				//Debug only
				blockStr += blockLibrary[i] + ",";
				
				mapString += blockLibrary[i] + BLOCK_FIELD_DELIM;
			}
			
			mapString += MAP_STRING_FIELD_DELIM;
						
			Debug.Log(blockStr);
			
			for(int z = lowerDepth; z <= upperDepth; z++){
				
				for(int x = 0; x < width; x++){
					
					for(int y = 0; y < height; y++){
					
						Block b = BlockUtilities.GetBlockAt(map,x,y,z);
						
						if(b != null && !b.isNullBlock){
							
							mapString += BlockUtilities.BlockToString(b,blockLibrary);
														
						}
						else{
							
							mapString += "-1" + BLOCK_FIELD_DELIM + "0" + BLOCK_FIELD_DELIM +""+ x +"," +y+","+z+""+BLOCK_FIELD_DELIM;
							
						}
						
						mapString += MAP_STRING_FIELD_DELIM;
					}
					
				}				
			}
						
			return mapString;
			
		}
Пример #47
0
		void DrawPath(Vector2 a, Vector2 b, BlockMap pathMap, int depth){
			
			List<PathNode> path = PathFinding.GetPath((int)a.x,(int)a.y,(int)b.x,(int)b.y,pathMap,depth,pathAllowDiagonals,pathRandomisation,1000,true);
			
			if(path != null){
				
				BlockMap bm = pathMap;
								
				Block ba = bm.GetBlockAt((int)a.x,(int)a.y,depth);
				Block bb = bm.GetBlockAt((int)b.x,(int)b.y,depth);
				
				if(ba == null){
					Debug.LogWarning("Null path block at: " + a.x + "," + a.y + " - aborting.");
					return;
				}
				
				if(bb == null){
					Debug.LogWarning("Null path block at: " + b.x + "," + b.y + " - aborting.");
					return;
				}
				
				//set the start and end nodes, as they don't come back with the path
				//PaintBlock(ba, false);
				//PaintBlock(bb, false);
				
				
				int upper_val, lower_val;
				
				upper_val = (int)(pathWidth / 2.0f);
				lower_val = upper_val;
				
				if(pathWidth % 2 != 0){
					upper_val += 1;
				}
				
				
				for(int x = ba.x-lower_val; x < ba.x+upper_val; x++){
						
					for(int y = ba.y-lower_val; y < ba.y+upper_val; y++){
				
						Block pB = bm.GetBlockAt(x,y,depth);
						
						if(pB != null){
							PaintBlock(pB,false);
						}
						
					}	
					
				}
				
				for(int x = bb.x-lower_val; x < bb.x+upper_val; x++){
						
					for(int y = bb.y-lower_val; y < bb.y+upper_val; y++){
				
						Block pB = bm.GetBlockAt(x,y,depth);
						
						if(pB != null){
							PaintBlock(pB,false);
						}
						
					}	
					
				}
				
				for(int i = 0; i < path.Count; i++){
															
					for(int x = path[i].x-lower_val; x < path[i].x+upper_val; x++){
						
						for(int y = path[i].y-lower_val; y < path[i].y+upper_val; y++){
					
							Block pB = bm.GetBlockAt(x,y,depth);
							
							if(pB != null){
								PaintBlock(pB,false);
							}
							
						}	
						
					}
				}
				
			}
			else{
				Debug.LogWarning("No path could be found between " + a.ToString() + " and " + b.ToString());
			}
			
		}
Пример #48
0
        private BlockMap CreateBlockMap(Point worldDimensions, List<Block> tiles)
        {
            BlockMap map = new BlockMap(
                worldDimensions.X / Definitions.Grid_Cell_Pixel_Size,
                worldDimensions.Y / Definitions.Grid_Cell_Pixel_Size,
                Definitions.Grid_Cell_Pixel_Size,
                Definitions.Grid_Cell_Pixel_Size,
                Map_Render_Layer);

            for (int i = 0; i < tiles.Count; i++)
            {
                map.SetTile(
                    (int)(tiles[i].WorldPosition.X / Definitions.Grid_Cell_Pixel_Size),
                    (int)(tiles[i].WorldPosition.Y / Definitions.Grid_Cell_Pixel_Size),
                    tiles[i]);
            }

            for (int i = 0; i < _bombs.Count; i++ )
            {
                _bombs[i].Map = map;
                _bombs[i].MapLocation = new Point(
                    (int)(_bombs[i].WorldPosition.X / Definitions.Grid_Cell_Pixel_Size),
                    (int)(_bombs[i].WorldPosition.Y / Definitions.Grid_Cell_Pixel_Size));
            }

            return map;
        }
Пример #49
0
    /// <summary>
    /// Activate the chunk at this coordinate - this comes before initializing
    /// </summary>
    /// <param name="width">
    ///The width of this chunk in blocks
    /// </param>
    /// <param name="height">
    ///The height of this chunk in blocks
    /// </param>
    /// <param name="parentMap">
    ///The map to which this chunk should be bound
    /// </param>
    public void Editor_Activate(int width, int height, int x, int y, int depth, BlockMap parentMap, bool positionAbsolute)
    {
        this.parentMap = parentMap;
        this.width = width;
        this.height = height;

        this.x = x;
        this.y = y;
        this.depth = depth;

        if(!positionAbsolute){

            for(int x1 = this.x-1; x1 <= this.x+1; x1++){
                for(int y1 = this.y-1; y1 <= this.y+1; y1++){

                    if(x1 == x && y1 == y){
                        continue;
                    }

                    if(parentMap.HasChunkAt(x1,y1,depth)){

                        MapChunk chunk = parentMap.GetChunkAt(x1,y1,depth,false);

                        int difference_x = x1 - this.x;
                        int difference_y = y1 - this.y;

                        Vector3 pos = Vector3.zero;

                        transform.parent = parentMap.transform;

                        transform.localPosition = pos;

                        float diff_dist_x = difference_x * (parentMap.tileScale.x * width);
                        float diff_dist_y = -(difference_y * (parentMap.tileScale.y * height));

                        if(parentMap.growthAxis == BlockMap.GrowthAxis.Up){

                            pos = new Vector3(
                                                      chunk.transform.localPosition.x + diff_dist_x,
                                                      chunk.transform.localPosition.y - diff_dist_y,
                                                      (depth * parentMap.tileScale.z)
                                                      );

                            transform.localRotation = Quaternion.identity;

                        }
                        else if(parentMap.growthAxis == BlockMap.GrowthAxis.Forward ){

                            pos = new Vector3(
                                                      chunk.transform.localPosition.x + diff_dist_x,
                                              		  (depth * parentMap.tileScale.z),
                                                      chunk.transform.localPosition.z - diff_dist_y
                                                      );

                            transform.localRotation = Quaternion.Euler(
                                                                       new Vector3(
                                                                                   90.0f,
                                                                                   0.0f,
                                                                                   0.0f
                                                                                   ));

                        }

                        transform.localPosition = pos;

                        transform.localScale = new Vector3(
                                                           parentMap.tileScale.x * width,
                                                           parentMap.tileScale.y * height,
                                                           parentMap.tileScale.z
                                                           );

                        return;
                    }

                }
            }
        }

        Vector3 localPos = Vector3.zero;

        if(positionAbsolute){

            if(parentMap.growthAxis == BlockMap.GrowthAxis.Up){
                localPos = new Vector3(-x * width,-y*height,0.0f);
            }
            else{
                //if(parentMap.growthAxis == BlockMap.GrowthAxis.Up){
                localPos = new Vector3(-x * width,0.0f,-y*height);
                //}
            }
        }

        transform.parent = parentMap.transform;
        transform.localScale = new Vector3(
                                           parentMap.tileScale.x * width,
                                           parentMap.tileScale.y * height,
                                           parentMap.tileScale.z
                                           );

        transform.localPosition = localPos;

        if(parentMap.growthAxis == BlockMap.GrowthAxis.Up){

            transform.localRotation = Quaternion.identity;

        }
        else if(parentMap.growthAxis == BlockMap.GrowthAxis.Forward ){

            transform.localRotation = Quaternion.Euler(
                                                       new Vector3(
                                                                   90.0f,
                                                                   0.0f,
                                                                   0.0f
                                                                   ));

        }
    }
Пример #50
0
        public void DrawScene(SceneView sceneView)
        {
            //Do all of our casting now
            CheckMouseOver();

            if(currentBehaviour != MapPaintBehaviour.Disabled && currentBehaviour != MapPaintBehaviour.Block_Move && currentBehaviour != MapPaintBehaviour.Plugin_Active){
                int controlID = GUIUtility.GetControlID(FocusType.Passive);

                Tools.current = Tool.None;

                if(Event.current.type == EventType.Layout){
                    HandleUtility.AddDefaultControl(controlID);
                }
            }

            if(currentBehaviour == MapPaintBehaviour.Block_Move){

                Tools.current = Tool.Move;

            }

            if(currentBehaviour == MapPaintBehaviour.Edit_Functions){

                for(int i = 0; i < existentBlockMaps.Length; i++){

                    if(existentBlockMaps[i].functionalOverlay == null){

                        continue;
                    }

                    DrawFunctionalOverlays(existentBlockMaps[i]);

                }

                if(functionBlock == null || setTidyTarget){

                    Block b = mouseoverBlock;

                    if(b != null){

                        Color c = Handles.color;

                        Handles.color = Color.yellow;

                        float radius = b.blockMap.tileScale.y * 0.4f;

                        Handles.DrawWireDisc(b.gameObject.transform.position,b.gameObject.transform.forward,radius);

                        Handles.color = c;

                    }
                }

            }

            if(drawingPath && pathBlocks.Count > 0){

                BlockMap pathMap = pathBlocks[0].blockMap;

                float radius = pathMap.tileScale.y * 0.4f;

                Color c = Handles.color;
                Handles.color = Color.green;

                for(int i = 0; i < pathBlocks.Count; i++){

                    Handles.DrawWireDisc(pathBlocks[i].transform.position,pathBlocks[i].transform.forward,radius);

                    if(i > 0){

                        Handles.DrawLine(pathBlocks[i].transform.position,pathBlocks[i-1].transform.position);

                    }

                }

                Handles.color = c;

            }

            //Debug.Log("Handle utility repaint");

            //HandleUtility.Repaint();

            Handles.BeginGUI();

            GUILayout.BeginArea(new Rect(0.0f,0.0f,Screen.width,Screen.height));

            GUILayout.BeginVertical();

            if(currentBehaviour == MapPaintBehaviour.Disabled){

                Color c = GUI.color;

                GUI.color = Color.white;

                GUILayout.Label(TidyMessages.MAP_CREATOR_INACTIVE);

                GUI.color = c;

            }
            else{

                Color c = GUI.color;

                GUI.color = Color.green;

                if(currentBehaviour == MapPaintBehaviour.Cycle){
                    GUILayout.Label(TidyMessages.MAP_CREATOR_CYCLING_ACTIVE);
                }
                else
                if(currentBehaviour == MapPaintBehaviour.Paint){
                    GUILayout.Label(TidyMessages.MAP_CREATOR_PAINTING_ACTIVE);
                }
                else
                if(currentBehaviour == MapPaintBehaviour.Block_Move){
                    GUILayout.Label(TidyMessages.MAP_CREATOR_BLOCK_MOVE_ACTIVE);
                }

                GUI.color = c;

                OutputMouseoverState();
            }

            GUILayout.EndVertical();

            GUILayout.EndArea();

            Handles.EndGUI();

            if(currentBehaviour == MapPaintBehaviour.Block_Move){

                    if(selectedBlock != null && focusMap != null){

                        if(selectedBlock.transform.localPosition != selectedBlockPosition){

                            if(canAct){

                                HandleBlockMove(selectedBlock,selectedBlockPosition);
                                selectedBlockPosition = selectedBlock.transform.localPosition;

                                HasActed();

                            }
                        }

                    }

            }

            bool initializedChunk = false;

            if(currentBehaviour != MapPaintBehaviour.Disabled && currentBehaviour != MapPaintBehaviour.Block_Move){

                if(Event.current.type == EventType.MouseUp || Event.current.type == EventType.mouseUp){

                    leftMouseDown = false;
                    rightMouseDown = false;

                }

                //these things only occur on mousedown
                if(Event.current.type == EventType.mouseDown || Event.current.type == EventType.MouseDown && (SceneView.currentDrawingSceneView.position.Contains(Event.current.mousePosition))){

                    //only on left click
                    if(Event.current.button == 0){

                        rightMouseDown = false;

                        leftMouseDown = true;

                        if(currentBehaviour == MapPaintBehaviour.DrawPath){

                            if(mouseoverBlock != null){

                                if(CanAddToPath(mouseoverBlock)){
                                    pathBlocks.Add(mouseoverBlock);
                                    drawingPath = true;
                                }

                            }

                        }
                        else
                        if(currentBehaviour == MapPaintBehaviour.Paint || currentBehaviour == MapPaintBehaviour.Cycle){

                            //we are changing a chunk!
                            if(mouseoverChunk != null){
                                BlockMap map = mouseoverChunk.GetParentMap();

                                focusMap = map;

                                OrientedBlock[] defaultBlocks = new OrientedBlock[map.chunkWidth*map.chunkHeight];

                                bool isEmptyBlock = TidyEditorUtility.IsEmptyBlock(workingBlock);

                                TriggerSelection();

                                for(int i = 0; i < defaultBlocks.Length; i++){

                                    //defaultBlocks[i] = EditorUtility.InstantiatePrefab(workingBlock) as OrientedBlock;

                                    if(isEmptyBlock){

                                        defaultBlocks[i] = GameObject.Instantiate(workingBlock) as OrientedBlock;

                                        defaultBlocks[i].name = workingBlock.name;

                                        if(map.growthAxis == BlockMap.GrowthAxis.Up){

                                            defaultBlocks[i].transform.localScale = new Vector3(map.tileScale.x,map.tileScale.y,map.tileScale.z);

                                        }
                                        else if(map.growthAxis == BlockMap.GrowthAxis.Forward){

                                            defaultBlocks[i].transform.localScale = new Vector3(map.tileScale.x,map.tileScale.z,map.tileScale.y);

                                        }

                                    }
                                    else{

                                        defaultBlocks[i] = PrefabUtility.InstantiatePrefab(workingBlock) as OrientedBlock;

                                        defaultBlocks[i].name = workingBlock.name;

                                        BoxCollider b = defaultBlocks[i].GetComponent<BoxCollider>();

                                        if(map.growthAxis == BlockMap.GrowthAxis.Up){
                                            b.size = new Vector3(map.tileScale.x,map.tileScale.y,map.tileScale.z);
                                        }
                                        else{
                                            b.size = new Vector3(map.tileScale.x,map.tileScale.z,map.tileScale.y);
                                        }
                                    }
                                }

                                int depth = mouseoverChunk.depth;

                                //MapChunk mc = map.GetChunkAt(mouseoverChunk.GetX(),mouseoverChunk.GetY(),depth,false);

                                map.Editor_InitializeChunkAt(mouseoverChunk.GetX(),mouseoverChunk.GetY(),depth,defaultBlocks,TidyEditorUtility.GetMapChunkPrefab());

                                HasActed();

                                initializedChunk = true;

                                //and then refresh the blocks around it

                                int m_x = mouseoverChunk.GetX();
                                int m_y = mouseoverChunk.GetY();

                                //MapChunk adjacentChunk = null;

                                for(int x = m_x-1; x <= m_x+1; x++){
                                    for(int y = m_y-1; y <= m_y+1; y++){

                                        MapChunk m = mouseoverChunk.parentMap.GetChunkAt(x,y,depth,false);

                                        if(m != null && m.Editor_IsInitialized()){

                                            //Debug.Log("Set chunk dirty at: " + x + ", " + y);

                                            m.RefreshChunk();

                                            //for(int i = 0; i < m.chunkPieces.Length; i++){
                                                //EditorUtility.SetDirty(m.chunkPieces[i]);
                                            //}

                                            //EditorUtility.SetDirty(m);

                                            /*if(!(x == m_x && y == m_y)){

                                                if(x == m_x || y == m_y){

                                                    adjacentChunk = m;
                                                }
                                            }*/

                                        }
                                    }
                                }

                                /*if(backgroundMaterial != null && (workingBlock.isNullBlock || workingBlock.actAsEmptyBlock)){

                                    //We have to do this from a populated area to an unpopulated are

                                    int x_lower = 0;
                                    int x_upper = mouseoverChunk.parentMap.chunkWidth;
                                    int x_direction = 1;
                                    int y_lower = 0;
                                    int y_upper = mouseoverChunk.parentMap.chunkHeight;
                                    int y_direction = 1;

                                    if(adjacentChunk != null){

                                        int x_dif = m_x - adjacentChunk.GetX();
                                        int y_dif = m_y - adjacentChunk.GetY();

                                        if(x_dif == -1){
                                            x_lower = mouseoverChunk.parentMap.chunkWidth-1;
                                            x_upper = -1;
                                            x_direction = -1;
                                        }

                                        if(y_dif == -1){
                                            y_lower = mouseoverChunk.parentMap.chunkHeight-1;
                                            y_upper = -1;
                                            y_direction = -1;
                                        }

                                    }

                                    List<Vector3> coord = new List<Vector3>();

                                    for(int x = x_lower; x != x_upper; x+=x_direction){
                                        for(int y = y_lower; y != y_upper; y+=y_direction){

                                            Block b = mouseoverChunk.GetBlockAtChunkCoord(x,y);

                                            coord.Add(new Vector3(b.x,b.y,b.depth));

                                        }
                                    }

                                    if(!mouseoverChunk.parentMap.HasBackgroundEntryFor(backgroundMaterial.name)){

                                        mouseoverChunk.parentMap.AddBackground(backgroundMaterial);
                                    }

                                    mouseoverChunk.parentMap.AddToBackground(coord.ToArray(),backgroundMaterial.name);
                                }*/

                                SetEntireMapDirty(mouseoverChunk.parentMap);

                            }

                        }

                        if(mouseoverBlock != null && !initializedChunk){

                            if(currentBehaviour == MapPaintBehaviour.Cycle){

                                CycleBlock(mouseoverBlock);

                            }

                        }

                        if(currentBehaviour == MapPaintBehaviour.Edit_Functions && functionBlock != null){
                        }
                        else{
                            Event.current.Use();
                        }

                    }

                    //on right-click
                    if(Event.current.button == 1){

                        rightMouseDown = true;

                        leftMouseDown = false;

                        if(mouseoverBlock != null){

                            if(currentBehaviour == MapPaintBehaviour.Cycle){

                                CycleBlockVariation(mouseoverBlock,1);

                            }

                        }

                        if(currentBehaviour == MapPaintBehaviour.DrawPath){

                            if(mouseoverBlock != null){

                                RemoveFromPath(mouseoverBlock);

                                if(pathBlocks.Count == 0){
                                    drawingPath = false;
                                }

                            }

                        }

                    }

                    //On middle mouse
                    if(Event.current.button == 2){

                        rightMouseDown = false;

                        leftMouseDown = false;

                        if(mouseoverBlock != null){

                            if(currentBehaviour == MapPaintBehaviour.Cycle){

                                CycleBlockVariation(mouseoverBlock,-1);

                            }

                        }

                    }

                }
            }

            if(leftMouseDown && currentBehaviour == MapPaintBehaviour.Edit_Functions){
                leftMouseDown = false;

                if(functionBlock == null && mouseoverBlock != null){
                    SetFunctionBlock(mouseoverBlock);
                }

                if(setTidyTarget && mouseoverBlock != null && functionBlock != null){
                    setTidyTarget = false;
                    currentTidyTarget = new TidyTarget(functionBlock,mouseoverBlock);
                }
            }

            if(leftMouseDown && currentBehaviour == MapPaintBehaviour.Paint_Background){

                if(mouseoverBlock != null){
                    AddToBackground(mouseoverBlock);
                }
            }

            if(functionBlock != null){

                //Draw the function block UI

                DrawFunctionBlockUI();

            }

            if(leftMouseDown && currentBehaviour == MapPaintBehaviour.Delete_Chunk && mouseoverChunk != null){
                DeleteChunk(mouseoverChunk);
                leftMouseDown = false;
            }

            if(leftMouseDown && currentBehaviour == MapPaintBehaviour.Paint && mouseoverBlock != null  && !initializedChunk){

                PaintBlock(mouseoverBlock);

            }

            if(rightMouseDown && currentBehaviour == MapPaintBehaviour.Paint && mouseoverBlock != null  && !initializedChunk){

                //Nope: As this overrides the ability to move the camera around with right click

                //PaintEmptyBlock(mouseoverBlock);

            }

            if(leftMouseDown && currentBehaviour == MapPaintBehaviour.Add_Layer_Above && (mouseoverChunk != null || mouseoverBlock != null)){

                MapChunk c = mouseoverChunk;

                if(c == null){

                    c = mouseoverBlock.blockMap.GetChunkForBlockCoordinate(mouseoverBlock.x,mouseoverBlock.y,mouseoverBlock.depth);

                }

                AddLayerChunk(c,1);

                parentWindow.Repaint();

                leftMouseDown = false;

            }

            if(leftMouseDown && currentBehaviour == MapPaintBehaviour.Add_Layer_Below && (mouseoverChunk != null || mouseoverBlock != null)){

                MapChunk c = mouseoverChunk;

                if(c == null){

                    c = mouseoverBlock.blockMap.GetChunkForBlockCoordinate(mouseoverBlock.x,mouseoverBlock.y,mouseoverBlock.depth);

                }

                AddLayerChunk(c,-1);

                parentWindow.Repaint();

                leftMouseDown = false;

            }

            /*for(int i = 0; i < plugins.Length; i++){

                if(plugins[i].obj == null){
                    continue;
                }

                plugins[i].obj.DrawScene(sceneView);
            }*/
        }
Пример #51
0
    public void Editor_ActivateBound(int width, int height, int x, int y, int depth, BlockMap parentMap, MapChunk boundChunk)
    {
        this.parentMap = parentMap;
        this.width = width;
        this.height = height;

        this.x = x;
        this.y = y;
        this.depth = depth;

        int chunkDiff = depth - boundChunk.depth;

        float heightOffset = 0.0f;

        if(chunkDiff == 1){
            //above
            heightOffset = parentMap.tileScale.z;

        }
        else if(chunkDiff == -1){
            //below
            heightOffset = -parentMap.tileScale.z;
        }
        else{
            Debug.LogWarning("Chunk depth difference inconsistent! Aneurysm imminent!");
        }

        transform.parent = parentMap.transform;

        Vector3 pos = Vector3.zero;

        if(parentMap.growthAxis == BlockMap.GrowthAxis.Up){

            pos = new Vector3(
                                      boundChunk.transform.localPosition.x,
                                      boundChunk.transform.localPosition.y,
                                      boundChunk.transform.localPosition.z + heightOffset
                                      );

            transform.localRotation = Quaternion.identity;

        }
        else if(parentMap.growthAxis == BlockMap.GrowthAxis.Forward ){

            pos = new Vector3(
                                      boundChunk.transform.localPosition.x,
                              		  boundChunk.transform.localPosition.y + heightOffset,
                                      boundChunk.transform.localPosition.z
                                      );

            transform.localRotation = Quaternion.Euler(
                                                       new Vector3(
                                                                   90.0f,
                                                                   0.0f,
                                                                   0.0f
                                                                   ));

        }

        transform.localPosition = pos;

        transform.localScale = new Vector3(
                                                       parentMap.tileScale.x * width,
                                                       parentMap.tileScale.y * height,
                                                       parentMap.tileScale.z
                                                       );
    }
Пример #52
0
		public void InitializeChunkSet(BlockMap parentMap, int x, int y){
			this.x = x;
			this.y = y;
			this.parentMap = parentMap;
		}
Пример #53
0
 internal GatherStream(byte[] buffer, BlockMap assignedBlocks, TimeSpan timeout) : base(buffer, false)
 {
     this.assignedBlocks = assignedBlocks;
     this.timeout = timeout;
 }
Пример #54
0
 public virtual void OnBindToMap(int x, int y, int depth, BlockMap blockMap)
 {
 }
Пример #55
0
		/// <summary>
		/// Returns the chunk at the given block coordinates 
		/// </summary>
		/// <param name="map">
		/// The map from which to retrieve the chunk
		/// </param>
		/// <param name="x">
		/// The block x coordinate
		/// </param>
		/// <param name="y">
		/// The block y coordinate
		/// </param>
		/// <param name="depth">
		/// The depth coordinate
		/// </param>
		/// <returns>
		/// The chunk (if one exists) - null if not
		/// </returns>
		public static MapChunk GetChunkAtCoordinates(BlockMap map, int x, int y, int depth){
			
			return map.GetChunkForBlockCoordinate(x,y,depth);
			
		}
Пример #56
0
		void DrawFunctionalOverlays(BlockMap map){
						
			TidyFunctionalOverlay overlay = map.functionalOverlay;
			
			Color hc = Handles.color;
			Handles.color = Color.green;
						
			float radius = map.tileScale.y * 0.4f;
			
			for(int i = 0; i < overlay.mapData.Count; i++){
				
				if(overlay.mapData[i] == null || overlay.mapData[i].parentBlock == null){
					overlay.mapData.RemoveAt(i);
					i--;
					continue;
				}
				
				Handles.DrawWireDisc(overlay.mapData[i].parentBlock.transform.position,overlay.mapData[i].parentBlock.transform.forward,radius);
								
			}
			
			Handles.color = hc;
			
		}
Пример #57
0
		/// <summary>
		/// Mathematically divine the coordinates of the global position of an object within a map 
		/// </summary>
		/// <param name="map">
		/// The map within which you wish to divine your coordinates
		/// </param>
		/// <param name="globalPosition">
		/// The global position of the transform for which to divine coordinates
		/// </param>
		/// <returns>
		/// The x,y,z coordinates of the transform, gathered mathematically. NOTE: This is not of use on a map that involves arbitrarily-placed blocks (e.g soft selection)
		/// </returns>
		public static Vector3 GetMathematicalCoordinates(BlockMap map, Vector3 globalPosition){
			
			Vector3 localPosition = map.transform.InverseTransformPoint(globalPosition);
			
			int x = 0;
			int y = 0;
			int z = 0;
			
			float halfChunk_x = (float)(map.chunkWidth) * map.tileScale.x * 0.5f;
						
			if(map.editorMap){
				MapChunk c = map.GetLeftMostMapChunk();
				if(c != null){
					halfChunk_x += c.transform.localPosition.x;
				}
				
			}
			
			float halfChunk_y = 0.0f;
			
			if(map.growthAxis == BlockMap.GrowthAxis.Up){
				halfChunk_y = (float)(map.chunkHeight) * map.tileScale.y * 0.5f;
				
				MapChunk c = map.GetTopMostMapChunk();
				if(c != null){
					halfChunk_y += c.transform.localPosition.y;
				}
			}
			else{
				halfChunk_y = (float)(map.chunkHeight) * map.tileScale.z * 0.5f;
				
				MapChunk c = map.GetTopMostMapChunk();
				if(c != null){
					halfChunk_y += c.transform.localPosition.z;
				}
			}
			
			Vector3 modPos = localPosition;
									
			modPos.x = (localPosition.x - halfChunk_x - (0.5f * map.tileScale.x));
			
			if(map.growthAxis == BlockMap.GrowthAxis.Up){
				modPos.y = (localPosition.y - halfChunk_y + (0.5f * map.tileScale.y));
			}
			else{
				modPos.z = (localPosition.z - halfChunk_y + (0.5f * map.tileScale.z));
			}
			
			x = (int)((modPos.x- 0.5f * map.tileScale.x) / map.tileScale.x) + 1;
			
			if(map.growthAxis == BlockMap.GrowthAxis.Up){
				y = (int)((modPos.y - 0.5f * map.tileScale.y) / map.tileScale.y);
			}
			else{
				y = (int)((modPos.z - 0.5f * map.tileScale.z) / map.tileScale.z);
			}
			
			if(map.growthAxis == BlockMap.GrowthAxis.Up){
				modPos.z += (-map.mapLowerDepth * map.tileScale.z);
				z = (int)(((modPos.z + 0.5f * map.tileScale.z) / map.tileScale.z) + map.mapLowerDepth);
			}
			else{
				modPos.z += (-map.mapLowerDepth * map.tileScale.y);
				z = (int)(((modPos.y - 0.5f * map.tileScale.y) / map.tileScale.y) + map.mapLowerDepth);
			}
						
			return new Vector3(-x,-y,z);
		}
Пример #58
0
		void RefreshBlocks(int x, int y, int depth, BlockMap map){
			
			EditorUtility.SetDirty(map);
			
			for(int x1 = x -1; x1 <= x + 1; x1++){
				for(int y1 = y - 1; y1 <= y + 1; y1++){
					
					Block b = map.GetBlockAt(x1,y1,depth);
					
					if(b != null){
						
						b.RefreshBlock();
						
						EditorUtility.SetDirty(b);
						
						//if(paintRandom){
							//b.RandomiseVariant();
						//}
						
					}
					
				}
			}
			
		}
Пример #59
0
		public void OnSelectionChange(){
							
			if(Selection.activeGameObject != null){
				
				focusMap = GetBlockMapFromSelection(Selection.activeGameObject);
								
				selectedBlock = GetBlockFromSelection(Selection.activeGameObject);
				
				if(selectedBlock != null && Selection.activeGameObject != selectedBlock){
					selectedBlockPosition = selectedBlock.transform.localPosition;
					
					if(currentBehaviour == MapPaintBehaviour.Block_Move){
						selectionChangeRequired = true;
					}
				}
				
				//Debug.Log("Repaint selection");
				
				parentWindow.Repaint();
			}
		}
	public virtual void OnBindToMap(BlockMap map, Block b){}