Example #1
1
        static long CalculateActorSelectionPriority(ActorInfo info, Rectangle bounds, int2 selectionPixel)
        {
            var centerPixel = new int2(bounds.X, bounds.Y);
            var pixelDistance = (centerPixel - selectionPixel).Length;

            return ((long)-pixelDistance << 32) + info.SelectionPriority();
        }
Example #2
1
        protected override void OnMouseDown(MouseEventArgs e)
        {
            var pos = new int2(e.X / TileSize, e.Y / TileSize);

            if (InputMode == null)
            {
                if (e.Button == MouseButtons.Left)
                {
                    CurrentTemplate = Templates.FirstOrDefault(t => t.Cells.ContainsKey(pos));
                    if (CurrentTemplate == null)
                        Templates.Add(CurrentTemplate = new Template { Cells = new Dictionary<int2, bool> { { pos, true } } });

                    Invalidate();
                }

                if (e.Button == MouseButtons.Right)
                {
                    Templates.RemoveAll(t => t.Cells.ContainsKey(pos));
                    CurrentTemplate = null;
                    Invalidate();
                }
            }
            else
            {
                TerrainTypes[pos.X, pos.Y] = int.Parse(InputMode);
                Invalidate();
            }
        }
Example #3
0
        // Used for classic mouse orders, determines whether or not action at xy is move or select
        public virtual bool InputOverridesSelection(World world, int2 xy, MouseInput mi)
        {
            var actor = world.ScreenMap.ActorsAt(xy).WithHighestSelectionPriority(xy);
            if (actor == null)
                return true;

            var target = Target.FromActor(actor);
            var cell = world.Map.CellContaining(target.CenterPosition);
            var actorsAt = world.ActorMap.GetActorsAt(cell).ToList();
            var underCursor = world.Selection.Actors.WithHighestSelectionPriority(xy);

            var o = OrderForUnit(underCursor, target, actorsAt, cell, mi);
            if (o != null)
            {
                var modifiers = TargetModifiers.None;
                if (mi.Modifiers.HasModifier(Modifiers.Ctrl))
                    modifiers |= TargetModifiers.ForceAttack;
                if (mi.Modifiers.HasModifier(Modifiers.Shift))
                    modifiers |= TargetModifiers.ForceQueue;
                if (mi.Modifiers.HasModifier(Modifiers.Alt))
                    modifiers |= TargetModifiers.ForceMove;

                if (o.Order.TargetOverridesSelection(modifiers))
                    return true;
            }

            return false;
        }
Example #4
0
        public IEnumerable<Order> Order(World world, int2 xy, MouseInput mi)
        {
            if (mi.Button == MouseButton.Right)
                world.CancelInputMode();

            return OrderInner(world, xy, mi);
        }
Example #5
0
		public override void Draw()
		{
			SpriteFont font;
			if (!Game.Renderer.Fonts.TryGetValue(Font, out font))
				throw new ArgumentException("Requested font '{0}' was not found.".F(Font));

			var text = GetText();
			if (text == null)
				return;

			var textSize = font.Measure(text);
			var position = RenderOrigin;

			if (VAlign == TextVAlign.Middle)
				position += new int2(0, (Bounds.Height - textSize.Y) / 2);

			if (VAlign == TextVAlign.Bottom)
				position += new int2(0, Bounds.Height - textSize.Y);

			if (Align == TextAlign.Center)
				position += new int2((Bounds.Width - textSize.X) / 2, 0);

			if (Align == TextAlign.Right)
				position += new int2(Bounds.Width - textSize.X, 0);

			if (WordWrap)
				text = WidgetUtils.WrapText(text, Bounds.Width, font);

			var color = GetColor();
			var contrast = GetContrastColor();
			if (Contrast)
				font.DrawTextWithContrast(text, position, color, contrast, 2);
			else
				font.DrawText(text, position, color);
		}
 void AddAdjacentWall(int2 location, int2 otherLocation)
 {
     if (otherLocation == location + new int2(0, -1)) adjacentWalls |= 1;
     if (otherLocation == location + new int2(+1, 0)) adjacentWalls |= 2;
     if (otherLocation == location + new int2(0, +1)) adjacentWalls |= 4;
     if (otherLocation == location + new int2(-1, 0)) adjacentWalls |= 8;
 }
Example #7
0
 public static bool CanPlaceBuilding(this World world, string name, BuildingInfo building, int2 topLeft, Actor toIgnore)
 {
     var res = world.WorldActor.Trait<ResourceLayer>();
     return FootprintUtils.Tiles(name, building, topLeft).All(
         t => world.Map.IsInMap(t.X, t.Y) && res.GetResource(t) == null &&
             world.IsCellBuildable(t, building.WaterBound, toIgnore));
 }
Example #8
0
        public override void Draw()
        {
            if (world == null) return;
            if( world.LocalPlayer.WinState != WinState.Undefined ) return;

            var o = new float2(mapRect.Location.X, mapRect.Location.Y + world.Map.Bounds.Height * previewScale * (1 - radarMinimapHeight)/2);
            var s = new float2(mapRect.Size.Width, mapRect.Size.Height*radarMinimapHeight);
            var rsr = Game.Renderer.RgbaSpriteRenderer;
            rsr.DrawSprite(terrainSprite, o, s);
            rsr.DrawSprite(customTerrainSprite, o, s);
            rsr.DrawSprite(actorSprite, o, s);
            rsr.DrawSprite(shroudSprite, o, s);

            // Draw viewport rect
            if (hasRadar && !animating)
            {
                var wr = Game.viewport.WorldRect;
                var wro = new int2(wr.X, wr.Y);
                var tl = CellToMinimapPixel(wro);
                var br = CellToMinimapPixel(wro + new int2(wr.Width, wr.Height));

                Game.Renderer.EnableScissor((int)mapRect.Left, (int)mapRect.Top, (int)mapRect.Width, (int)mapRect.Height);
                Game.Renderer.LineRenderer.DrawRect(tl, br, Color.White);
                Game.Renderer.DisableScissor();
            }
        }
Example #9
0
        public string GetCursor( World world, int2 xy, MouseInput mi )
        {
            bool useSelect = false;

            var custom = world.WorldActor.TraitOrDefault<ICustomUnitOrderGenerator>();
            if (custom != null)
            {
               return custom.GetCursor(world, xy, mi);
            }

            var underCursor = world.FindUnitsAtMouse(mi.Location)
                .Where(a => a.HasTrait<ITargetable>())
                .OrderByDescending(a => a.Info.Traits.Contains<SelectableInfo>() ? a.Info.Traits.Get<SelectableInfo>().Priority : int.MinValue)
                .FirstOrDefault();

            if (mi.Modifiers.HasModifier(Modifiers.Shift) || !world.Selection.Actors.Any())
                if (underCursor != null)
                    useSelect = true;

            var orders = world.Selection.Actors
                .Select(a => OrderForUnit(a, xy, mi, underCursor))
                .Where(o => o != null)
                .ToArray();

            if( orders.Length == 0 ) return (useSelect) ? "select" : "default";

            return orders[0].cursor ?? ((useSelect) ? "select" : "default");
        }
Example #10
0
        public void Apply(Surface surface)
        {
            // change the bits in the map
            var template = surface.TileSet.Templates[brushTemplate.N];
            var tile = surface.TileSetRenderer.Data(brushTemplate.N);
            var pos = surface.GetBrushLocation();

            if (surface.GetModifiers() == Keys.Shift)
            {
                FloodFillWithBrush(surface, pos);
                return;
            }

            for (var u = 0; u < template.Size.X; u++)
                for (var v = 0; v < template.Size.Y; v++)
                {
                    var cell = pos + new CVec(u, v);
                    if (surface.Map.Contains(cell))
                    {
                        var z = u + v * template.Size.X;
                        if (tile != null && tile[z].Length > 0)
                        {
                            var index = template.PickAny ? (byte)((u + pos.X) % 4 + ((v + pos.Y) % 4) * 4) : (byte)z;
                            surface.Map.MapTiles.Value[cell] = new TerrainTile(brushTemplate.N, index);
                        }

                        var ch = new int2((pos.X + u) / Surface.ChunkSize, (pos.Y + v) / Surface.ChunkSize);
                        if (surface.Chunks.ContainsKey(ch))
                        {
                            surface.Chunks[ch].Dispose();
                            surface.Chunks.Remove(ch);
                        }
                    }
                }
        }
Example #11
0
 public MoveFlash( World world, int2 cell )
 {
     this.pos = Game.CellSize * (cell + new float2(0.5f, 0.5f));
     anim.PlayThen( "idle",
         () => world.AddFrameEndTask(
             w => w.Remove( this ) ) );
 }
Example #12
0
        public Missile(MissileInfo info, ProjectileArgs args)
        {
            Info = info;
            Args = args;

            SubPxPosition = 1024 * Args.src;
            Altitude = Args.srcAltitude;
            Facing = Args.facing;

            if (info.Inaccuracy > 0)
                offset = (info.Inaccuracy * args.firedBy.World.SharedRandom.Gauss2D(2)).ToInt2();

            if (Info.Image != null)
            {
                anim = new Animation(Info.Image, () => Facing);
                anim.PlayRepeating("idle");
            }

            if (Info.ContrailLength > 0)
            {
                Trail = new ContrailHistory(Info.ContrailLength,
                    Info.ContrailUsePlayerColor ? ContrailHistory.ChooseColor(args.firedBy) : Info.ContrailColor,
                    Info.ContrailDelay);
            }
        }
Example #13
0
        public Order IssueOrder(Actor self, int2 xy, MouseInput mi, Actor underCursor)
        {
            if (mi.Button == MouseButton.Right && self == underCursor)
                return new Order("DeployTransform", self);

            return null;
        }
Example #14
0
        void DoParadrop(Player owner, int2 p, string[] items)
        {
            var startPos = owner.World.ChooseRandomEdgeCell();
            owner.World.AddFrameEndTask(w =>
            {
                var info = (Info as ParatroopersPowerInfo);
                var flare = info.FlareType != null ? w.CreateActor(info.FlareType, new TypeDictionary
                {
                    new LocationInit( p ),
                    new OwnerInit( owner ),
                }) : null;

                var a = w.CreateActor(info.UnitType, new TypeDictionary
                {
                    new LocationInit( startPos ),
                    new OwnerInit( owner ),
                    new FacingInit( Util.GetFacing(p - startPos, 0) ),
                    new AltitudeInit( Rules.Info[info.UnitType].Traits.Get<PlaneInfo>().CruiseAltitude ),
                });

                a.CancelActivity();
                a.QueueActivity(new FlyCircle(p));
                a.Trait<ParaDrop>().SetLZ(p, flare);

                var cargo = a.Trait<Cargo>();
                foreach (var i in items)
                    cargo.Load(a, owner.World.CreateActor(false, i.ToLowerInvariant(), new TypeDictionary { new OwnerInit( a.Owner ) }));
            });
        }
Example #15
0
        public IEnumerable<Actor> GetUnitsAt( int2 a )
        {
            if (!map.IsInMap(a)) yield break;

            for( var i = influence[ a.X, a.Y ] ; i != null ; i = i.next )
                yield return i.actor;
        }
Example #16
0
        public IEnumerable<Order> Order(World world, CPos cell, int2 worldPixel, MouseInput mi)
        {
            world.CancelInputMode();

            if (mi.Button == MouseButton.Left)
                yield return new Order("PlaceBeacon", world.LocalPlayer.PlayerActor, false) { TargetLocation = cell, SuppressVisualFeedback = true };
        }
Example #17
0
			public R8Frame(Stream s)
			{
				// Scan forward until we find some data
				var type = s.ReadUInt8();
				while (type == 0)
					type = s.ReadUInt8();

				var width = s.ReadInt32();
				var height = s.ReadInt32();
				var x = s.ReadInt32();
				var y = s.ReadInt32();

				Size = new Size(width, height);
				Offset = new int2(width / 2 - x, height / 2 - y);

				/*var imageOffset = */
				s.ReadInt32();
				var paletteOffset = s.ReadInt32();
				var bpp = s.ReadUInt8();
				if (bpp != 8)
					throw new InvalidDataException("Error: {0} bits per pixel are not supported.".F(bpp));

				var frameHeight = s.ReadUInt8();
				var frameWidth = s.ReadUInt8();
				FrameSize = new Size(frameWidth, frameHeight);

				// Skip alignment byte
				s.ReadUInt8();

				Data = s.ReadBytes(width * height);

				// Ignore palette
				if (type == 1 && paletteOffset != 0)
					s.Seek(520, SeekOrigin.Current);
			}
Example #18
0
        public Order IssueOrder(Actor self, int2 xy, MouseInput mi, Actor underCursor)
        {
            if (underCursor != null && underCursor.HasTrait<RenderInfantry>())
                return new Order("Disguise", self, underCursor);

            return null;
        }
        public override void Initialize(WidgetArgs args)
        {
            base.Initialize(args);

            // Start in the closed position
            offset = ClosedOffset;
        }
Example #20
0
 public IonCannon(Actor firedBy, World world, int2 location)
 {
     this.firedBy = firedBy;
     target = Target.FromCell(location);
     anim = new Animation("ionsfx");
     anim.PlayThen("idle", () => Finish(world));
 }
Example #21
0
 public Smoke(World world, int2 pos, string trail)
 {
     this.pos = pos;
     anim = new Animation(trail);
     anim.PlayThen("idle",
         () => world.AddFrameEndTask(w => w.Remove(this)));
 }
Example #22
0
        public Viewport(WorldRenderer wr, Map map)
        {
            worldRenderer = wr;
            var grid = Game.ModData.Manifest.Get<MapGrid>();

            // Calculate map bounds in world-px
            if (wr.World.Type == WorldType.Editor)
            {
                // The full map is visible in the editor
                var width = map.MapSize.X * grid.TileSize.Width;
                var height = map.MapSize.Y * grid.TileSize.Height;
                if (wr.World.Map.Grid.Type == MapGridType.RectangularIsometric)
                    height /= 2;

                mapBounds = new Rectangle(0, 0, width, height);
                CenterLocation = new int2(width / 2, height / 2);
            }
            else
            {
                var tl = wr.ScreenPxPosition(map.ProjectedTopLeft);
                var br = wr.ScreenPxPosition(map.ProjectedBottomRight);
                mapBounds = Rectangle.FromLTRB(tl.X, tl.Y, br.X, br.Y);
                CenterLocation = (tl + br) / 2;
            }

            Zoom = Game.Settings.Graphics.PixelDouble ? 2 : 1;
            tileSize = grid.TileSize;
        }
Example #23
0
        // Used to check for neighbouring bridges
        public Bridge GetBridge(int2 cell)
        {
            if (!world.Map.IsInMap(cell.X, cell.Y))
                return null;

            return Bridges[ cell.X, cell.Y ];
        }
        public void AddSmudge(int2 loc)
        {
            if (!world.GetTerrainInfo(loc).AcceptSmudge)
                return;

            if (Game.CosmeticRandom.Next(0,100) <= Info.SmokePercentage)
                world.AddFrameEndTask(w => w.Add(new Smoke(w, Traits.Util.CenterOfCell(loc), Info.SmokeType)));

            // No smudge; create a new one
            if (!tiles.ContainsKey(loc))
            {
                byte st = (byte)(1 + world.SharedRandom.Next(Info.Types.Length - 1));
                tiles.Add(loc, new TileReference<byte,byte>(st,(byte)0));
                return;
            }

            var tile = tiles[loc];
            // Existing smudge; make it deeper
            int depth = Info.Depths[tile.type-1];
            if (tile.index < depth - 1)
            {
                tile.index++;
                tiles[loc] = tile;	// struct semantics.
            }
        }
Example #25
0
        public override void DrawInner(World world)
        {
            int margin = 5;
            var font = (Bold) ? Game.Renderer.BoldFont : Game.Renderer.RegularFont;
            var cursor = (showCursor && Focused) ? "|" : "";
            var textSize = font.Measure(Text + "|");
            var pos = RenderOrigin;

            WidgetUtils.DrawPanel("dialog3",
                new Rectangle(pos.X, pos.Y, Bounds.Width, Bounds.Height));

            // Inset text by the margin and center vertically
            var textPos = pos + new int2(margin, (Bounds.Height - textSize.Y) / 2 - VisualHeight);

            // Right align when editing and scissor when the text overflows
            if (textSize.X > Bounds.Width - 2 * margin)
            {
                if (Focused)
                    textPos += new int2(Bounds.Width - 2 * margin - textSize.X, 0);

                Game.Renderer.Device.EnableScissor(pos.X + margin, pos.Y, Bounds.Width - 2 * margin, Bounds.Bottom);
            }

            font.DrawText(Text + cursor, textPos, Color.White);

            if (textSize.X > Bounds.Width - 2 * margin)
            {
                Game.Renderer.RgbaSpriteRenderer.Flush();
                Game.Renderer.Device.DisableScissor();
            }
        }
Example #26
0
		public override void Initialize(WidgetArgs args)
		{
			base.Initialize(args);

			var width = world.Map.Bounds.Width;
			var height = world.Map.Bounds.Height;
			var size = Math.Max(width, height);
			var rb = RenderBounds;

			previewScale = Math.Min(rb.Width * 1f / width, rb.Height * 1f / height);
			previewOrigin = new int2((int)(previewScale * (size - width) / 2), (int)(previewScale * (size - height) / 2));
			mapRect = new Rectangle(previewOrigin.X, previewOrigin.Y, (int)(previewScale * width), (int)(previewScale * height));

			// Only needs to be done once
			using (var terrainBitmap = Minimap.TerrainBitmap(world.Map.Rules.TileSets[world.Map.Tileset], world.Map))
			{
				var r = new Rectangle(0, 0, width, height);
				var s = new Size(terrainBitmap.Width, terrainBitmap.Height);
				var terrainSheet = new Sheet(s, false);
				terrainSheet.Texture.SetData(terrainBitmap);
				terrainSprite = new Sprite(terrainSheet, r, TextureChannel.Alpha);

				// Data is set in Tick()
				customTerrainSprite = new Sprite(new Sheet(s, false), r, TextureChannel.Alpha);
				actorSprite = new Sprite(new Sheet(s, false), r, TextureChannel.Alpha);
				shroudSprite = new Sprite(new Sheet(s, false), r, TextureChannel.Alpha);
			}
		}
Example #27
0
		public void SetPreview(ActorInfo actor, TypeDictionary td)
		{
			var init = new ActorPreviewInitializer(actor, worldRenderer, td);
			preview = actor.TraitInfos<IRenderActorPreviewInfo>()
				.SelectMany(rpi => rpi.RenderPreview(init))
				.ToArray();

			// Calculate the preview bounds
			PreviewOffset = int2.Zero;
			IdealPreviewSize = int2.Zero;

			var r = preview
				.SelectMany(p => p.Render(worldRenderer, WPos.Zero))
				.OrderBy(WorldRenderer.RenderableScreenZPositionComparisonKey)
				.Select(rr => rr.PrepareRender(worldRenderer));

			if (r.Any())
			{
				var b = r.First().ScreenBounds(worldRenderer);
				foreach (var rr in r.Skip(1))
					b = Rectangle.Union(b, rr.ScreenBounds(worldRenderer));

				IdealPreviewSize = new int2(b.Width, b.Height);
				PreviewOffset = -new int2(b.Left, b.Top) - IdealPreviewSize / 2;
			}
		}
        public IEnumerable<Order> Order( World world, int2 xy, MouseInput mi )
        {
            var underCursor = world.FindUnitsAtMouse(mi.Location)
                .Where(a => a.HasTrait<ITargetable>())
                .OrderByDescending(
                    a =>
                    a.Info.Traits.Contains<SelectableInfo>()
                        ? a.Info.Traits.Get<SelectableInfo>().Priority
                        : int.MinValue)
                .FirstOrDefault();

            var orders = world.Selection.Actors
                .Select(a => OrderForUnit(a, xy, mi, underCursor))
                .Where(o => o != null)
                .ToArray();

            var actorsInvolved = orders.Select(o => o.self).Distinct();
            if (actorsInvolved.Any())
                yield return new Order("CreateGroup", actorsInvolved.First().Owner.PlayerActor, false)
                {
                    TargetString = string.Join(",", actorsInvolved.Select(a => a.ActorID.ToString()).ToArray())
                };

            foreach (var o in orders)
                yield return CheckSameOrder(o.iot, o.trait.IssueOrder(o.self, o.iot, o.target, mi.Modifiers.HasModifier(Modifiers.Shift)));
        }
Example #29
0
File: Husk.cs Project: pdovy/OpenRA
 public Husk(ActorInitializer init)
 {
     this.self = init.self;
     this.location = init.Get<LocationInit,int2>();
     this.Facing = init.Contains<FacingInit>() ? init.Get<FacingInit,int>() : 128;
     self.World.WorldActor.Trait<UnitInfluence>().Add(self, this);
 }
Example #30
0
 public Building(ActorInitializer init)
 {
     this.self = init.self;
     this.topLeft = init.Get<LocationInit,int2>();
     this.Info = self.Info.Traits.Get<BuildingInfo>();
     this.PlayerPower = init.self.Owner.PlayerActor.Trait<PowerManager>();
 }
Example #31
0
 public void setPosition(int2 pos)
 {
     this.m_position = pos;
 }
Example #32
0
 public static int3 ToInt3XY(this int2 iv2)
 {
     return(new int3(iv2.x, iv2.y, 0));
 }
 public string GetCursor(World world, CPos cell, int2 worldPixel, MouseInput mi)
 {
     return(world.Map.Contains(cell) ? cursor : "generic-blocked");
 }
Example #34
0
        // ----------------------------------------------------------------------------
        // int2

        public static float2 ToFloat2(this int2 iv2)
        {
            return(new float2(iv2.x, iv2.y));
        }
Example #35
0
 public static string ToStringCompact(this int2 iv2)
 {
     return(string.Format("({0}, {1})", iv2.x, iv2.y));
 }
Example #36
0
 public static float3 ToFloat3XZ(this int2 iv2)
 {
     return(new float3(iv2.x, 0.0f, iv2.y));
 }
Example #37
0
 public static float3 ToFloat3XY(this int2 iv2)
 {
     return(new float3(iv2.x, iv2.y, 0.0f));
 }
Example #38
0
 public static int3 ToInt3XZ(this int2 iv2)
 {
     return(new int3(iv2.x, 0, iv2.y));
 }
Example #39
0
 private int getNodeIndex(int x, int y, int2 gridSize)
 {
     return(x + y * gridSize.x);
 }
Example #40
0
        public void Execute()
        {
            NativeArray <PathNode> pathNodes = new NativeArray <PathNode>(gridSize.x * gridSize.y, Allocator.Temp);

            // set up all path nodes
            for (int x = 0; x < gridSize.x; x++)
            {
                for (int y = 0; y < gridSize.y; y++)
                {
                    PathNode pathNode = new PathNode();
                    pathNode.x     = x;
                    pathNode.y     = y;
                    pathNode.index = x + y * gridSize.x;

                    pathNode.walkable          = true;
                    pathNode.cameFromNodeIndex = -1;

                    pathNodes[pathNode.index] = pathNode;
                }
            }

            NativeList <PathNode> openList   = new NativeList <PathNode>(Allocator.Temp);
            NativeList <PathNode> closedList = new NativeList <PathNode>(Allocator.Temp);

            PathNode startNode    = pathNodes[getNodeIndex(positionStart.x, positionStart.y, gridSize)];
            int      endNodeIndex = getNodeIndex(positionEnd.x, positionEnd.y, gridSize);

            startNode.gCost = 0;
            startNode.UpdateFCost();
            openList.Add(startNode);

            while (openList.Length > 0)
            {
                PathNode currentNode = getNodeWithLowestFCost(ref openList);
                closedList.Add(currentNode);

                if (currentNode.index == endNodeIndex)
                {
                    // todo: return the path
                    break;
                }

                NativeList <PathNode> eligibleNeighbours = getEligibleNeighbours(currentNode, pathNodes, gridSize);

                for (int i = 0; i < eligibleNeighbours.Length; i++)
                {
                    PathNode neighbourNode = eligibleNeighbours[i];

                    if (containsNode(closedList, neighbourNode))
                    {
                        continue;
                    }

                    int2 currentPosition   = new int2(currentNode.x, currentNode.y);
                    int2 neighbourPosition = new int2(neighbourNode.x, neighbourNode.y);

                    int tentativeGCost = currentNode.gCost + CalculateDistanceCost(currentPosition, neighbourPosition);
                    if (!containsNode(openList, neighbourNode) || tentativeGCost < neighbourNode.gCost)
                    {
                        neighbourNode.cameFromNodeIndex = currentNode.index;
                        neighbourNode.gCost             = tentativeGCost;
                        neighbourNode.hCost             = CalculateDistanceCost(new int2(neighbourNode.x, neighbourNode.y), positionEnd);
                        neighbourNode.UpdateFCost();
                        pathNodes[neighbourNode.index] = neighbourNode;

                        if (!containsNode(openList, neighbourNode))
                        {
                            openList.Add(neighbourNode);
                        }
                    }
                }
            }

            NativeList <int2> path = getPath(pathNodes, pathNodes[endNodeIndex]);

            path.Dispose();
            openList.Dispose();
            closedList.Dispose();
        }
Example #41
0
        static void ReadOverlay(Map map, IniFile file, int2 fullSize)
        {
            var overlaySection    = file.GetSection("OverlayPack");
            var overlayCompressed = Convert.FromBase64String(string.Concat(overlaySection.Select(kvp => kvp.Value)));
            var overlayPack       = new byte[1 << 18];
            var temp = new byte[1 << 18];

            UnpackLCW(overlayCompressed, overlayPack, temp);

            var overlayDataSection    = file.GetSection("OverlayDataPack");
            var overlayDataCompressed = Convert.FromBase64String(string.Concat(overlayDataSection.Select(kvp => kvp.Value)));
            var overlayDataPack       = new byte[1 << 18];

            UnpackLCW(overlayDataCompressed, overlayDataPack, temp);

            var overlayIndex = new CellLayer <int>(map);

            overlayIndex.Clear(0xFF);

            for (var y = 0; y < fullSize.Y; y++)
            {
                for (var x = fullSize.X * 2 - 2; x >= 0; x--)
                {
                    var dx = (ushort)x;
                    var dy = (ushort)(y * 2 + x % 2);

                    var uv = new MPos(dx / 2, dy);
                    var rx = (ushort)((dx + dy) / 2 + 1);
                    var ry = (ushort)(dy - rx + fullSize.X + 1);

                    if (!map.Resources.Contains(uv))
                    {
                        continue;
                    }

                    overlayIndex[uv] = rx + 512 * ry;
                }
            }

            foreach (var cell in map.AllCells)
            {
                var overlayType = overlayPack[overlayIndex[cell]];
                if (overlayType == 0xFF)
                {
                    continue;
                }

                string actorType;
                if (OverlayToActor.TryGetValue(overlayType, out actorType))
                {
                    if (string.IsNullOrEmpty(actorType))
                    {
                        continue;
                    }

                    var shape = new Size(1, 1);
                    if (OverlayShapes.TryGetValue(overlayType, out shape))
                    {
                        // Only import the top-left cell of multi-celled overlays
                        var aboveType = overlayPack[overlayIndex[cell - new CVec(1, 0)]];
                        if (shape.Width > 1 && aboveType != 0xFF)
                        {
                            string a;
                            if (OverlayToActor.TryGetValue(aboveType, out a) && a == actorType)
                            {
                                continue;
                            }
                        }

                        var leftType = overlayPack[overlayIndex[cell - new CVec(0, 1)]];
                        if (shape.Height > 1 && leftType != 0xFF)
                        {
                            string a;
                            if (OverlayToActor.TryGetValue(leftType, out a) && a == actorType)
                            {
                                continue;
                            }
                        }
                    }

                    var ar = new ActorReference(actorType)
                    {
                        new LocationInit(cell),
                        new OwnerInit("Neutral")
                    };

                    DamageState damageState;
                    if (OverlayToHealth.TryGetValue(overlayType, out damageState))
                    {
                        var health = 100;
                        if (damageState == DamageState.Critical)
                        {
                            health = 25;
                        }
                        else if (damageState == DamageState.Heavy)
                        {
                            health = 50;
                        }
                        else if (damageState == DamageState.Medium)
                        {
                            health = 75;
                        }

                        if (health != 100)
                        {
                            ar.Add(new HealthInit(health));
                        }
                    }

                    map.ActorDefinitions.Add(new MiniYamlNode("Actor" + map.ActorDefinitions.Count, ar.Save()));

                    continue;
                }

                var resourceType = ResourceFromOverlay
                                   .Where(kv => kv.Value.Contains(overlayType))
                                   .Select(kv => kv.Key)
                                   .FirstOrDefault();

                if (resourceType != 0)
                {
                    map.Resources[cell] = new ResourceTile(resourceType, overlayDataPack[overlayIndex[cell]]);
                    continue;
                }

                Console.WriteLine("{0} unknown overlay {1}", cell, overlayType);
            }
        }
Example #42
0
        private NativeList <PathNode> getEligibleNeighbours(PathNode centerNode, NativeArray <PathNode> pathNodes, int2 gridSize)
        {
            NativeArray <int2> adjacentOffsetArray = new NativeArray <int2>(4, Allocator.Temp);

            adjacentOffsetArray[0] = new int2(-1, 0); // Left
            adjacentOffsetArray[1] = new int2(+1, 0); // Right
            adjacentOffsetArray[2] = new int2(0, +1); // Up
            adjacentOffsetArray[3] = new int2(0, -1); // Down

            NativeArray <int2> diagonalOffsetArray = new NativeArray <int2>(4, Allocator.Temp);

            diagonalOffsetArray[0] = new int2(+1, +1); // Top Right
            diagonalOffsetArray[1] = new int2(-1, +1); // Top Left
            diagonalOffsetArray[2] = new int2(+1, -1); // Bottom Right
            diagonalOffsetArray[3] = new int2(-1, -1); // Bottom Left

            NativeList <PathNode> eligibleNeighbours = new NativeList <PathNode>(Allocator.Temp);

            // iterate through all neighbours
            for (int i = 0; i < adjacentOffsetArray.Length; i++)
            {
                int2 offset           = adjacentOffsetArray[i];
                int2 adjacentPosition = new int2(centerNode.x + offset.x, centerNode.y + offset.y);

                if (!IsPositionInsideGrid(adjacentPosition, gridSize))
                {
                    continue;
                }

                int neighbourIndex = getNodeIndex(adjacentPosition.x, adjacentPosition.y, gridSize);

                if (pathNodes[neighbourIndex].walkable)
                {
                    eligibleNeighbours.Add(pathNodes[neighbourIndex]);
                }
            }

            for (int i = 0; i < diagonalOffsetArray.Length; i++)
            {
                int2 offset           = diagonalOffsetArray[i];
                int2 diagonalPosition = new int2(centerNode.x + offset.x, centerNode.y + offset.y);
                int2 cornerPosition1  = new int2(centerNode.x, centerNode.y + offset.y);
                int2 cornerPosition2  = new int2(centerNode.x + offset.x, centerNode.y);

                if (!IsPositionInsideGrid(diagonalPosition, gridSize))
                {
                    continue;
                }

                int neighbourIndex = getNodeIndex(diagonalPosition.x, diagonalPosition.y, gridSize);
                int cornerIndex1   = getNodeIndex(cornerPosition1.x, cornerPosition1.y, gridSize);
                int cornerIndex2   = getNodeIndex(cornerPosition2.x, cornerPosition2.y, gridSize);

                if (pathNodes[neighbourIndex].walkable &&
                    pathNodes[cornerIndex1].walkable &&
                    pathNodes[cornerIndex2].walkable)
                {
                    eligibleNeighbours.Add(pathNodes[neighbourIndex]);
                }
            }

            return(eligibleNeighbours);
        }
Example #43
0
 public Rect(int2 lowerLeft, int width, int height)
 {
     LowerLeft = lowerLeft;
     Width     = width;
     Height    = height;
 }
Example #44
0
 public Rect(int x, int y, int width, int height)
 {
     LowerLeft = new int2(x, y);
     Width     = width;
     Height    = height;
 }
Example #45
0
 public int2 ViewToWorldPx(int2 view)
 {
     return((graphicSettings.UIScale / Zoom * view.ToFloat2()).ToInt2() + TopLeft);
 }
Example #46
0
 public int2 WorldToViewPx(int2 world)
 {
     return(((Zoom / graphicSettings.UIScale) * (world - TopLeft).ToFloat2()).ToInt2());
 }
Example #47
0
        protected override IEnumerable <IRenderable> RenderDecoration(Actor self, WorldRenderer wr, int2 screenPos)
        {
            pips.PlayRepeating(Info.EmptySequence);

            var palette   = wr.Palette(Info.Palette);
            var pipSize   = pips.Image.Size.XY.ToInt2();
            var pipStride = Info.PipStride != int2.Zero ? Info.PipStride : new int2(pipSize.X, 0);

            screenPos -= pipSize / 2;

            var currentAmmo = 0;
            var totalAmmo   = 0;

            foreach (var a in ammo)
            {
                currentAmmo += a.CurrentAmmoCount;
                totalAmmo   += a.Info.Ammo;
            }

            var pipCount = Info.PipCount > 0 ? Info.PipCount : totalAmmo;

            for (var i = 0; i < pipCount; i++)
            {
                pips.PlayRepeating(currentAmmo * pipCount > i * totalAmmo ? Info.FullSequence : Info.EmptySequence);
                yield return(new UISpriteRenderable(pips.Image, self.CenterPosition, screenPos, 0, palette, 1f));

                screenPos += pipStride;
            }
        }
        protected override IEnumerable <IRenderable> RenderDecoration(Actor self, WorldRenderer wr, int2 screenPos)
        {
            pips.PlayRepeating(Info.EmptySequence);

            var palette   = wr.Palette(Info.Palette);
            var pipSize   = pips.Image.Size.XY.ToInt2();
            var pipStride = Info.PipStride != int2.Zero ? Info.PipStride : new int2(pipSize.X, 0);

            screenPos -= pipSize / 2;
            for (var i = 0; i < Info.PipCount; i++)
            {
                pips.PlayRepeating(player.Resources * Info.PipCount > i * player.ResourceCapacity ? Info.FullSequence : Info.EmptySequence);
                yield return(new UISpriteRenderable(pips.Image, self.CenterPosition, screenPos, 0, palette));

                screenPos += pipStride;
            }
        }
Example #49
0
        void DrawProductionTooltip(World world, string unit, int2 pos)
        {
            pos.Y += 15;

            var pl = world.LocalPlayer;
            var p  = pos.ToFloat2() - new float2(297, -3);

            var info         = Rules.Info[unit];
            var tooltip      = info.Traits.Get <TooltipInfo>();
            var buildable    = info.Traits.Get <BuildableInfo>();
            var cost         = info.Traits.Get <ValuedInfo>().Cost;
            var canBuildThis = CurrentQueue.CanBuild(info);

            var longDescSize = Game.Renderer.Fonts["Regular"].Measure(tooltip.Description.Replace("\\n", "\n")).Y;

            if (!canBuildThis)
            {
                longDescSize += 8;
            }

            WidgetUtils.DrawPanel("dialog4", new Rectangle(Game.viewport.Width - 300, pos.Y, 300, longDescSize + 65));

            Game.Renderer.Fonts["Bold"].DrawText(
                tooltip.Name + ((buildable.Hotkey != null) ? " ({0})".F(buildable.Hotkey.ToUpper()) : ""),
                p.ToInt2() + new int2(5, 5), Color.White);

            var resources = pl.PlayerActor.Trait <PlayerResources>();
            var power     = pl.PlayerActor.Trait <PowerManager>();

            DrawRightAligned("${0}".F(cost), pos + new int2(-5, 5),
                             (resources.DisplayCash + resources.DisplayOre >= cost ? Color.White : Color.Red));

            var lowpower = power.PowerState != PowerState.Normal;
            var time     = CurrentQueue.GetBuildTime(info.Name)
                           * ((lowpower) ? CurrentQueue.Info.LowPowerSlowdown : 1);

            DrawRightAligned(WidgetUtils.FormatTime(time), pos + new int2(-5, 35), lowpower ? Color.Red : Color.White);

            var bi = info.Traits.GetOrDefault <BuildingInfo>();

            if (bi != null)
            {
                DrawRightAligned("{1}{0}".F(bi.Power, bi.Power > 0 ? "+" : ""), pos + new int2(-5, 20),
                                 ((power.PowerProvided - power.PowerDrained) >= -bi.Power || bi.Power > 0) ? Color.White : Color.Red);
            }

            p += new int2(5, 35);
            if (!canBuildThis)
            {
                var prereqs = buildable.Prerequisites.Select(Description);
                if (prereqs.Any())
                {
                    Game.Renderer.Fonts["Regular"].DrawText("{0} {1}".F(RequiresText, prereqs.JoinWith(", ")), p.ToInt2(), Color.White);

                    p += new int2(0, 8);
                }
            }

            p += new int2(0, 15);
            Game.Renderer.Fonts["Regular"].DrawText(tooltip.Description.Replace("\\n", "\n"),
                                                    p.ToInt2(), Color.White);
        }
Example #50
0
 public void Resize(int2 size)
 {
     texture     = new Texture2D(size.x, size.y, TextureFormat, false);
     PixelBuffer = texture.GetRawTextureData <TPixel>();
 }
Example #51
0
 public void SetAttachment(int2 location, Sprite sprite, string palette)
 {
     this.sprite   = sprite;
     this.location = location;
     this.palette  = palette;
 }
Example #52
0
        void DrawRightAligned(string text, int2 pos, Color c)
        {
            var font = Game.Renderer.Fonts["Bold"];

            font.DrawText(text, pos - new int2(font.Measure(text).X, 0), c);
        }
Example #53
0
 public CapsuleShape(int2 a, int2 b, WDist radius)
 {
     PointA = a;
     PointB = b;
     Radius = radius;
 }
Example #54
0
 public int2 WorldToViewPx(int2 world)
 {
     return((Zoom * (world - TopLeft).ToFloat2()).ToInt2());
 }
Example #55
0
 public override string GetCursor(int2 pos)
 {
     return(GetScrollCursor(this, edgeDirections, pos));
 }
Example #56
0
 public void PlaceObjectTo(int2 pos, MyStaticObject obj)
 {
     obj.setPosition(pos);
     this.DeleteObstacle(pos.x, pos.y);
     Tiles[pos.x, pos.y].Objects.Add(obj);
 }
Example #57
0
 /// <summary>
 /// Returns a position in the world that is projected to the given screen position.
 /// There are many possible world positions, and the returned value chooses the value with no elevation.
 /// </summary>
 public WPos ProjectedPosition(int2 screenPx)
 {
     return(new WPos(TileScale * screenPx.X / TileSize.Width, TileScale * screenPx.Y / TileSize.Height, 0));
 }
Example #58
0
 public int2 ViewToWorldPx(int2 view)
 {
     return((1f / Zoom * view.ToFloat2()).ToInt2() + TopLeft);
 }
Example #59
0
 public static float3 ConvertTo3D(this int2 value)
 {
     return(new float3(value.x, 0, value.y));
 }
Example #60
0
        public override void Draw()
        {
            if (!initialised)
            {
                Init();
            }

            if (!IsVisible())
            {
                return;
            }

            var rb     = RenderBounds;
            var offset = int2.Zero;

            var svc = world.Players.Select(p => p.PlayerActor.TraitOrDefault <StrategicVictoryConditions>()).FirstOrDefault();

            var totalWidth = svc.Total * 32;
            var curX       = -totalWidth / 2;

            foreach (var a in svc.AllPoints)
            {
                WidgetUtils.DrawRGBA(ChromeProvider.GetImage("strategic", "critical_unowned"), offset + new float2(rb.Left + curX, rb.Top));

                if (world.LocalPlayer != null && WorldUtils.AreMutualAllies(a.Owner, world.LocalPlayer))
                {
                    WidgetUtils.DrawRGBA(ChromeProvider.GetImage("strategic", "player_owned"), offset + new float2(rb.Left + curX, rb.Top));
                }
                else if (!a.Owner.NonCombatant)
                {
                    WidgetUtils.DrawRGBA(ChromeProvider.GetImage("strategic", "enemy_owned"), offset + new float2(rb.Left + curX, rb.Top));
                }

                curX += 32;
            }

            offset += new int2(0, 32);

            if (world.LocalPlayer == null)
            {
                return;
            }
            var pendingWinner = FindFirstWinningPlayer(world);

            if (pendingWinner == null)
            {
                return;
            }
            var winnerSvc = pendingWinner.PlayerActor.Trait <StrategicVictoryConditions>();

            var isVictory = pendingWinner == world.LocalPlayer || !WorldUtils.AreMutualAllies(pendingWinner, world.LocalPlayer);
            var tc        = "Strategic {0} in {1}".F(
                isVictory ? "victory" : "defeat",
                WidgetUtils.FormatTime(winnerSvc.TicksLeft, world.Timestep));

            var font = Game.Renderer.Fonts["Bold"];

            var size = font.Measure(tc);

            font.DrawTextWithContrast(tc, offset + new float2(rb.Left - size.X / 2 + 1, rb.Top + 1), Color.White, Color.Black, 1);
            offset += new int2(0, size.Y + 1);
        }