From abf45686a1187bf0da3fc14464a85ecf0f3ae1a7 Mon Sep 17 00:00:00 2001 From: Alli Date: Fri, 8 Jan 2010 19:05:26 +1300 Subject: [PATCH 01/34] minimap shroud --- OpenRa.Game/Graphics/Minimap.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/OpenRa.Game/Graphics/Minimap.cs b/OpenRa.Game/Graphics/Minimap.cs index fbb13f3ef9..c9a12c6825 100644 --- a/OpenRa.Game/Graphics/Minimap.cs +++ b/OpenRa.Game/Graphics/Minimap.cs @@ -76,7 +76,14 @@ namespace OpenRa.Game.Graphics foreach (var a in Game.world.Actors.Where(a => a.traits.Contains())) bitmap.SetPixel(a.Location.X, a.Location.Y, Chat.paletteColors[(int)a.Owner.Palette]); - + + for (var y = 0; y < 128; y++ ) + for (var x = 0; x < 128; x++ ) + { + if( ! Game.LocalPlayer.Shroud.IsExplored(new int2(x,y))) + bitmap.SetPixel(x, y, Color.Black); + } + sheet.Texture.SetData(bitmap); } From b332785d2eb92b01f279b25ceeabb02250807e46 Mon Sep 17 00:00:00 2001 From: Paul Chote Date: Fri, 8 Jan 2010 19:35:43 +1300 Subject: [PATCH 02/34] Initial GpsSatellite support --- OpenRa.Game/OpenRa.Game.csproj | 1 + OpenRa.Game/Shroud.cs | 14 ++++++++++++++ OpenRa.Game/Traits/GpsSatellite.cs | 22 ++++++++++++++++++++++ units.ini | 2 +- 4 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 OpenRa.Game/Traits/GpsSatellite.cs diff --git a/OpenRa.Game/OpenRa.Game.csproj b/OpenRa.Game/OpenRa.Game.csproj index 80e5bc199f..c9317d181a 100644 --- a/OpenRa.Game/OpenRa.Game.csproj +++ b/OpenRa.Game/OpenRa.Game.csproj @@ -216,6 +216,7 @@ + diff --git a/OpenRa.Game/Shroud.cs b/OpenRa.Game/Shroud.cs index 56cc9efb59..400075390a 100644 --- a/OpenRa.Game/Shroud.cs +++ b/OpenRa.Game/Shroud.cs @@ -26,6 +26,20 @@ namespace OpenRa.Game dirty = true; } + + public void RevealAll() + { + for (int x = 0; x < 128; x++) + for (int y = 0; y < 128; y++) + explored[x, y] = true; + } + + public void HideAll() + { + for (int x = 0; x < 128; x++) + for (int y = 0; y < 128; y++) + explored[x, y] = false; + } Sprite ChooseShroud(int i, int j) { diff --git a/OpenRa.Game/Traits/GpsSatellite.cs b/OpenRa.Game/Traits/GpsSatellite.cs new file mode 100644 index 0000000000..4cb62d968f --- /dev/null +++ b/OpenRa.Game/Traits/GpsSatellite.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OpenRa.Game.Traits +{ + class GpsSatellite + { + public GpsSatellite(Actor self) + { + // TODO: connect this to a special power that calls Activate(); + Activate(self); + } + + public void Activate(Actor self) + { + // TODO: Launch satellite + self.Owner.Shroud.RevealAll(); + } + } +} diff --git a/units.ini b/units.ini index 6ed539a5f0..3b156254a1 100644 --- a/units.ini +++ b/units.ini @@ -345,7 +345,7 @@ MINV ; `Produces` is a category of objects that this building can produce. [ATEK] Description=Allied Tech Center -Traits=Building, RenderBuilding, IronCurtainable +Traits=Building, RenderBuilding, IronCurtainable, GpsSatellite Dimensions=2,2 Footprint=xx xx SelectionPriority=3 From 431036c2f2f0aaac9c680ff55530ed4b19983b53 Mon Sep 17 00:00:00 2001 From: Chris Forbes Date: Fri, 8 Jan 2010 19:48:29 +1300 Subject: [PATCH 03/34] shroud tidy up --- OpenRa.Game/Shroud.cs | 61 +++++++++++++++++++++---------------------- 1 file changed, 30 insertions(+), 31 deletions(-) diff --git a/OpenRa.Game/Shroud.cs b/OpenRa.Game/Shroud.cs index 56cc9efb59..3761d54296 100644 --- a/OpenRa.Game/Shroud.cs +++ b/OpenRa.Game/Shroud.cs @@ -27,20 +27,29 @@ namespace OpenRa.Game dirty = true; } + static readonly byte[] ShroudTiles = + { + 0xf,0xf,0xf,0xf, + 0xf,0xf,0xf,0xf, + 0xf,0xf,0xf,0xf, + 0xf,0xf,0xf,0xf, + 0,7,13,0, + 14,6,12,4, + 11,3,9,1, + 0,2,8,0, + }; + + static readonly byte[] ExtraShroudTiles = + { + 46, 41, 42, 38, + 43, 45, 39, 35, + 40, 37, 44, 34, + 36, 33, 32, 47, + }; + Sprite ChooseShroud(int i, int j) { // bits are for exploredness: left, right, up, down, self - var n = new[] { - 0xf,0xf,0xf,0xf, - 0xf,0x0f,0x0f,0xf, - 0xf,0x0f,0x0f,0xf, - 0xf,0xf,0xf,0xf, - 0,7,13,0, - 14,6,12,4, - 11,3,9,1, - 0,2,8,0, - }; - var v = 0; if (explored[i - 1, j]) v |= 1; if (explored[i + 1, j]) v |= 2; @@ -48,27 +57,17 @@ namespace OpenRa.Game if (explored[i, j + 1]) v |= 8; if (explored[i, j]) v |= 16; - var x = n[v]; + var x = ShroudTiles[v]; + if (x != 0) + return shadowBits[x]; - if (x == 0) - { - // bits are for exploredness: TL, TR, BR, BL - var m = new[] { - 46, 41, 42, 38, - 43, 45, 39, 35, - 40, 37, 44, 34, - 36, 33, 32, 47, - }; - - var u = 0; - if (explored[i - 1, j - 1]) u |= 1; - if (explored[i + 1, j - 1]) u |= 2; - if (explored[i + 1, j + 1]) u |= 4; - if (explored[i - 1, j + 1]) u |= 8; - return shadowBits[m[u]]; - } - - return shadowBits[x]; + // bits are for exploredness: TL, TR, BR, BL + var u = 0; + if (explored[i - 1, j - 1]) u |= 1; + if (explored[i + 1, j - 1]) u |= 2; + if (explored[i + 1, j + 1]) u |= 4; + if (explored[i - 1, j + 1]) u |= 8; + return shadowBits[ExtraShroudTiles[u]]; } public void Draw(SpriteRenderer r) From 27321201ba57896ebcbcf9e730eee223d43b369e Mon Sep 17 00:00:00 2001 From: Chris Forbes Date: Fri, 8 Jan 2010 20:02:24 +1300 Subject: [PATCH 04/34] more pedantry --- OpenRa.Game/Traits/IronCurtainable.cs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/OpenRa.Game/Traits/IronCurtainable.cs b/OpenRa.Game/Traits/IronCurtainable.cs index 685075273f..84374c0a57 100644 --- a/OpenRa.Game/Traits/IronCurtainable.cs +++ b/OpenRa.Game/Traits/IronCurtainable.cs @@ -1,14 +1,9 @@ -using OpenRa.Game.Traits; -using OpenRa.Game.Orders; -using System.Collections.Generic; -using System.Linq; -using System.Drawing; +using System.Linq; using OpenRa.Game.Effects; -using OpenRa.Game.Graphics; namespace OpenRa.Game.Traits { - class IronCurtainable: IOrder, IDamageModifier, ITick + class IronCurtainable : IOrder, IDamageModifier, ITick { int RemainingTicks = 0; @@ -23,10 +18,10 @@ namespace OpenRa.Game.Traits { return (RemainingTicks > 0) ? 0.0f : 1.0f; } - + public Order IssueOrder(Actor self, int2 xy, MouseInput mi, Actor underCursor) { - return null; // Chronoshift order is issued through Chrome. + return null; // IronCurtain order is issued through Chrome. } public void ResolveOrder(Actor self, Order order) @@ -38,7 +33,9 @@ namespace OpenRa.Game.Traits RemainingTicks = (int)(Rules.General.IronCurtain * 60 * 25); Sound.Play("ironcur9.aud"); // Play active anim - var ironCurtain = Game.world.Actors.Where(a => a.Owner == order.Subject.Owner && a.traits.Contains()).FirstOrDefault(); + var ironCurtain = Game.world.Actors + .Where(a => a.Owner == order.Subject.Owner && a.traits.Contains()) + .FirstOrDefault(); if (ironCurtain != null) ironCurtain.traits.Get().PlayCustomAnim(ironCurtain, "active"); } From 8a3f6c501cd11d8a5a525c3b964f9e2cf5763fa3 Mon Sep 17 00:00:00 2001 From: Chris Forbes Date: Fri, 8 Jan 2010 20:39:43 +1300 Subject: [PATCH 05/34] fix prereqs for MSLO --- rules.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rules.ini b/rules.ini index 34338ddc33..8b753341e0 100644 --- a/rules.ini +++ b/rules.ini @@ -1228,7 +1228,7 @@ ROT=30 ; big missile silo [MSLO] -Prerequisite=stek +Prerequisite=stek,atek Primary=none Strength=400 Armor=heavy From 9b4959bbb2783fcc7d70120de8782038ad0426e4 Mon Sep 17 00:00:00 2001 From: Paul Chote Date: Fri, 8 Jan 2010 20:49:25 +1300 Subject: [PATCH 06/34] GPS satellite launch animation --- OpenRa.Game/Effects/GpsSatellite.cs | 33 +++++++++++++++++++++++ OpenRa.Game/Effects/SatelliteLaunch.cs | 37 ++++++++++++++++++++++++++ OpenRa.Game/OpenRa.Game.csproj | 2 ++ OpenRa.Game/Shroud.cs | 2 ++ OpenRa.Game/Traits/GpsSatellite.cs | 31 ++++++++++++--------- sequences.xml | 4 +++ 6 files changed, 97 insertions(+), 12 deletions(-) create mode 100644 OpenRa.Game/Effects/GpsSatellite.cs create mode 100644 OpenRa.Game/Effects/SatelliteLaunch.cs diff --git a/OpenRa.Game/Effects/GpsSatellite.cs b/OpenRa.Game/Effects/GpsSatellite.cs new file mode 100644 index 0000000000..55f58d3200 --- /dev/null +++ b/OpenRa.Game/Effects/GpsSatellite.cs @@ -0,0 +1,33 @@ +using System.Collections.Generic; +using OpenRa.Game.Graphics; +using OpenRa.Game.Traits; + +namespace OpenRa.Game.Effects +{ + class GpsSatellite : IEffect + { + readonly float heightPerTick = 10; + float2 offset; + Animation anim = new Animation("sputnik"); + + public GpsSatellite(float2 offset) + { + this.offset = offset; + anim.PlayRepeating("idle"); + } + + public void Tick() + { + anim.Tick(); + offset.Y -= heightPerTick; + + if (offset.Y < 0) + Game.world.AddFrameEndTask(w => w.Remove(this)); + } + + public IEnumerable Render() + { + yield return new Renderable(anim.Image,offset, PaletteType.Gold); + } + } +} diff --git a/OpenRa.Game/Effects/SatelliteLaunch.cs b/OpenRa.Game/Effects/SatelliteLaunch.cs new file mode 100644 index 0000000000..7cc0d36dca --- /dev/null +++ b/OpenRa.Game/Effects/SatelliteLaunch.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using OpenRa.Game.Graphics; +using OpenRa.Game.Traits; + +namespace OpenRa.Game.Effects +{ + class SatelliteLaunch : IEffect + { + int frame = 0; + Actor a; + Animation doors = new Animation("atek"); + float2 doorOffset = new float2(-4,0); + + public SatelliteLaunch(Actor a) + { + this.a = a; + doors.PlayThen("active", + () => Game.world.AddFrameEndTask(w => w.Remove(this))); + } + + public void Tick() + { + doors.Tick(); + + if (++frame == 19) + { + Game.world.AddFrameEndTask(w => w.Add(new GpsSatellite(a.CenterLocation - .5f * doors.Image.size + doorOffset))); + } + } + + public IEnumerable Render() + { + yield return new Renderable(doors.Image, + a.CenterLocation - .5f * doors.Image.size + doorOffset, PaletteType.Gold); + } + } +} diff --git a/OpenRa.Game/OpenRa.Game.csproj b/OpenRa.Game/OpenRa.Game.csproj index c9317d181a..d78bfb97c2 100644 --- a/OpenRa.Game/OpenRa.Game.csproj +++ b/OpenRa.Game/OpenRa.Game.csproj @@ -83,10 +83,12 @@ + + diff --git a/OpenRa.Game/Shroud.cs b/OpenRa.Game/Shroud.cs index 400075390a..c6ec79a662 100644 --- a/OpenRa.Game/Shroud.cs +++ b/OpenRa.Game/Shroud.cs @@ -32,6 +32,7 @@ namespace OpenRa.Game for (int x = 0; x < 128; x++) for (int y = 0; y < 128; y++) explored[x, y] = true; + dirty = true; } public void HideAll() @@ -39,6 +40,7 @@ namespace OpenRa.Game for (int x = 0; x < 128; x++) for (int y = 0; y < 128; y++) explored[x, y] = false; + dirty = true; } Sprite ChooseShroud(int i, int j) diff --git a/OpenRa.Game/Traits/GpsSatellite.cs b/OpenRa.Game/Traits/GpsSatellite.cs index 4cb62d968f..e71f8a3455 100644 --- a/OpenRa.Game/Traits/GpsSatellite.cs +++ b/OpenRa.Game/Traits/GpsSatellite.cs @@ -1,22 +1,29 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using OpenRa.Game.Effects; namespace OpenRa.Game.Traits { - class GpsSatellite + class GpsSatellite : ITick { - public GpsSatellite(Actor self) - { - // TODO: connect this to a special power that calls Activate(); - Activate(self); - } + int frame = 0; + int revealTicks = 30 * 25; // 30 second delay between launch and reveal + bool fired = false; + public GpsSatellite(Actor self) {} + public void Tick(Actor self) + { + // HACK: Launch after 5 seconds + if (++frame == 150) + Activate(self); + + if (fired && --revealTicks == 0) + { + self.Owner.Shroud.RevealAll(); + } + } public void Activate(Actor self) { - // TODO: Launch satellite - self.Owner.Shroud.RevealAll(); + Game.world.AddFrameEndTask(w => w.Add(new SatelliteLaunch(self))); + fired = true; } } } diff --git a/sequences.xml b/sequences.xml index ba46bfa4a9..252a584725 100644 --- a/sequences.xml +++ b/sequences.xml @@ -94,6 +94,7 @@ + @@ -1030,4 +1031,7 @@ + + + \ No newline at end of file From cc0498314ef372806b89bc373c2556c63a894c64 Mon Sep 17 00:00:00 2001 From: Chris Forbes Date: Fri, 8 Jan 2010 20:57:53 +1300 Subject: [PATCH 07/34] support power impl; incomplete --- OpenRa.Game/Chrome.cs | 80 ++++++++++++++++++----------- OpenRa.Game/GameRules/InfoLoader.cs | 9 ++-- OpenRa.Game/GameRules/TechTree.cs | 2 +- OpenRa.Game/OpenRa.Game.csproj | 1 + OpenRa.Game/Player.cs | 8 +++ OpenRa.Game/SupportPower.cs | 48 +++++++++++++++++ units.ini | 6 ++- 7 files changed, 118 insertions(+), 36 deletions(-) create mode 100644 OpenRa.Game/SupportPower.cs diff --git a/OpenRa.Game/Chrome.cs b/OpenRa.Game/Chrome.cs index 6e69caf944..7aacabe1f6 100644 --- a/OpenRa.Game/Chrome.cs +++ b/OpenRa.Game/Chrome.cs @@ -47,6 +47,7 @@ namespace OpenRa.Game readonly List>> buttons = new List>>(); readonly List digitSprites; readonly Dictionary tabSprites; + readonly Dictionary spsprites; readonly Sprite[] shimSprites; readonly Sprite blank; @@ -55,6 +56,12 @@ namespace OpenRa.Game bool hadRadar = false; bool optionsPressed = false; const int MinRows = 4; + + string currentTab = "Building"; + static string[] groups = new string[] { "Building", "Defense", "Infantry", "Vehicle", "Plane", "Ship" }; + readonly Dictionary sprites; + + const int NumClockFrames = 54; public Chrome(Renderer r) { @@ -116,6 +123,11 @@ namespace OpenRa.Game u => u, u => SpriteSheetBuilder.LoadAllSprites(Rules.UnitInfo[u].Icon ?? (u + "icon"))[0]); + spsprites = Rules.SupportPowerInfo + .ToDictionary( + u => u.Key, + u => SpriteSheetBuilder.LoadAllSprites(u.Value.Image)[0]); + tabSprites = groups.Select( (g, i) => Pair.New(g, OpenRa.Game.Graphics.Util.MakeArray(3, @@ -163,7 +175,6 @@ namespace OpenRa.Game DrawMinimap(); - chromeRenderer.DrawSprite(specialBinSprite, float2.Zero, PaletteType.Chrome); chromeRenderer.DrawSprite(moneyBinSprite, new float2(Game.viewport.Width - 320, 0), PaletteType.Chrome); DrawMoney(); @@ -172,6 +183,7 @@ namespace OpenRa.Game DrawButtons(); int paletteHeight = DrawBuildPalette(currentTab); + DrawSupportPowers(); DrawBuildTabs(paletteHeight); DrawChat(); DrawOptionsMenu(); @@ -220,15 +232,11 @@ namespace OpenRa.Game // Don't let tabs overlap the bevel if (y > paletteOrigin.Y + paletteHeight - tabHeight - 9 && y < paletteOrigin.Y + paletteHeight) - { y += tabHeight; - } // Stick tabs to the edge of the screen if (y > paletteOrigin.Y + paletteHeight) - { x = Game.viewport.Width - tabWidth; - } chromeRenderer.DrawSprite(q.Value[index], new float2(x, y), PaletteType.Chrome); @@ -321,10 +329,8 @@ namespace OpenRa.Game if (!hasChronosphere) repairButton.ReplaceAnim("disabled"); else - { - //repairButton.ReplaceAnim(Game.controller.orderGenerator is RepairOrderGenerator ? "pressed" : "normal"); AddButton(chronoshiftRect, isLmb => HandleChronosphereButton()); - } + buildPaletteRenderer.DrawSprite(repairButton.Image, chronoshiftDrawPos, PaletteType.Chrome); // Iron Curtain @@ -336,13 +342,10 @@ namespace OpenRa.Game if (!hasCurtain) repairButton.ReplaceAnim("disabled"); else - { - //repairButton.ReplaceAnim(Game.controller.orderGenerator is RepairOrderGenerator ? "pressed" : "normal"); AddButton(curtainRect, isLmb => HandleIronCurtainButton()); - } + buildPaletteRenderer.DrawSprite(repairButton.Image, curtainDrawPos, PaletteType.Chrome); - // Repair Rectangle repairRect = new Rectangle(Game.viewport.Width - 120, 5, repairButton.Image.bounds.Width, repairButton.Image.bounds.Height); var repairDrawPos = Game.viewport.Location + new float2(repairRect.Location); @@ -386,7 +389,7 @@ namespace OpenRa.Game buildPaletteRenderer.Flush(); //Options - Rectangle optionsRect = new Rectangle(0 + 40,0, optionsButton.Image.bounds.Width, + Rectangle optionsRect = new Rectangle(0,0, optionsButton.Image.bounds.Width, optionsButton.Image.bounds.Height); var optionsDrawPos = Game.viewport.Location + new float2(optionsRect.Location); @@ -464,22 +467,6 @@ namespace OpenRa.Game renderer.DrawText(line.b, p, line.a); renderer.DrawText(line.c, p + new int2(size.X + 10, 0), Color.White); } - - string currentTab = "Building"; - static string[] groups = new string[] { "Building", "Defense", "Infantry", "Vehicle", "Plane", "Ship" }; - Dictionary sprites; - - const int NumClockFrames = 54; - Func ClockAnimFrame(string group) - { - return () => - { - var queue = Game.LocalPlayer.PlayerActor.traits.Get(); - var producing = queue.CurrentItem( group ); - if (producing == null) return 0; - return (producing.TotalTime - producing.RemainingTime) * NumClockFrames / producing.TotalTime; - }; - } // Return an int telling us the y coordinate at the bottom of the palette int DrawBuildPalette(string queueName) @@ -717,5 +704,40 @@ namespace OpenRa.Game renderer.DrawText(info.LongDesc.Replace( "\\n", "\n" ), p.ToInt2(), Color.White); } } + + void DrawSupportPowers() + { + chromeRenderer.DrawSprite(specialBinSprite, new float2(0,14), PaletteType.Chrome); + chromeRenderer.Flush(); + var y = 24; + foreach (var sp in Game.LocalPlayer.SupportPowers) + { + var image = spsprites[sp.Key]; + if (sp.Value.IsAvailable) + { + var drawPos = Game.viewport.Location + new float2(5, y); + buildPaletteRenderer.DrawSprite(image, drawPos, PaletteType.Chrome); + + clock.PlayFetchIndex("idle", + () => (sp.Value.TotalTime - sp.Value.RemainingTime) + * NumClockFrames / sp.Value.TotalTime); + clock.Tick(); + + buildPaletteRenderer.DrawSprite(clock.Image, drawPos, PaletteType.Chrome); + + if (sp.Value.IsDone) + { + ready.Play("ready"); + buildPaletteRenderer.DrawSprite(ready.Image, + drawPos + new float2((64 - ready.Image.size.X) / 2, 2), + PaletteType.Chrome); + } + + y += 51; + } + } + + buildPaletteRenderer.Flush(); + } } } diff --git a/OpenRa.Game/GameRules/InfoLoader.cs b/OpenRa.Game/GameRules/InfoLoader.cs index 8ce668a69c..6a35b9b510 100644 --- a/OpenRa.Game/GameRules/InfoLoader.cs +++ b/OpenRa.Game/GameRules/InfoLoader.cs @@ -5,10 +5,11 @@ using System.Text; using OpenRa.FileFormats; using OpenRa.Game.Graphics; using IjwFramework.Types; +using System.Collections; namespace OpenRa.Game.GameRules { - class InfoLoader + class InfoLoader : IEnumerable> { readonly Dictionary infos = new Dictionary(); @@ -28,9 +29,7 @@ namespace OpenRa.Game.GameRules get { return infos[name.ToLowerInvariant()]; } } - public IEnumerator> GetEnumerator() - { - return infos.GetEnumerator(); - } + public IEnumerator> GetEnumerator() { return infos.GetEnumerator(); } + IEnumerator IEnumerable.GetEnumerator() { return infos.GetEnumerator(); } } } diff --git a/OpenRa.Game/GameRules/TechTree.cs b/OpenRa.Game/GameRules/TechTree.cs index af0fd79ce4..c2cfb0c230 100755 --- a/OpenRa.Game/GameRules/TechTree.cs +++ b/OpenRa.Game/GameRules/TechTree.cs @@ -43,7 +43,7 @@ namespace OpenRa.Game.GameRules return false; return true; - } + } public IEnumerable BuildableItems( Player player, params string[] categories ) { diff --git a/OpenRa.Game/OpenRa.Game.csproj b/OpenRa.Game/OpenRa.Game.csproj index 80e5bc199f..913dd4655d 100644 --- a/OpenRa.Game/OpenRa.Game.csproj +++ b/OpenRa.Game/OpenRa.Game.csproj @@ -119,6 +119,7 @@ + diff --git a/OpenRa.Game/Player.cs b/OpenRa.Game/Player.cs index bae1f38aa5..b84e10f668 100644 --- a/OpenRa.Game/Player.cs +++ b/OpenRa.Game/Player.cs @@ -28,6 +28,7 @@ namespace OpenRa.Game public bool IsReady; public Shroud Shroud = new Shroud(); + public Dictionary SupportPowers; public Player( Actor playerActor, int index, PaletteType palette, string playerName, Race race, string internalName ) { @@ -37,6 +38,10 @@ namespace OpenRa.Game this.InternalName = internalName; this.PlayerName = playerName; this.Race = race; + + SupportPowers = Rules.SupportPowerInfo.ToDictionary( + spi => spi.Key, + spi => new SupportPower(spi.Value, this)); } void UpdatePower() @@ -126,6 +131,9 @@ namespace OpenRa.Game UpdatePower(); UpdateOreCapacity(); + foreach (var sp in SupportPowers.Values) + sp.Tick(); + if (this == Game.LocalPlayer) { var totalMoney = Cash + Ore; diff --git a/OpenRa.Game/SupportPower.cs b/OpenRa.Game/SupportPower.cs new file mode 100644 index 0000000000..2a6ff5ba56 --- /dev/null +++ b/OpenRa.Game/SupportPower.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using OpenRa.Game.GameRules; + +namespace OpenRa.Game +{ + class SupportPower + { + public readonly SupportPowerInfo Info; + public readonly Player Owner; + + public SupportPower(SupportPowerInfo info, Player owner) + { + Info = info; + Owner = owner; + + RemainingTime = TotalTime = (int)info.ChargeTime * 60 * 25; + } + + public bool IsAvailable { get; private set; } + public bool IsDone { get { return RemainingTime == 0; } } + public int RemainingTime { get; private set; } + public int TotalTime { get; private set; } + + public void Tick() + { + if (Info.GivenAuto) + { + var buildings = Rules.TechTree.GatherBuildings(Owner); + var effectivePrereq = Info.Prerequisite + .Select( a => a.ToLowerInvariant() ) + .Where( a => Rules.UnitInfo[a].Owner + .Any( r => r == Owner.Race )); + + IsAvailable = Info.TechLevel > -1 + && effectivePrereq.Any() + && effectivePrereq.All(a => buildings[a].Count > 0); + } + + if (IsAvailable && (!Info.Powered || Owner.GetPowerState() == PowerState.Normal)) + { + if (RemainingTime > 0) --RemainingTime; + } + } + } +} diff --git a/units.ini b/units.ini index 5c39efaabf..fac05d0bd8 100644 --- a/units.ini +++ b/units.ini @@ -857,6 +857,7 @@ Description=Chronoshift LongDesc=Temporarily teleports a vehicle across the map. Prerequisite=PDOX Image=warpicon +TechLevel=12 [SpyPlanePower] ; free with first AFLD ChargeTime=3 @@ -872,6 +873,7 @@ Description=Atom Bomb LongDesc=Launches a nuclear missile at your target Prerequisite=MSLO Image=atomicon +TechLevel=12 [GpsSatellitePower] ; free with ATEK ChargeTime=8 @@ -880,10 +882,12 @@ LongDesc=Reveals the entire map OneShot=yes Prerequisite=ATEK Image=gpssicon +TechLevel=12 [InvulnerabilityPower] ; the point of IRON ChargeTime=11 Description=Invulnerability LongDesc=Makes a single unit invulnerable for a short time. Image=infxicon -Prerequisite=IRON \ No newline at end of file +Prerequisite=IRON +TechLevel=12 \ No newline at end of file From 7fff532ca1ae109474d4337f1b4abebefc537df3 Mon Sep 17 00:00:00 2001 From: Alli Date: Fri, 8 Jan 2010 21:21:20 +1300 Subject: [PATCH 08/34] some of Thief Steal --- OpenRa.Game/OpenRa.Game.csproj | 2 ++ OpenRa.Game/Orders/UnitOrderGenerator.cs | 1 + OpenRa.Game/Traits/Activities/StealOre.cs | 35 +++++++++++++++++++++++ OpenRa.Game/Traits/ThiefSteal.cs | 30 +++++++++++++++++++ 4 files changed, 68 insertions(+) create mode 100644 OpenRa.Game/Traits/Activities/StealOre.cs create mode 100644 OpenRa.Game/Traits/ThiefSteal.cs diff --git a/OpenRa.Game/OpenRa.Game.csproj b/OpenRa.Game/OpenRa.Game.csproj index 80e5bc199f..c4148588d1 100644 --- a/OpenRa.Game/OpenRa.Game.csproj +++ b/OpenRa.Game/OpenRa.Game.csproj @@ -162,6 +162,7 @@ + @@ -255,6 +256,7 @@ + diff --git a/OpenRa.Game/Orders/UnitOrderGenerator.cs b/OpenRa.Game/Orders/UnitOrderGenerator.cs index dc4019ceea..95ad375bbb 100644 --- a/OpenRa.Game/Orders/UnitOrderGenerator.cs +++ b/OpenRa.Game/Orders/UnitOrderGenerator.cs @@ -86,6 +86,7 @@ namespace OpenRa.Game.Orders case "Infiltrate": return Cursor.Enter; case "Capture": return Cursor.Capture; case "Harvest": return Cursor.AttackMove; + case "Steal" : return Cursor.Enter; default: return null; } diff --git a/OpenRa.Game/Traits/Activities/StealOre.cs b/OpenRa.Game/Traits/Activities/StealOre.cs new file mode 100644 index 0000000000..9b343e1e30 --- /dev/null +++ b/OpenRa.Game/Traits/Activities/StealOre.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OpenRa.Game.Traits.Activities +{ + class StealOre : IActivity + { + Actor target; + public const int CashStolen = 100; //todo: push this out to Rules + + public StealOre(Actor target) { this.target = target; } + + public IActivity NextActivity { get; set; } + + public IActivity Tick(Actor self) + { + if (target == null || target.IsDead) return NextActivity; + + if (target.Owner == self.Owner) return NextActivity; + + target.Owner.TakeCash(CashStolen); + self.Owner.GiveCash(CashStolen); + + // the thief is sacrificed. + self.Health = 0; + Game.world.AddFrameEndTask(w => w.Remove(self)); + + return NextActivity; + } + + public void Cancel(Actor self) { target = null; NextActivity = null; } + } +} diff --git a/OpenRa.Game/Traits/ThiefSteal.cs b/OpenRa.Game/Traits/ThiefSteal.cs new file mode 100644 index 0000000000..4b3f016c26 --- /dev/null +++ b/OpenRa.Game/Traits/ThiefSteal.cs @@ -0,0 +1,30 @@ +using OpenRa.Game.Traits.Activities; + +namespace OpenRa.Game.Traits +{ + class ThiefSteal : IOrder + { + public ThiefSteal(Actor self) { } + + public Order IssueOrder(Actor self, int2 xy, MouseInput mi, Actor underCursor) + { + if (mi.Button != MouseButton.Right) return null; + if (underCursor == null) return null; + if (!underCursor.traits.Contains()) return null; + + // todo: other bits + + return new Order("Steal", self, underCursor, int2.Zero, null); + } + + public void ResolveOrder(Actor self, Order order) + { + if (order.OrderString == "Steal") + { + self.CancelActivity(); + self.QueueActivity(new Move(order.TargetActor, 1)); + self.QueueActivity(new StealOre(order.TargetActor)); + } + } + } +} From 0738c4ebe38ab155789c5a53f00d2b6d578864dd Mon Sep 17 00:00:00 2001 From: Paul Chote Date: Fri, 8 Jan 2010 21:24:52 +1300 Subject: [PATCH 09/34] Allow GPS to be revoked --- OpenRa.Game/Shroud.cs | 51 ++++++++++++++---------------- OpenRa.Game/Traits/GpsSatellite.cs | 2 +- 2 files changed, 24 insertions(+), 29 deletions(-) diff --git a/OpenRa.Game/Shroud.cs b/OpenRa.Game/Shroud.cs index b2f60a891b..697e774406 100644 --- a/OpenRa.Game/Shroud.cs +++ b/OpenRa.Game/Shroud.cs @@ -13,10 +13,21 @@ namespace OpenRa.Game Sprite[] shadowBits = SpriteSheetBuilder.LoadAllSprites("shadow"); Sprite[,] sprites = new Sprite[128, 128]; bool dirty; - - public bool IsExplored(int2 xy) + bool hasGPS = false; + + public bool HasGPS { - return explored[ xy.X, xy.Y ]; + get { return hasGPS; } + set { hasGPS = value; dirty = true;} + } + + public bool IsExplored(int2 xy) { return IsExplored(xy.X, xy.Y); } + public bool IsExplored(int x, int y) + { + if (hasGPS) + return true; + + return explored[ x, y ]; } public void Explore(Actor a) @@ -26,22 +37,6 @@ namespace OpenRa.Game dirty = true; } - - public void RevealAll() - { - for (int x = 0; x < 128; x++) - for (int y = 0; y < 128; y++) - explored[x, y] = true; - dirty = true; - } - - public void HideAll() - { - for (int x = 0; x < 128; x++) - for (int y = 0; y < 128; y++) - explored[x, y] = false; - dirty = true; - } static readonly byte[] ShroudTiles = { @@ -67,11 +62,11 @@ namespace OpenRa.Game { // bits are for exploredness: left, right, up, down, self var v = 0; - if (explored[i - 1, j]) v |= 1; - if (explored[i + 1, j]) v |= 2; - if (explored[i, j - 1]) v |= 4; - if (explored[i, j + 1]) v |= 8; - if (explored[i, j]) v |= 16; + if (IsExplored(i - 1, j)) v |= 1; + if (IsExplored(i + 1, j)) v |= 2; + if (IsExplored(i, j - 1)) v |= 4; + if (IsExplored(i, j + 1)) v |= 8; + if (IsExplored(i, j)) v |= 16; var x = ShroudTiles[v]; if (x != 0) @@ -79,10 +74,10 @@ namespace OpenRa.Game // bits are for exploredness: TL, TR, BR, BL var u = 0; - if (explored[i - 1, j - 1]) u |= 1; - if (explored[i + 1, j - 1]) u |= 2; - if (explored[i + 1, j + 1]) u |= 4; - if (explored[i - 1, j + 1]) u |= 8; + if (IsExplored(i - 1, j - 1)) u |= 1; + if (IsExplored(i + 1, j - 1)) u |= 2; + if (IsExplored(i + 1, j + 1)) u |= 4; + if (IsExplored(i - 1, j + 1)) u |= 8; return shadowBits[ExtraShroudTiles[u]]; } diff --git a/OpenRa.Game/Traits/GpsSatellite.cs b/OpenRa.Game/Traits/GpsSatellite.cs index e71f8a3455..f735f941be 100644 --- a/OpenRa.Game/Traits/GpsSatellite.cs +++ b/OpenRa.Game/Traits/GpsSatellite.cs @@ -17,7 +17,7 @@ namespace OpenRa.Game.Traits if (fired && --revealTicks == 0) { - self.Owner.Shroud.RevealAll(); + self.Owner.Shroud.HasGPS = true; } } public void Activate(Actor self) From 6ff0f82c02ac1ff88926d239de97db1c36a5cb10 Mon Sep 17 00:00:00 2001 From: Chris Forbes Date: Fri, 8 Jan 2010 21:24:52 +1300 Subject: [PATCH 10/34] more support power stuff --- OpenRa.Game/Chrome.cs | 43 +++++++++++++++++++++++++++++++++++++ OpenRa.Game/SupportPower.cs | 4 ++++ units.ini | 8 +++---- 3 files changed, 51 insertions(+), 4 deletions(-) diff --git a/OpenRa.Game/Chrome.cs b/OpenRa.Game/Chrome.cs index 7aacabe1f6..e3c2ee72a6 100644 --- a/OpenRa.Game/Chrome.cs +++ b/OpenRa.Game/Chrome.cs @@ -710,6 +710,10 @@ namespace OpenRa.Game chromeRenderer.DrawSprite(specialBinSprite, new float2(0,14), PaletteType.Chrome); chromeRenderer.Flush(); var y = 24; + + string tooltipItem = null; + int2 tooltipPos = int2.Zero; + foreach (var sp in Game.LocalPlayer.SupportPowers) { var image = spsprites[sp.Key]; @@ -733,11 +737,50 @@ namespace OpenRa.Game PaletteType.Chrome); } + var rect = new Rectangle(5, y, 64, 48); + if (rect.Contains(lastMousePos.ToPoint())) + { + tooltipItem = sp.Key; + tooltipPos = drawPos.ToInt2() + new int2(72, 0) - Game.viewport.Location.ToInt2(); + } + y += 51; } } buildPaletteRenderer.Flush(); + + if (tooltipItem != null) + DrawSupportPowerTooltip(tooltipItem, tooltipPos); + } + + string FormatTime(int ticks) + { + var seconds = ticks / 25; + var minutes = seconds / 60; + + return "{0}:{1}".F(minutes, seconds % 60); + } + + void DrawSupportPowerTooltip(string sp, int2 pos) + { + chromeRenderer.DrawSprite(tooltipSprite, pos, PaletteType.Chrome); + chromeRenderer.Flush(); + + var info = Rules.SupportPowerInfo[sp]; + + pos += new int2(5, 5); + + renderer.DrawText2(info.Description, pos, Color.White); + + var timer = "Charge Time: {0}".F(FormatTime(Game.LocalPlayer.SupportPowers[sp].RemainingTime)); + DrawRightAligned(timer, pos + new int2((int)tooltipSprite.size.X - 10, 0), Color.White); + + if (info.LongDesc != null) + { + pos += new int2(0, 25); + renderer.DrawText(info.LongDesc.Replace("\\n", "\n"), pos, Color.White); + } } } } diff --git a/OpenRa.Game/SupportPower.cs b/OpenRa.Game/SupportPower.cs index 2a6ff5ba56..1d4f6e548f 100644 --- a/OpenRa.Game/SupportPower.cs +++ b/OpenRa.Game/SupportPower.cs @@ -44,5 +44,9 @@ namespace OpenRa.Game if (RemainingTime > 0) --RemainingTime; } } + + public void Activate() + { + } } } diff --git a/units.ini b/units.ini index fac05d0bd8..b3eca27c1d 100644 --- a/units.ini +++ b/units.ini @@ -826,7 +826,7 @@ InvulnerabilityPower [ParadropPower] ; comes free with first AFLD ChargeTime=7 Description=Paratroopers -LongDesc=A Badger drops a squad of Riflemen anywhere on the map +LongDesc=A Badger drops a squad of Riflemen \nanywhere on the map Prerequisite=AFLD TechLevel=5 Image=pinficon @@ -844,7 +844,7 @@ GivenAuto=no [SonarPulsePower] ; picked up in a crate, or by spy -> spen/syrd ChargeTime=10 Description=Sonar Pulse -LongDesc=Reveals all submarines on the map for a short time. +LongDesc=Reveals all submarines on the map for a \nshort time. OneShot=yes Powered=no Image=sonricon @@ -854,7 +854,7 @@ GivenAuto=no [ChronoshiftPower] ; free with Chronosphere... sortof the point. ChargeTime=7 Description=Chronoshift -LongDesc=Temporarily teleports a vehicle across the map. +LongDesc=Temporarily teleports a vehicle across \nthe map. Prerequisite=PDOX Image=warpicon TechLevel=12 @@ -887,7 +887,7 @@ TechLevel=12 [InvulnerabilityPower] ; the point of IRON ChargeTime=11 Description=Invulnerability -LongDesc=Makes a single unit invulnerable for a short time. +LongDesc=Makes a single unit invulnerable for a \nshort time. Image=infxicon Prerequisite=IRON TechLevel=12 \ No newline at end of file From 28746d0bcdb6992a65957d42cec3aba1ed047277 Mon Sep 17 00:00:00 2001 From: Chris Forbes Date: Fri, 8 Jan 2010 21:50:27 +1300 Subject: [PATCH 11/34] support power impl pretty much done --- OpenRa.Game/Chrome.cs | 10 +++++- OpenRa.Game/GameRules/SupportPowerInfo.cs | 1 + OpenRa.Game/OpenRa.Game.csproj | 2 ++ OpenRa.Game/SupportPower.cs | 36 ++++++++++++++++++- .../SupportPowers/ISupportPowerImpl.cs | 12 +++++++ OpenRa.Game/SupportPowers/NullPower.cs | 16 +++++++++ units.ini | 10 +++++- 7 files changed, 84 insertions(+), 3 deletions(-) create mode 100644 OpenRa.Game/SupportPowers/ISupportPowerImpl.cs create mode 100644 OpenRa.Game/SupportPowers/NullPower.cs diff --git a/OpenRa.Game/Chrome.cs b/OpenRa.Game/Chrome.cs index e3c2ee72a6..be8c42280e 100644 --- a/OpenRa.Game/Chrome.cs +++ b/OpenRa.Game/Chrome.cs @@ -729,15 +729,18 @@ namespace OpenRa.Game buildPaletteRenderer.DrawSprite(clock.Image, drawPos, PaletteType.Chrome); + var rect = new Rectangle(5, y, 64, 48); if (sp.Value.IsDone) { ready.Play("ready"); buildPaletteRenderer.DrawSprite(ready.Image, drawPos + new float2((64 - ready.Image.size.X) / 2, 2), PaletteType.Chrome); + + AddButton(rect, HandleSupportPower( sp.Value )); } - var rect = new Rectangle(5, y, 64, 48); + if (rect.Contains(lastMousePos.ToPoint())) { tooltipItem = sp.Key; @@ -754,6 +757,11 @@ namespace OpenRa.Game DrawSupportPowerTooltip(tooltipItem, tooltipPos); } + Action HandleSupportPower(SupportPower sp) + { + return b => { if (b) sp.Activate(); }; + } + string FormatTime(int ticks) { var seconds = ticks / 25; diff --git a/OpenRa.Game/GameRules/SupportPowerInfo.cs b/OpenRa.Game/GameRules/SupportPowerInfo.cs index 6eb34f32be..603d68f494 100644 --- a/OpenRa.Game/GameRules/SupportPowerInfo.cs +++ b/OpenRa.Game/GameRules/SupportPowerInfo.cs @@ -16,5 +16,6 @@ namespace OpenRa.Game.GameRules public readonly string[] Prerequisite = { }; public readonly int TechLevel = -1; public readonly bool GivenAuto = true; + public readonly string Impl = null; } } diff --git a/OpenRa.Game/OpenRa.Game.csproj b/OpenRa.Game/OpenRa.Game.csproj index 913dd4655d..00e9e9b692 100644 --- a/OpenRa.Game/OpenRa.Game.csproj +++ b/OpenRa.Game/OpenRa.Game.csproj @@ -120,6 +120,8 @@ + + diff --git a/OpenRa.Game/SupportPower.cs b/OpenRa.Game/SupportPower.cs index 1d4f6e548f..4e30951c1a 100644 --- a/OpenRa.Game/SupportPower.cs +++ b/OpenRa.Game/SupportPower.cs @@ -3,6 +3,8 @@ using System.Collections.Generic; using System.Linq; using System.Text; using OpenRa.Game.GameRules; +using OpenRa.Game.Traits; +using OpenRa.Game.SupportPowers; namespace OpenRa.Game { @@ -10,15 +12,25 @@ namespace OpenRa.Game { public readonly SupportPowerInfo Info; public readonly Player Owner; + readonly ISupportPowerImpl Impl; + + static ISupportPowerImpl ConstructPowerImpl(string implName) + { + var type = typeof(ISupportPowerImpl).Assembly.GetType( + typeof(ISupportPowerImpl).Namespace + "." + implName, true, false); + var ctor = type.GetConstructor(Type.EmptyTypes); + return (ISupportPowerImpl)ctor.Invoke(new object[] { }); + } public SupportPower(SupportPowerInfo info, Player owner) { Info = info; Owner = owner; - RemainingTime = TotalTime = (int)info.ChargeTime * 60 * 25; + Impl = ConstructPowerImpl(info.Impl); } + public bool IsUsed; public bool IsAvailable { get; private set; } public bool IsDone { get { return RemainingTime == 0; } } public int RemainingTime { get; private set; } @@ -26,6 +38,9 @@ namespace OpenRa.Game public void Tick() { + if (Info.OneShot && IsUsed) + return; + if (Info.GivenAuto) { var buildings = Rules.TechTree.GatherBuildings(Owner); @@ -47,6 +62,25 @@ namespace OpenRa.Game public void Activate() { + if (Impl != null) + Impl.Activate(this); + } + + public void FinishActivate() + { + if (Info.OneShot) + { + IsUsed = true; + IsAvailable = false; + } + RemainingTime = TotalTime; + } + + public void Give(bool requireCharge) // called by crate/spy/etc code + { + IsAvailable = true; + IsUsed = false; + RemainingTime = requireCharge ? TotalTime : 0; } } } diff --git a/OpenRa.Game/SupportPowers/ISupportPowerImpl.cs b/OpenRa.Game/SupportPowers/ISupportPowerImpl.cs new file mode 100644 index 0000000000..b8831e63c2 --- /dev/null +++ b/OpenRa.Game/SupportPowers/ISupportPowerImpl.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OpenRa.Game.SupportPowers +{ + interface ISupportPowerImpl + { + void Activate(SupportPower p); + } +} diff --git a/OpenRa.Game/SupportPowers/NullPower.cs b/OpenRa.Game/SupportPowers/NullPower.cs new file mode 100644 index 0000000000..dadb23b5bd --- /dev/null +++ b/OpenRa.Game/SupportPowers/NullPower.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OpenRa.Game.SupportPowers +{ + class NullPower : ISupportPowerImpl + { + public void Activate(SupportPower p) + { + // if this was a real power, i'd do something here! + throw new NotImplementedException(); + } + } +} diff --git a/units.ini b/units.ini index b3eca27c1d..720f1383b8 100644 --- a/units.ini +++ b/units.ini @@ -830,6 +830,7 @@ LongDesc=A Badger drops a squad of Riflemen \nanywhere on the map Prerequisite=AFLD TechLevel=5 Image=pinficon +Impl=NullPower [ParabombPower] ; picked up in a crate ChargeTime=14 @@ -840,6 +841,7 @@ Powered=no Image=pbmbicon TechLevel=8 GivenAuto=no +Impl=NullPower [SonarPulsePower] ; picked up in a crate, or by spy -> spen/syrd ChargeTime=10 @@ -850,6 +852,7 @@ Powered=no Image=sonricon TechLevel=5 GivenAuto=no +Impl=NullPower [ChronoshiftPower] ; free with Chronosphere... sortof the point. ChargeTime=7 @@ -858,6 +861,7 @@ LongDesc=Temporarily teleports a vehicle across \nthe map. Prerequisite=PDOX Image=warpicon TechLevel=12 +Impl=NullPower [SpyPlanePower] ; free with first AFLD ChargeTime=3 @@ -866,6 +870,7 @@ Description=Spy Plane LongDesc=Reveals an area of the map. Prerequisite=AFLD Image=smigicon +Impl=NullPower [NukePower] ; the point of MSLO ChargeTime=13 @@ -874,6 +879,7 @@ LongDesc=Launches a nuclear missile at your target Prerequisite=MSLO Image=atomicon TechLevel=12 +Impl=NullPower [GpsSatellitePower] ; free with ATEK ChargeTime=8 @@ -883,6 +889,7 @@ OneShot=yes Prerequisite=ATEK Image=gpssicon TechLevel=12 +Impl=NullPower [InvulnerabilityPower] ; the point of IRON ChargeTime=11 @@ -890,4 +897,5 @@ Description=Invulnerability LongDesc=Makes a single unit invulnerable for a \nshort time. Image=infxicon Prerequisite=IRON -TechLevel=12 \ No newline at end of file +TechLevel=12 +Impl=NullPower \ No newline at end of file From a0fafdeed4fdbb146987d0f3195c45ba37683652 Mon Sep 17 00:00:00 2001 From: Chris Forbes Date: Fri, 8 Jan 2010 21:54:29 +1300 Subject: [PATCH 12/34] added auto activate cap for powers; attached to gps satellite --- OpenRa.Game/GameRules/SupportPowerInfo.cs | 1 + OpenRa.Game/SupportPower.cs | 3 +++ units.ini | 1 + 3 files changed, 5 insertions(+) diff --git a/OpenRa.Game/GameRules/SupportPowerInfo.cs b/OpenRa.Game/GameRules/SupportPowerInfo.cs index 603d68f494..df60930d1f 100644 --- a/OpenRa.Game/GameRules/SupportPowerInfo.cs +++ b/OpenRa.Game/GameRules/SupportPowerInfo.cs @@ -17,5 +17,6 @@ namespace OpenRa.Game.GameRules public readonly int TechLevel = -1; public readonly bool GivenAuto = true; public readonly string Impl = null; + public readonly bool AutoActivate = false; } } diff --git a/OpenRa.Game/SupportPower.cs b/OpenRa.Game/SupportPower.cs index 4e30951c1a..1669fc0459 100644 --- a/OpenRa.Game/SupportPower.cs +++ b/OpenRa.Game/SupportPower.cs @@ -58,6 +58,9 @@ namespace OpenRa.Game { if (RemainingTime > 0) --RemainingTime; } + + if (RemainingTime == 0 && Info.AutoActivate) + Activate(); } public void Activate() diff --git a/units.ini b/units.ini index 720f1383b8..a80d24df82 100644 --- a/units.ini +++ b/units.ini @@ -890,6 +890,7 @@ Prerequisite=ATEK Image=gpssicon TechLevel=12 Impl=NullPower +AutoActivate=yes [InvulnerabilityPower] ; the point of IRON ChargeTime=11 From fc2b671b2c77748fe52bb18934106bfa1aa1a9ea Mon Sep 17 00:00:00 2001 From: Paul Chote Date: Fri, 8 Jan 2010 21:59:28 +1300 Subject: [PATCH 13/34] Finish theif logic. TODO: Determine amount to steal --- OpenRa.Game/OpenRa.Game.csproj | 4 ++-- .../Activities/{StealOre.cs => Steal.cs} | 18 ++++++----------- OpenRa.Game/Traits/StoresOre.cs | 20 +++++++++++++++++-- .../Traits/{ThiefSteal.cs => Thief.cs} | 15 +++++++------- OpenRa.Game/Traits/TraitsInterfaces.cs | 1 + units.ini | 2 +- 6 files changed, 35 insertions(+), 25 deletions(-) rename OpenRa.Game/Traits/Activities/{StealOre.cs => Steal.cs} (55%) rename OpenRa.Game/Traits/{ThiefSteal.cs => Thief.cs} (65%) diff --git a/OpenRa.Game/OpenRa.Game.csproj b/OpenRa.Game/OpenRa.Game.csproj index 67a4bd669c..19aeebc77a 100644 --- a/OpenRa.Game/OpenRa.Game.csproj +++ b/OpenRa.Game/OpenRa.Game.csproj @@ -165,7 +165,7 @@ - + @@ -260,7 +260,7 @@ - + diff --git a/OpenRa.Game/Traits/Activities/StealOre.cs b/OpenRa.Game/Traits/Activities/Steal.cs similarity index 55% rename from OpenRa.Game/Traits/Activities/StealOre.cs rename to OpenRa.Game/Traits/Activities/Steal.cs index 9b343e1e30..b0605691c0 100644 --- a/OpenRa.Game/Traits/Activities/StealOre.cs +++ b/OpenRa.Game/Traits/Activities/Steal.cs @@ -5,27 +5,21 @@ using System.Text; namespace OpenRa.Game.Traits.Activities { - class StealOre : IActivity + class Steal : IActivity { Actor target; - public const int CashStolen = 100; //todo: push this out to Rules - - public StealOre(Actor target) { this.target = target; } + + public Steal(Actor target) { this.target = target; } public IActivity NextActivity { get; set; } public IActivity Tick(Actor self) { if (target == null || target.IsDead) return NextActivity; - if (target.Owner == self.Owner) return NextActivity; - - target.Owner.TakeCash(CashStolen); - self.Owner.GiveCash(CashStolen); - - // the thief is sacrificed. - self.Health = 0; - Game.world.AddFrameEndTask(w => w.Remove(self)); + + foreach (var t in target.traits.WithInterface()) + t.OnSteal(target, self); return NextActivity; } diff --git a/OpenRa.Game/Traits/StoresOre.cs b/OpenRa.Game/Traits/StoresOre.cs index 25d16af2d0..9068839e60 100644 --- a/OpenRa.Game/Traits/StoresOre.cs +++ b/OpenRa.Game/Traits/StoresOre.cs @@ -1,9 +1,11 @@ using System.Collections.Generic; - +using System; namespace OpenRa.Game.Traits { - class StoresOre : IPips + class StoresOre : IPips, IAcceptThief { + public const int MaxStealAmount = 100; //todo: How is cash stolen determined? + readonly Actor self; public StoresOre(Actor self) @@ -11,6 +13,20 @@ namespace OpenRa.Game.Traits this.self = self; } + public void OnSteal(Actor self, Actor thief) + { + var cashStolen = Math.Min(MaxStealAmount, self.Owner.Cash); + self.Owner.TakeCash(cashStolen); + thief.Owner.GiveCash(cashStolen); + + if (Game.LocalPlayer == thief.Owner) + Sound.Play("credit1.aud"); + + // the thief is sacrificed. + thief.Health = 0; + Game.world.AddFrameEndTask(w => w.Remove(thief)); + } + public IEnumerable GetPips(Actor self) { for (int i = 0; i < self.Info.OrePips; i++) diff --git a/OpenRa.Game/Traits/ThiefSteal.cs b/OpenRa.Game/Traits/Thief.cs similarity index 65% rename from OpenRa.Game/Traits/ThiefSteal.cs rename to OpenRa.Game/Traits/Thief.cs index 4b3f016c26..362436fae0 100644 --- a/OpenRa.Game/Traits/ThiefSteal.cs +++ b/OpenRa.Game/Traits/Thief.cs @@ -1,19 +1,18 @@ using OpenRa.Game.Traits.Activities; - +using System.Collections.Generic; +using System.Linq; namespace OpenRa.Game.Traits { - class ThiefSteal : IOrder + class Thief : IOrder { - public ThiefSteal(Actor self) { } + public Thief(Actor self) { } public Order IssueOrder(Actor self, int2 xy, MouseInput mi, Actor underCursor) { if (mi.Button != MouseButton.Right) return null; if (underCursor == null) return null; - if (!underCursor.traits.Contains()) return null; - - // todo: other bits - + if (!underCursor.traits.WithInterface().Any()) return null; + return new Order("Steal", self, underCursor, int2.Zero, null); } @@ -23,7 +22,7 @@ namespace OpenRa.Game.Traits { self.CancelActivity(); self.QueueActivity(new Move(order.TargetActor, 1)); - self.QueueActivity(new StealOre(order.TargetActor)); + self.QueueActivity(new Steal(order.TargetActor)); } } } diff --git a/OpenRa.Game/Traits/TraitsInterfaces.cs b/OpenRa.Game/Traits/TraitsInterfaces.cs index 5ee0a485ef..11dc8713ad 100644 --- a/OpenRa.Game/Traits/TraitsInterfaces.cs +++ b/OpenRa.Game/Traits/TraitsInterfaces.cs @@ -17,6 +17,7 @@ namespace OpenRa.Game.Traits interface INotifyDamage { void Damaged(Actor self, AttackInfo e); } interface INotifyBuildComplete { void BuildingComplete (Actor self); } interface INotifyProduction { void UnitProduced(Actor self, Actor other); } + interface IAcceptThief { void OnSteal(Actor self, Actor thief); } interface IOrder { Order IssueOrder( Actor self, int2 xy, MouseInput mi, Actor underCursor ); diff --git a/units.ini b/units.ini index 56b2f4d5a7..9340a2aea3 100644 --- a/units.ini +++ b/units.ini @@ -594,7 +594,7 @@ SelectionSize=12,17,0,-9 [THF] Description=Thief Voice=ThiefVoice -Traits=Unit, Mobile, RenderInfantry, TakeCover, SquishByTank, Passenger +Traits=Unit, Mobile, RenderInfantry, TakeCover, SquishByTank, Passenger, Thief LongDesc=Infiltrates enemy refineries & \nsilos, and steals money stored there.\n Unarmed SelectionSize=12,17,0,-9 [E7] From ad7f188bf51ca6284f0880e3961b772a02b8c6a9 Mon Sep 17 00:00:00 2001 From: Paul Chote Date: Fri, 8 Jan 2010 22:15:42 +1300 Subject: [PATCH 14/34] Steal half the ore a building holds --- OpenRa.Game/Traits/StoresOre.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/OpenRa.Game/Traits/StoresOre.cs b/OpenRa.Game/Traits/StoresOre.cs index 9068839e60..bdabfca5d2 100644 --- a/OpenRa.Game/Traits/StoresOre.cs +++ b/OpenRa.Game/Traits/StoresOre.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System; +using OpenRa.Game.GameRules; namespace OpenRa.Game.Traits { class StoresOre : IPips, IAcceptThief @@ -15,9 +16,10 @@ namespace OpenRa.Game.Traits public void OnSteal(Actor self, Actor thief) { - var cashStolen = Math.Min(MaxStealAmount, self.Owner.Cash); - self.Owner.TakeCash(cashStolen); - thief.Owner.GiveCash(cashStolen); + // Steal half the ore the building holds + var toSteal = (self.Info as BuildingInfo).Storage/2; + self.Owner.TakeCash(toSteal); + thief.Owner.GiveCash(toSteal); if (Game.LocalPlayer == thief.Owner) Sound.Play("credit1.aud"); From 54c28ab74d41fedc9d9cc2897ac23ab9825642b1 Mon Sep 17 00:00:00 2001 From: Chris Forbes Date: Fri, 8 Jan 2010 22:25:12 +1300 Subject: [PATCH 15/34] gps support power wired up properly --- OpenRa.Game/Chrome.cs | 2 +- OpenRa.Game/GameRules/SupportPowerInfo.cs | 2 +- OpenRa.Game/OpenRa.Game.csproj | 1 + OpenRa.Game/SupportPower.cs | 4 ++- OpenRa.Game/SupportPowers/GpsSatellite.cs | 30 +++++++++++++++++++++++ OpenRa.Game/Traits/GpsSatellite.cs | 25 +------------------ units.ini | 2 +- 7 files changed, 38 insertions(+), 28 deletions(-) create mode 100644 OpenRa.Game/SupportPowers/GpsSatellite.cs diff --git a/OpenRa.Game/Chrome.cs b/OpenRa.Game/Chrome.cs index be8c42280e..2966536c79 100644 --- a/OpenRa.Game/Chrome.cs +++ b/OpenRa.Game/Chrome.cs @@ -767,7 +767,7 @@ namespace OpenRa.Game var seconds = ticks / 25; var minutes = seconds / 60; - return "{0}:{1}".F(minutes, seconds % 60); + return "{0:D2}:{1:D2}".F(minutes, seconds % 60); } void DrawSupportPowerTooltip(string sp, int2 pos) diff --git a/OpenRa.Game/GameRules/SupportPowerInfo.cs b/OpenRa.Game/GameRules/SupportPowerInfo.cs index df60930d1f..0f6192c8cd 100644 --- a/OpenRa.Game/GameRules/SupportPowerInfo.cs +++ b/OpenRa.Game/GameRules/SupportPowerInfo.cs @@ -9,7 +9,7 @@ namespace OpenRa.Game.GameRules { public readonly bool Powered = true; public readonly bool OneShot = false; - public readonly int ChargeTime = 0; + public readonly float ChargeTime = 0; public readonly string Image; public readonly string Description = ""; public readonly string LongDesc = ""; diff --git a/OpenRa.Game/OpenRa.Game.csproj b/OpenRa.Game/OpenRa.Game.csproj index 56efe41371..f2d076e61e 100644 --- a/OpenRa.Game/OpenRa.Game.csproj +++ b/OpenRa.Game/OpenRa.Game.csproj @@ -122,6 +122,7 @@ + diff --git a/OpenRa.Game/SupportPower.cs b/OpenRa.Game/SupportPower.cs index 1669fc0459..3f8bab86a6 100644 --- a/OpenRa.Game/SupportPower.cs +++ b/OpenRa.Game/SupportPower.cs @@ -8,6 +8,8 @@ using OpenRa.Game.SupportPowers; namespace OpenRa.Game { + // todo: fix this to route Activate through the orders system (otherwise desync in netplay) + class SupportPower { public readonly SupportPowerInfo Info; @@ -26,7 +28,7 @@ namespace OpenRa.Game { Info = info; Owner = owner; - RemainingTime = TotalTime = (int)info.ChargeTime * 60 * 25; + RemainingTime = TotalTime = (int)(info.ChargeTime * 60 * 25); Impl = ConstructPowerImpl(info.Impl); } diff --git a/OpenRa.Game/SupportPowers/GpsSatellite.cs b/OpenRa.Game/SupportPowers/GpsSatellite.cs new file mode 100644 index 0000000000..a40f959de1 --- /dev/null +++ b/OpenRa.Game/SupportPowers/GpsSatellite.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using OpenRa.Game.Effects; + +namespace OpenRa.Game.SupportPowers +{ + class GpsSatellite : ISupportPowerImpl + { + const int revealDelay = 30 * 25; + + public void Activate(SupportPower p) + { + var launchSite = Game.world.Actors + .FirstOrDefault( a => a.Owner == p.Owner && a.traits.Contains() ); + + if (launchSite == null) + return; + + Game.world.AddFrameEndTask(w => + { + w.Add(new SatelliteLaunch(launchSite)); + w.Add(new DelayedAction(revealDelay, () => p.Owner.Shroud.HasGPS = true)); + }); + + p.FinishActivate(); + } + } +} diff --git a/OpenRa.Game/Traits/GpsSatellite.cs b/OpenRa.Game/Traits/GpsSatellite.cs index f735f941be..3e6f70fd5e 100644 --- a/OpenRa.Game/Traits/GpsSatellite.cs +++ b/OpenRa.Game/Traits/GpsSatellite.cs @@ -2,28 +2,5 @@ namespace OpenRa.Game.Traits { - class GpsSatellite : ITick - { - int frame = 0; - int revealTicks = 30 * 25; // 30 second delay between launch and reveal - bool fired = false; - - public GpsSatellite(Actor self) {} - public void Tick(Actor self) - { - // HACK: Launch after 5 seconds - if (++frame == 150) - Activate(self); - - if (fired && --revealTicks == 0) - { - self.Owner.Shroud.HasGPS = true; - } - } - public void Activate(Actor self) - { - Game.world.AddFrameEndTask(w => w.Add(new SatelliteLaunch(self))); - fired = true; - } - } + class GpsSatellite { public GpsSatellite(Actor self) { } } } diff --git a/units.ini b/units.ini index 7662978c8a..0e151fcc56 100644 --- a/units.ini +++ b/units.ini @@ -889,7 +889,7 @@ OneShot=yes Prerequisite=ATEK Image=gpssicon TechLevel=12 -Impl=NullPower +Impl=GpsSatellite AutoActivate=yes [InvulnerabilityPower] ; the point of IRON From 840a17d255dca7ebe0d2938f7b2c8ef391399656 Mon Sep 17 00:00:00 2001 From: Paul Chote Date: Fri, 8 Jan 2010 22:28:01 +1300 Subject: [PATCH 16/34] Fix powerdown effect + flash --- OpenRa.Game/Effects/PowerDownIndicator.cs | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/OpenRa.Game/Effects/PowerDownIndicator.cs b/OpenRa.Game/Effects/PowerDownIndicator.cs index 185366a078..55858a6f54 100644 --- a/OpenRa.Game/Effects/PowerDownIndicator.cs +++ b/OpenRa.Game/Effects/PowerDownIndicator.cs @@ -9,7 +9,10 @@ namespace OpenRa.Game.Effects Actor a; Building b; Animation anim = new Animation("powerdown"); - + bool removeNextFrame = false; + bool indicatorState = true; + int stateTicks = 0; + public PowerDownIndicator(Actor a) { this.a = a; @@ -19,8 +22,19 @@ namespace OpenRa.Game.Effects public void Tick() { - if (!b.Disabled || a.IsDead) + if (removeNextFrame == true) Game.world.AddFrameEndTask(w => w.Remove(this)); + + // Fix off-by one frame bug with undisabling causing low-power + if (!b.Disabled || a.IsDead) + removeNextFrame = true; + + // Flash power icon + if (++stateTicks == 15) + { + stateTicks = 0; + indicatorState = !indicatorState; + } } public IEnumerable Render() @@ -28,7 +42,7 @@ namespace OpenRa.Game.Effects foreach (var r in a.Render()) yield return r.WithPalette(PaletteType.Disabled); - if (b.ManuallyDisabled) + if (b.ManuallyDisabled && indicatorState) yield return new Renderable(anim.Image, a.CenterLocation - .5f * anim.Image.size, PaletteType.Chrome); } From 2ea729759c23728fc5a51a073158982449cde326 Mon Sep 17 00:00:00 2001 From: Chris Forbes Date: Fri, 8 Jan 2010 22:28:27 +1300 Subject: [PATCH 17/34] rename GpsSatellite trait to GpsLaunchSite --- OpenRa.Game/GameRules/SupportPowerInfo.cs | 6 +----- OpenRa.Game/OpenRa.Game.csproj | 2 +- OpenRa.Game/SupportPower.cs | 3 --- OpenRa.Game/SupportPowers/GpsSatellite.cs | 8 +++----- OpenRa.Game/Traits/GpsLaunchSite.cs | 6 ++++++ OpenRa.Game/Traits/GpsSatellite.cs | 6 ------ units.ini | 2 +- 7 files changed, 12 insertions(+), 21 deletions(-) create mode 100644 OpenRa.Game/Traits/GpsLaunchSite.cs delete mode 100644 OpenRa.Game/Traits/GpsSatellite.cs diff --git a/OpenRa.Game/GameRules/SupportPowerInfo.cs b/OpenRa.Game/GameRules/SupportPowerInfo.cs index 0f6192c8cd..a86f7fda87 100644 --- a/OpenRa.Game/GameRules/SupportPowerInfo.cs +++ b/OpenRa.Game/GameRules/SupportPowerInfo.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - + namespace OpenRa.Game.GameRules { public class SupportPowerInfo diff --git a/OpenRa.Game/OpenRa.Game.csproj b/OpenRa.Game/OpenRa.Game.csproj index f2d076e61e..b714392a7e 100644 --- a/OpenRa.Game/OpenRa.Game.csproj +++ b/OpenRa.Game/OpenRa.Game.csproj @@ -223,7 +223,7 @@ - + diff --git a/OpenRa.Game/SupportPower.cs b/OpenRa.Game/SupportPower.cs index 3f8bab86a6..02e170b8a4 100644 --- a/OpenRa.Game/SupportPower.cs +++ b/OpenRa.Game/SupportPower.cs @@ -1,9 +1,6 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; using OpenRa.Game.GameRules; -using OpenRa.Game.Traits; using OpenRa.Game.SupportPowers; namespace OpenRa.Game diff --git a/OpenRa.Game/SupportPowers/GpsSatellite.cs b/OpenRa.Game/SupportPowers/GpsSatellite.cs index a40f959de1..be748106fa 100644 --- a/OpenRa.Game/SupportPowers/GpsSatellite.cs +++ b/OpenRa.Game/SupportPowers/GpsSatellite.cs @@ -1,8 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Linq; using OpenRa.Game.Effects; +using OpenRa.Game.Traits; namespace OpenRa.Game.SupportPowers { @@ -13,7 +11,7 @@ namespace OpenRa.Game.SupportPowers public void Activate(SupportPower p) { var launchSite = Game.world.Actors - .FirstOrDefault( a => a.Owner == p.Owner && a.traits.Contains() ); + .FirstOrDefault( a => a.Owner == p.Owner && a.traits.Contains() ); if (launchSite == null) return; diff --git a/OpenRa.Game/Traits/GpsLaunchSite.cs b/OpenRa.Game/Traits/GpsLaunchSite.cs new file mode 100644 index 0000000000..639f5b93a1 --- /dev/null +++ b/OpenRa.Game/Traits/GpsLaunchSite.cs @@ -0,0 +1,6 @@ +using OpenRa.Game.Effects; + +namespace OpenRa.Game.Traits +{ + class GpsLaunchSite { public GpsLaunchSite(Actor self) { } } +} diff --git a/OpenRa.Game/Traits/GpsSatellite.cs b/OpenRa.Game/Traits/GpsSatellite.cs deleted file mode 100644 index 3e6f70fd5e..0000000000 --- a/OpenRa.Game/Traits/GpsSatellite.cs +++ /dev/null @@ -1,6 +0,0 @@ -using OpenRa.Game.Effects; - -namespace OpenRa.Game.Traits -{ - class GpsSatellite { public GpsSatellite(Actor self) { } } -} diff --git a/units.ini b/units.ini index 0e151fcc56..8d7d1ac456 100644 --- a/units.ini +++ b/units.ini @@ -348,7 +348,7 @@ MINV ; `Produces` is a category of objects that this building can produce. [ATEK] Description=Allied Tech Center -Traits=Building, RenderBuilding, IronCurtainable, GpsSatellite +Traits=Building, RenderBuilding, IronCurtainable, GpsLaunchSite Dimensions=2,2 Footprint=xx xx SelectionPriority=3 From 86b0ee8c9776d9cc37c1375b0945302bf9ecf51c Mon Sep 17 00:00:00 2001 From: Paul Chote Date: Sat, 9 Jan 2010 00:21:39 +1300 Subject: [PATCH 18/34] Iron curtain power implementation; Remove AutoActivate attribute to be part of the GPS implementation --- OpenRa.Game/Chrome.cs | 38 ---------------- OpenRa.Game/GameRules/SupportPowerInfo.cs | 1 - OpenRa.Game/OpenRa.Game.csproj | 1 + .../Orders/IronCurtainOrderGenerator.cs | 11 ++++- OpenRa.Game/Orders/Order.cs | 14 ++++++ OpenRa.Game/SupportPower.cs | 20 +++++++-- OpenRa.Game/SupportPowers/GpsSatellite.cs | 10 ++++- .../SupportPowers/ISupportPowerImpl.cs | 3 ++ OpenRa.Game/SupportPowers/IronCurtainPower.cs | 43 +++++++++++++++++++ OpenRa.Game/SupportPowers/NullPower.cs | 3 ++ OpenRa.Game/Traits/IronCurtainable.cs | 9 +--- units.ini | 3 +- 12 files changed, 101 insertions(+), 55 deletions(-) create mode 100644 OpenRa.Game/SupportPowers/IronCurtainPower.cs diff --git a/OpenRa.Game/Chrome.cs b/OpenRa.Game/Chrome.cs index 2966536c79..006e3a9b0d 100644 --- a/OpenRa.Game/Chrome.cs +++ b/OpenRa.Game/Chrome.cs @@ -320,32 +320,6 @@ namespace OpenRa.Game void DrawButtons() { - // Chronoshift - Rectangle chronoshiftRect = new Rectangle(6, 14, repairButton.Image.bounds.Width, repairButton.Image.bounds.Height); - var chronoshiftDrawPos = Game.viewport.Location + new float2(chronoshiftRect.Location); - - var hasChronosphere = Game.world.Actors.Any(a => a.Owner == Game.LocalPlayer && a.traits.Contains()); - - if (!hasChronosphere) - repairButton.ReplaceAnim("disabled"); - else - AddButton(chronoshiftRect, isLmb => HandleChronosphereButton()); - - buildPaletteRenderer.DrawSprite(repairButton.Image, chronoshiftDrawPos, PaletteType.Chrome); - - // Iron Curtain - Rectangle curtainRect = new Rectangle(6, 14+50, repairButton.Image.bounds.Width, repairButton.Image.bounds.Height); - var curtainDrawPos = Game.viewport.Location + new float2(curtainRect.Location); - - var hasCurtain = Game.world.Actors.Any(a => a.Owner == Game.LocalPlayer && a.traits.Contains()); - - if (!hasCurtain) - repairButton.ReplaceAnim("disabled"); - else - AddButton(curtainRect, isLmb => HandleIronCurtainButton()); - - buildPaletteRenderer.DrawSprite(repairButton.Image, curtainDrawPos, PaletteType.Chrome); - // Repair Rectangle repairRect = new Rectangle(Game.viewport.Width - 120, 5, repairButton.Image.bounds.Width, repairButton.Image.bounds.Height); var repairDrawPos = Game.viewport.Location + new float2(repairRect.Location); @@ -435,18 +409,6 @@ namespace OpenRa.Game } } - void HandleChronosphereButton() - { - if (Game.controller.ToggleInputMode()) - Sound.Play("slcttgt1.aud"); - } - - void HandleIronCurtainButton() - { - if (Game.controller.ToggleInputMode()) - Sound.Play("slcttgt1.aud"); - } - void DrawChat() { var chatpos = new int2(400, Game.viewport.Height - 20); diff --git a/OpenRa.Game/GameRules/SupportPowerInfo.cs b/OpenRa.Game/GameRules/SupportPowerInfo.cs index 0f6192c8cd..2a84d600ba 100644 --- a/OpenRa.Game/GameRules/SupportPowerInfo.cs +++ b/OpenRa.Game/GameRules/SupportPowerInfo.cs @@ -17,6 +17,5 @@ namespace OpenRa.Game.GameRules public readonly int TechLevel = -1; public readonly bool GivenAuto = true; public readonly string Impl = null; - public readonly bool AutoActivate = false; } } diff --git a/OpenRa.Game/OpenRa.Game.csproj b/OpenRa.Game/OpenRa.Game.csproj index 15182d690a..876f551722 100644 --- a/OpenRa.Game/OpenRa.Game.csproj +++ b/OpenRa.Game/OpenRa.Game.csproj @@ -123,6 +123,7 @@ + diff --git a/OpenRa.Game/Orders/IronCurtainOrderGenerator.cs b/OpenRa.Game/Orders/IronCurtainOrderGenerator.cs index d73c787f19..286fef488b 100644 --- a/OpenRa.Game/Orders/IronCurtainOrderGenerator.cs +++ b/OpenRa.Game/Orders/IronCurtainOrderGenerator.cs @@ -4,11 +4,17 @@ using System.Linq; using System.Text; using OpenRa.Game.GameRules; using OpenRa.Game.Traits; - +using OpenRa.Game.SupportPowers; namespace OpenRa.Game.Orders { class IronCurtainOrderGenerator : IOrderGenerator { + ISupportPowerImpl power; + public IronCurtainOrderGenerator(ISupportPowerImpl power) + { + this.power = power; + } + public IEnumerable Order(int2 xy, MouseInput mi) { if (mi.Button == MouseButton.Right) @@ -31,7 +37,8 @@ namespace OpenRa.Game.Orders if (unit != null) { - yield return new Order("IronCurtain", underCursor, null, int2.Zero, null); + yield return new Order("IronCurtain", underCursor, this.power); + //yield return new Order("IronCurtain", underCursor, null, int2.Zero, null); } } } diff --git a/OpenRa.Game/Orders/Order.cs b/OpenRa.Game/Orders/Order.cs index c2d25713bc..6caa67148d 100644 --- a/OpenRa.Game/Orders/Order.cs +++ b/OpenRa.Game/Orders/Order.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Linq; +using OpenRa.Game.SupportPowers; namespace OpenRa.Game { @@ -31,6 +32,19 @@ namespace OpenRa.Game this.TargetLocation = targetLocation; this.TargetString = targetString; } + // This is a hack - fix me + public readonly ISupportPowerImpl Power; + public Order(string orderString, Actor subject, ISupportPowerImpl power) + { + this.OrderString = orderString; + this.SubjectId = UIntFromActor( subject ); + + this.Power = power; + + this.TargetActorId = UIntFromActor(null); + this.TargetLocation = int2.Zero; + this.TargetString = null; + } public bool Validate() { diff --git a/OpenRa.Game/SupportPower.cs b/OpenRa.Game/SupportPower.cs index 3f8bab86a6..9ae79fecbf 100644 --- a/OpenRa.Game/SupportPower.cs +++ b/OpenRa.Game/SupportPower.cs @@ -37,7 +37,9 @@ namespace OpenRa.Game public bool IsDone { get { return RemainingTime == 0; } } public int RemainingTime { get; private set; } public int TotalTime { get; private set; } - + bool notifiedReady = false; + bool notifiedCharging = false; + public void Tick() { if (Info.OneShot && IsUsed) @@ -59,10 +61,20 @@ namespace OpenRa.Game if (IsAvailable && (!Info.Powered || Owner.GetPowerState() == PowerState.Normal)) { if (RemainingTime > 0) --RemainingTime; + if (!notifiedCharging) + { + Impl.IsChargingNotification(this); + notifiedCharging = true; + } } - if (RemainingTime == 0 && Info.AutoActivate) - Activate(); + if (RemainingTime == 0 + && Impl != null + && !notifiedReady) + { + Impl.IsReadyNotification(this); + notifiedReady = true; + } } public void Activate() @@ -79,6 +91,8 @@ namespace OpenRa.Game IsAvailable = false; } RemainingTime = TotalTime; + notifiedReady = false; + notifiedCharging = false; } public void Give(bool requireCharge) // called by crate/spy/etc code diff --git a/OpenRa.Game/SupportPowers/GpsSatellite.cs b/OpenRa.Game/SupportPowers/GpsSatellite.cs index a40f959de1..6e072ac2c0 100644 --- a/OpenRa.Game/SupportPowers/GpsSatellite.cs +++ b/OpenRa.Game/SupportPowers/GpsSatellite.cs @@ -8,8 +8,16 @@ namespace OpenRa.Game.SupportPowers { class GpsSatellite : ISupportPowerImpl { - const int revealDelay = 30 * 25; + const int revealDelay = 15 * 25; + public void OnFireNotification(Actor a, int2 xy) { } + public void IsChargingNotification(SupportPower p) { } + public void IsReadyNotification(SupportPower p) + { + // Power is auto-activated + Activate(p); + } + public void Activate(SupportPower p) { var launchSite = Game.world.Actors diff --git a/OpenRa.Game/SupportPowers/ISupportPowerImpl.cs b/OpenRa.Game/SupportPowers/ISupportPowerImpl.cs index b8831e63c2..b1ef896690 100644 --- a/OpenRa.Game/SupportPowers/ISupportPowerImpl.cs +++ b/OpenRa.Game/SupportPowers/ISupportPowerImpl.cs @@ -8,5 +8,8 @@ namespace OpenRa.Game.SupportPowers interface ISupportPowerImpl { void Activate(SupportPower p); + void OnFireNotification(Actor target, int2 xy); + void IsChargingNotification(SupportPower p); + void IsReadyNotification(SupportPower p); } } diff --git a/OpenRa.Game/SupportPowers/IronCurtainPower.cs b/OpenRa.Game/SupportPowers/IronCurtainPower.cs new file mode 100644 index 0000000000..67bb0b5c6d --- /dev/null +++ b/OpenRa.Game/SupportPowers/IronCurtainPower.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using OpenRa.Game.Orders; +using OpenRa.Game.Traits; + +namespace OpenRa.Game.SupportPowers +{ + class IronCurtainPower : ISupportPowerImpl + { + public void IsReadyNotification(SupportPower p) + { + Sound.Play("ironrdy1.aud"); + } + + public void IsChargingNotification(SupportPower p) + { + Sound.Play("ironchg1.aud"); + } + + public void OnFireNotification(Actor target, int2 xy) + { + p.FinishActivate(); + Game.controller.CancelInputMode(); + Sound.Play("ironcur9.aud"); + + // Play active anim + var ironCurtain = Game.world.Actors + .Where(a => a.Owner == p.Owner && a.traits.Contains()) + .FirstOrDefault(); + if (ironCurtain != null) + ironCurtain.traits.Get().PlayCustomAnim(ironCurtain, "active"); + } + SupportPower p; + public void Activate(SupportPower p) + { + this.p = p; + // Pick a building to use + Game.controller.orderGenerator = new IronCurtainOrderGenerator(this); + Sound.Play("slcttgt1.aud"); + } + } +} diff --git a/OpenRa.Game/SupportPowers/NullPower.cs b/OpenRa.Game/SupportPowers/NullPower.cs index dadb23b5bd..57f76dc60d 100644 --- a/OpenRa.Game/SupportPowers/NullPower.cs +++ b/OpenRa.Game/SupportPowers/NullPower.cs @@ -7,6 +7,9 @@ namespace OpenRa.Game.SupportPowers { class NullPower : ISupportPowerImpl { + public void OnFireNotification(Actor a, int2 xy) { } + public void IsReadyNotification(SupportPower p) { } + public void IsChargingNotification(SupportPower p) { } public void Activate(SupportPower p) { // if this was a real power, i'd do something here! diff --git a/OpenRa.Game/Traits/IronCurtainable.cs b/OpenRa.Game/Traits/IronCurtainable.cs index 84374c0a57..e49ace50a3 100644 --- a/OpenRa.Game/Traits/IronCurtainable.cs +++ b/OpenRa.Game/Traits/IronCurtainable.cs @@ -28,16 +28,9 @@ namespace OpenRa.Game.Traits { if (order.OrderString == "IronCurtain") { - Game.controller.CancelInputMode(); + order.Power.OnFireNotification(self, self.Location); Game.world.AddFrameEndTask(w => w.Add(new InvulnEffect(self))); RemainingTicks = (int)(Rules.General.IronCurtain * 60 * 25); - Sound.Play("ironcur9.aud"); - // Play active anim - var ironCurtain = Game.world.Actors - .Where(a => a.Owner == order.Subject.Owner && a.traits.Contains()) - .FirstOrDefault(); - if (ironCurtain != null) - ironCurtain.traits.Get().PlayCustomAnim(ironCurtain, "active"); } } } diff --git a/units.ini b/units.ini index abbdf16043..43af439a17 100644 --- a/units.ini +++ b/units.ini @@ -890,7 +890,6 @@ Prerequisite=ATEK Image=gpssicon TechLevel=12 Impl=GpsSatellite -AutoActivate=yes [InvulnerabilityPower] ; the point of IRON ChargeTime=11 @@ -899,4 +898,4 @@ LongDesc=Makes a single unit invulnerable for a \nshort time. Image=infxicon Prerequisite=IRON TechLevel=12 -Impl=NullPower \ No newline at end of file +Impl=IronCurtainPower \ No newline at end of file From 69b3de0a2e6a03df3c7239943935f814bcfcca5f Mon Sep 17 00:00:00 2001 From: Chris Forbes Date: Sat, 9 Jan 2010 00:45:45 +1300 Subject: [PATCH 19/34] really hacky radar shim --- OpenRa.Game/Chrome.cs | 9 +++++---- OpenRa.Game/Game.cs | 3 ++- OpenRa.Game/Graphics/Minimap.cs | 36 +++++++++++++++++++++++++++++---- sequences.xml | 30 ++++++++++++++++++++++----- 4 files changed, 64 insertions(+), 14 deletions(-) diff --git a/OpenRa.Game/Chrome.cs b/OpenRa.Game/Chrome.cs index 2966536c79..3f936ee39d 100644 --- a/OpenRa.Game/Chrome.cs +++ b/OpenRa.Game/Chrome.cs @@ -68,7 +68,7 @@ namespace OpenRa.Game // Positioning of chrome elements // Build palette paletteColumns = 4; - paletteOrigin = new int2(Game.viewport.Width - paletteColumns * 64 - 9 - 20, 240 - 9); + paletteOrigin = new int2(Game.viewport.Width - paletteColumns * 64 - 9 - 20, 282); this.renderer = r; specialBin = new Sheet(renderer, "specialbin.png"); @@ -198,9 +198,10 @@ namespace OpenRa.Game if (hasRadar != hadRadar) Sound.Play((hasRadar) ? "radaron2.aud" : "radardn1.aud"); hadRadar = hasRadar; + + var isJammed = false; // todo: MRJ can do this - if (hasRadar) - Game.minimap.Draw(new float2(Game.viewport.Width - 256, 8)); + Game.minimap.Draw(new float2(Game.viewport.Width - 247, 10), hasRadar, isJammed); } void AddButton(Rectangle r, Action b) { buttons.Add(Pair.New(r, b)); } @@ -278,7 +279,7 @@ namespace OpenRa.Game void DrawPower() { //draw background - float2 powerOrigin = Game.viewport.Location+new float2(Game.viewport.Width - 20, 240 - 9); + float2 powerOrigin = Game.viewport.Location + new float2(Game.viewport.Width - 20, paletteOrigin.Y); buildPaletteRenderer.DrawSprite(powerLevelTopSprite, powerOrigin, PaletteType.Chrome); buildPaletteRenderer.DrawSprite(powerLevelBottomSprite, powerOrigin + new float2(0, powerLevelTopSprite.size.Y), PaletteType.Chrome); diff --git a/OpenRa.Game/Game.cs b/OpenRa.Game/Game.cs index c4b1e52605..271d636519 100644 --- a/OpenRa.Game/Game.cs +++ b/OpenRa.Game/Game.cs @@ -84,11 +84,12 @@ namespace OpenRa.Game Rules.Map.InitOreDensity(); worldRenderer = new WorldRenderer(renderer); - minimap = new Minimap(renderer); SequenceProvider.Initialize(usingAftermath); viewport = new Viewport(clientSize, Rules.Map.Offset, Rules.Map.Offset + Rules.Map.Size, renderer); + minimap = new Minimap(renderer); + BuildingInfluence = new BuildingInfluenceMap(); UnitInfluence = new UnitInfluenceMap(); diff --git a/OpenRa.Game/Graphics/Minimap.cs b/OpenRa.Game/Graphics/Minimap.cs index c9a12c6825..7aa060aac5 100644 --- a/OpenRa.Game/Graphics/Minimap.cs +++ b/OpenRa.Game/Graphics/Minimap.cs @@ -9,25 +9,36 @@ namespace OpenRa.Game.Graphics { Sheet sheet; SpriteRenderer spriteRenderer; + SpriteRenderer shpRenderer; Sprite sprite; Bitmap terrain, oreLayer; + Animation radarAnim, alliesAnim, sovietAnim; public void Tick() { } public Minimap(Renderer r) { sheet = new Sheet(r, new Size(128, 128)); + shpRenderer = new SpriteRenderer(r, true); spriteRenderer = new SpriteRenderer(r, true, r.RgbaSpriteShader); sprite = new Sprite(sheet, new Rectangle(0, 0, 128, 128), TextureChannel.Alpha); + + sovietAnim = new Animation("ussrradr"); + sovietAnim.PlayRepeating("idle"); + alliesAnim = new Animation("natoradr"); + alliesAnim.PlayRepeating("idle"); + radarAnim = Game.LocalPlayer.Race == Race.Allies ? alliesAnim : sovietAnim; } - // todo: extract these from the palette Color[] terrainTypeColors; public void InvalidateOre() { oreLayer = null; } public void Update() { + radarAnim = Game.LocalPlayer.Race == Race.Allies ? alliesAnim : sovietAnim; + radarAnim.Tick(); + if (terrainTypeColors == null) { var pal = new Palette(FileSystem.Open(Rules.Map.Theater + ".pal")); @@ -87,10 +98,27 @@ namespace OpenRa.Game.Graphics sheet.Texture.SetData(bitmap); } - public void Draw(float2 pos) + public void Draw(float2 pos, bool hasRadar, bool isJammed) { - spriteRenderer.DrawSprite(sprite, pos, PaletteType.Chrome, new float2(256,256)); - spriteRenderer.Flush(); + if (hasRadar && radarAnim.CurrentSequence.Name == "idle") + radarAnim.PlayThen("open", () => radarAnim.PlayRepeating("active")); + if (hasRadar && radarAnim.CurrentSequence.Name == "no-power") + radarAnim.PlayBackwardsThen("close", () => radarAnim.PlayRepeating("active")); + if (!hasRadar && radarAnim.CurrentSequence.Name == "active") + radarAnim.PlayThen("close", () => radarAnim.PlayRepeating("no-power")); + if (isJammed && radarAnim.CurrentSequence.Name == "active") + radarAnim.PlayRepeating("jammed"); + if (!isJammed && radarAnim.CurrentSequence.Name == "jammed") + radarAnim.PlayRepeating("active"); + + shpRenderer.DrawSprite(radarAnim.Image, pos + Game.viewport.Location - new float2( 290-256,0), PaletteType.Chrome, new float2(290, 272)); + shpRenderer.Flush(); + + if (radarAnim.CurrentSequence.Name == "active") + { + spriteRenderer.DrawSprite(sprite, pos - new float2((290-256)/2, -5), PaletteType.Chrome, new float2(256, 256)); + spriteRenderer.Flush(); + } } } } diff --git a/sequences.xml b/sequences.xml index cd8b326b66..135736bbcc 100644 --- a/sequences.xml +++ b/sequences.xml @@ -94,7 +94,7 @@ - + @@ -202,9 +202,9 @@ - - - + + + @@ -1031,10 +1031,30 @@ - + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From becfd6eef37fecb405de9a1b8d688f073a3456cc Mon Sep 17 00:00:00 2001 From: Paul Chote Date: Sat, 9 Jan 2010 00:53:48 +1300 Subject: [PATCH 20/34] Chronosphere implementation plus supporting tweaks to Order --- OpenRa.Game/OpenRa.Game.csproj | 1 + .../ChronoshiftDestinationOrderGenerator.cs | 10 ++--- .../ChronosphereSelectOrderGenerator.cs | 10 ++++- .../Orders/IronCurtainOrderGenerator.cs | 11 +++--- OpenRa.Game/Orders/Order.cs | 29 +++++++------- .../SupportPowers/ChronospherePower.cs | 39 +++++++++++++++++++ OpenRa.Game/Traits/Chronoshiftable.cs | 20 ++-------- OpenRa.Game/Traits/IronCurtainable.cs | 2 +- units.ini | 2 +- 9 files changed, 79 insertions(+), 45 deletions(-) create mode 100644 OpenRa.Game/SupportPowers/ChronospherePower.cs diff --git a/OpenRa.Game/OpenRa.Game.csproj b/OpenRa.Game/OpenRa.Game.csproj index 876f551722..ee0dff883d 100644 --- a/OpenRa.Game/OpenRa.Game.csproj +++ b/OpenRa.Game/OpenRa.Game.csproj @@ -122,6 +122,7 @@ + diff --git a/OpenRa.Game/Orders/ChronoshiftDestinationOrderGenerator.cs b/OpenRa.Game/Orders/ChronoshiftDestinationOrderGenerator.cs index a2cd5ef75f..94b728793c 100644 --- a/OpenRa.Game/Orders/ChronoshiftDestinationOrderGenerator.cs +++ b/OpenRa.Game/Orders/ChronoshiftDestinationOrderGenerator.cs @@ -1,19 +1,20 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Drawing; using OpenRa.Game.Traits; +using OpenRa.Game.SupportPowers; namespace OpenRa.Game.Orders { class ChronoshiftDestinationOrderGenerator : IOrderGenerator { public readonly Actor self; - - public ChronoshiftDestinationOrderGenerator(Actor self) + ISupportPowerImpl chronospherePower; + public ChronoshiftDestinationOrderGenerator(Actor self, ISupportPowerImpl chronospherePower) { this.self = self; + this.chronospherePower = chronospherePower; } public IEnumerable Order(int2 xy, MouseInput mi) @@ -23,8 +24,7 @@ namespace OpenRa.Game.Orders Game.controller.CancelInputMode(); yield break; } - - yield return new Order("Chronoshift", self, null, xy, null); + yield return new Order("Chronoshift", self, null, xy, null, chronospherePower); } public void Tick() {} diff --git a/OpenRa.Game/Orders/ChronosphereSelectOrderGenerator.cs b/OpenRa.Game/Orders/ChronosphereSelectOrderGenerator.cs index 4ff3de312d..ddafc11a6f 100644 --- a/OpenRa.Game/Orders/ChronosphereSelectOrderGenerator.cs +++ b/OpenRa.Game/Orders/ChronosphereSelectOrderGenerator.cs @@ -1,14 +1,20 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using OpenRa.Game.GameRules; using OpenRa.Game.Traits; +using OpenRa.Game.SupportPowers; namespace OpenRa.Game.Orders { class ChronosphereSelectOrderGenerator : IOrderGenerator { + ISupportPowerImpl chronospherePower; + public ChronosphereSelectOrderGenerator(ISupportPowerImpl chronospherePower) + { + this.chronospherePower = chronospherePower; + } + public IEnumerable Order(int2 xy, MouseInput mi) { if (mi.Button == MouseButton.Right) @@ -31,7 +37,7 @@ namespace OpenRa.Game.Orders if (unit != null) { - yield return new Order("ChronosphereSelect", underCursor, null, int2.Zero, null); + yield return new Order("ChronosphereSelect", underCursor, null, int2.Zero, null, chronospherePower); } } } diff --git a/OpenRa.Game/Orders/IronCurtainOrderGenerator.cs b/OpenRa.Game/Orders/IronCurtainOrderGenerator.cs index 286fef488b..261c2184df 100644 --- a/OpenRa.Game/Orders/IronCurtainOrderGenerator.cs +++ b/OpenRa.Game/Orders/IronCurtainOrderGenerator.cs @@ -1,18 +1,18 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using OpenRa.Game.GameRules; using OpenRa.Game.Traits; using OpenRa.Game.SupportPowers; + namespace OpenRa.Game.Orders { class IronCurtainOrderGenerator : IOrderGenerator { - ISupportPowerImpl power; - public IronCurtainOrderGenerator(ISupportPowerImpl power) + ISupportPowerImpl ironCurtainPower; + public IronCurtainOrderGenerator(ISupportPowerImpl ironCurtainPower) { - this.power = power; + this.ironCurtainPower = ironCurtainPower; } public IEnumerable Order(int2 xy, MouseInput mi) @@ -37,8 +37,7 @@ namespace OpenRa.Game.Orders if (unit != null) { - yield return new Order("IronCurtain", underCursor, this.power); - //yield return new Order("IronCurtain", underCursor, null, int2.Zero, null); + yield return new Order("IronCurtain", underCursor, null, int2.Zero, null, ironCurtainPower); } } } diff --git a/OpenRa.Game/Orders/Order.cs b/OpenRa.Game/Orders/Order.cs index 6caa67148d..d6c1d4933a 100644 --- a/OpenRa.Game/Orders/Order.cs +++ b/OpenRa.Game/Orders/Order.cs @@ -14,6 +14,9 @@ namespace OpenRa.Game public readonly string TargetString; public bool IsImmediate; + // This is a hack - fix me + public readonly ISupportPowerImpl SupportPowerImpl; + public Actor Subject { get { return ActorFromUInt(SubjectId); } } public Actor TargetActor { get { return ActorFromUInt(TargetActorId); } } public Player Player { get { return Subject.Owner; } } @@ -21,29 +24,27 @@ namespace OpenRa.Game public Order(string orderString, Actor subject, Actor targetActor, int2 targetLocation, string targetString) : this( orderString, UIntFromActor( subject ), - UIntFromActor( targetActor ), targetLocation, targetString ) {} + UIntFromActor( targetActor ), targetLocation, targetString, null ) {} + + public Order(string orderString, Actor subject, + Actor targetActor, int2 targetLocation, string targetString, ISupportPowerImpl power) + : this(orderString, UIntFromActor(subject), + UIntFromActor(targetActor), targetLocation, targetString, power) { } Order(string orderString, uint subjectId, uint targetActorId, int2 targetLocation, string targetString) + : this(orderString, subjectId, + targetActorId, targetLocation, targetString, null) { } + + Order(string orderString, uint subjectId, + uint targetActorId, int2 targetLocation, string targetString, ISupportPowerImpl power) { this.OrderString = orderString; this.SubjectId = subjectId; this.TargetActorId = targetActorId; this.TargetLocation = targetLocation; this.TargetString = targetString; - } - // This is a hack - fix me - public readonly ISupportPowerImpl Power; - public Order(string orderString, Actor subject, ISupportPowerImpl power) - { - this.OrderString = orderString; - this.SubjectId = UIntFromActor( subject ); - - this.Power = power; - - this.TargetActorId = UIntFromActor(null); - this.TargetLocation = int2.Zero; - this.TargetString = null; + this.SupportPowerImpl = power; } public bool Validate() diff --git a/OpenRa.Game/SupportPowers/ChronospherePower.cs b/OpenRa.Game/SupportPowers/ChronospherePower.cs new file mode 100644 index 0000000000..bab8c671eb --- /dev/null +++ b/OpenRa.Game/SupportPowers/ChronospherePower.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Drawing; +using OpenRa.Game.Orders; +using OpenRa.Game.Traits; + +namespace OpenRa.Game.SupportPowers +{ + class ChronospherePower : ISupportPowerImpl + { + public void IsReadyNotification(SupportPower p) { Sound.Play("chrordy1.aud"); } + public void IsChargingNotification(SupportPower p) { Sound.Play("chrochr1.aud"); } + + public void OnFireNotification(Actor target, int2 xy) + { + p.FinishActivate(); + Game.controller.CancelInputMode(); + + Sound.Play("chrono2.aud"); + + foreach (var a in Game.world.Actors.Where(a => a.traits.Contains())) + a.traits.Get().DoChronoshift(); + + // Play chronosphere active anim + var chronosphere = Game.world.Actors.Where(a => a.Owner == p.Owner && a.traits.Contains()).FirstOrDefault(); + + if (chronosphere != null) + chronosphere.traits.Get().PlayCustomAnim(chronosphere, "active"); + } + SupportPower p; + public void Activate(SupportPower p) + { + this.p = p; + Game.controller.orderGenerator = new ChronosphereSelectOrderGenerator(this); + Sound.Play("slcttgt1.aud"); + } + } +} diff --git a/OpenRa.Game/Traits/Chronoshiftable.cs b/OpenRa.Game/Traits/Chronoshiftable.cs index 7f86dca0be..d97bca1ec9 100644 --- a/OpenRa.Game/Traits/Chronoshiftable.cs +++ b/OpenRa.Game/Traits/Chronoshiftable.cs @@ -2,7 +2,6 @@ using OpenRa.Game.Orders; using System.Collections.Generic; using System.Linq; -using System.Drawing; namespace OpenRa.Game.Traits { @@ -40,7 +39,7 @@ namespace OpenRa.Game.Traits { if (order.OrderString == "ChronosphereSelect") { - Game.controller.orderGenerator = new ChronoshiftDestinationOrderGenerator(self); + Game.controller.orderGenerator = new ChronoshiftDestinationOrderGenerator(self, order.SupportPowerImpl); } var movement = self.traits.WithInterface().FirstOrDefault(); @@ -49,37 +48,26 @@ namespace OpenRa.Game.Traits // Cannot chronoshift into unexplored location if (!Game.LocalPlayer.Shroud.IsExplored(order.TargetLocation)) return; - + // Set up return-to-sender info chronoshiftOrigin = self.Location; chronoshiftReturnTicks = (int)(Rules.General.ChronoDuration * 60 * 25); - var chronosphere = Game.world.Actors.Where(a => a.Owner == order.Subject.Owner && a.traits.Contains()).FirstOrDefault(); - // Kill cargo if (Rules.General.ChronoKillCargo && self.traits.Contains()) { var cargo = self.traits.Get(); while (!cargo.IsEmpty(self)) { - if (chronosphere != null) - chronosphere.Owner.Kills++; + order.Player.Kills++; cargo.Unload(self); } } // Set up the teleport - Game.controller.CancelInputMode(); self.CancelActivity(); self.QueueActivity(new Activities.Teleport(order.TargetLocation)); - Sound.Play("chrono2.aud"); - - foreach (var a in Game.world.Actors.Where(a => a.traits.Contains())) - a.traits.Get().DoChronoshift(); - - // Play chronosphere active anim - if (chronosphere != null) - chronosphere.traits.Get().PlayCustomAnim(chronosphere, "active"); + order.SupportPowerImpl.OnFireNotification(self, self.Location); } } diff --git a/OpenRa.Game/Traits/IronCurtainable.cs b/OpenRa.Game/Traits/IronCurtainable.cs index e49ace50a3..a6663f1466 100644 --- a/OpenRa.Game/Traits/IronCurtainable.cs +++ b/OpenRa.Game/Traits/IronCurtainable.cs @@ -28,7 +28,7 @@ namespace OpenRa.Game.Traits { if (order.OrderString == "IronCurtain") { - order.Power.OnFireNotification(self, self.Location); + order.SupportPowerImpl.OnFireNotification(self, self.Location); Game.world.AddFrameEndTask(w => w.Add(new InvulnEffect(self))); RemainingTicks = (int)(Rules.General.IronCurtain * 60 * 25); } diff --git a/units.ini b/units.ini index 43af439a17..b985f2f3ab 100644 --- a/units.ini +++ b/units.ini @@ -861,7 +861,7 @@ LongDesc=Temporarily teleports a vehicle across \nthe map. Prerequisite=PDOX Image=warpicon TechLevel=12 -Impl=NullPower +Impl=ChronospherePower [SpyPlanePower] ; free with first AFLD ChargeTime=3 From c59595d9db05b905de4e8d6223c88b7b95272fd6 Mon Sep 17 00:00:00 2001 From: Chris Forbes Date: Sat, 9 Jan 2010 08:21:10 +1300 Subject: [PATCH 21/34] various renames --- OpenRa.Game/Chrome.cs | 137 ++++++++++++++++---------------- OpenRa.Game/Graphics/Minimap.cs | 8 +- 2 files changed, 74 insertions(+), 71 deletions(-) diff --git a/OpenRa.Game/Chrome.cs b/OpenRa.Game/Chrome.cs index 3f936ee39d..3a3afc674b 100644 --- a/OpenRa.Game/Chrome.cs +++ b/OpenRa.Game/Chrome.cs @@ -15,9 +15,9 @@ namespace OpenRa.Game { readonly Renderer renderer; readonly LineRenderer lineRenderer; - readonly Sheet specialBin; - readonly SpriteRenderer chromeRenderer; - readonly Sprite specialBinSprite; + readonly Sheet chromeTexture; + readonly SpriteRenderer rgbaRenderer; + readonly Sprite[] specialBinSprites; readonly Sprite moneyBinSprite; readonly Sprite tooltipSprite; readonly Sprite powerIndicatorSprite; @@ -39,7 +39,7 @@ namespace OpenRa.Game readonly Sprite optionsBottomRight; readonly Sprite optionsBackground; - readonly SpriteRenderer buildPaletteRenderer; + readonly SpriteRenderer shpRenderer; readonly Animation cantBuild; readonly Animation ready; readonly Animation clock; @@ -71,14 +71,17 @@ namespace OpenRa.Game paletteOrigin = new int2(Game.viewport.Width - paletteColumns * 64 - 9 - 20, 282); this.renderer = r; - specialBin = new Sheet(renderer, "specialbin.png"); - chromeRenderer = new SpriteRenderer(renderer, true, renderer.RgbaSpriteShader); + chromeTexture = new Sheet(renderer, "specialbin.png"); + rgbaRenderer = new SpriteRenderer(renderer, true, renderer.RgbaSpriteShader); lineRenderer = new LineRenderer(renderer); - buildPaletteRenderer = new SpriteRenderer(renderer, true); + shpRenderer = new SpriteRenderer(renderer, true); - specialBinSprite = new Sprite(specialBin, new Rectangle(0, 0, 32, 192), TextureChannel.Alpha); - moneyBinSprite = new Sprite(specialBin, new Rectangle(512 - 320, 0, 320, 32), TextureChannel.Alpha); - tooltipSprite = new Sprite(specialBin, new Rectangle(0, 288, 272, 136), TextureChannel.Alpha); + specialBinSprites = new [] + { + new Sprite(chromeTexture, new Rectangle(0, 0, 32, 192), TextureChannel.Alpha), + }; + moneyBinSprite = new Sprite(chromeTexture, new Rectangle(512 - 320, 0, 320, 32), TextureChannel.Alpha); + tooltipSprite = new Sprite(chromeTexture, new Rectangle(0, 288, 272, 136), TextureChannel.Alpha); var powerIndicator = new Animation("power"); powerIndicator.PlayRepeating("power-level-indicator"); @@ -131,7 +134,7 @@ namespace OpenRa.Game tabSprites = groups.Select( (g, i) => Pair.New(g, OpenRa.Game.Graphics.Util.MakeArray(3, - n => new Sprite(specialBin, + n => new Sprite(chromeTexture, new Rectangle(512 - (n + 1) * 27, 64 + i * 40, 27, 40), TextureChannel.Alpha)))) .ToDictionary(a => a.First, a => a.Second); @@ -140,15 +143,15 @@ namespace OpenRa.Game cantBuild.PlayFetchIndex("idle", () => 0); digitSprites = Graphics.Util.MakeArray(10, a => a) - .Select(n => new Sprite(specialBin, new Rectangle(32 + 13 * n, 0, 13, 17), TextureChannel.Alpha)).ToList(); + .Select(n => new Sprite(chromeTexture, new Rectangle(32 + 13 * n, 0, 13, 17), TextureChannel.Alpha)).ToList(); shimSprites = new[] { - new Sprite( specialBin, new Rectangle( 0, 192, 9, 10 ), TextureChannel.Alpha ), - new Sprite( specialBin, new Rectangle( 0, 202, 9, 10 ), TextureChannel.Alpha ), - new Sprite( specialBin, new Rectangle( 0, 216, 9, 48 ), TextureChannel.Alpha ), - new Sprite( specialBin, new Rectangle( 11, 192, 64, 10 ), TextureChannel.Alpha ), - new Sprite( specialBin, new Rectangle( 11, 202, 64, 10 ), TextureChannel.Alpha ), + new Sprite( chromeTexture, new Rectangle( 0, 192, 9, 10 ), TextureChannel.Alpha ), + new Sprite( chromeTexture, new Rectangle( 0, 202, 9, 10 ), TextureChannel.Alpha ), + new Sprite( chromeTexture, new Rectangle( 0, 216, 9, 48 ), TextureChannel.Alpha ), + new Sprite( chromeTexture, new Rectangle( 11, 192, 64, 10 ), TextureChannel.Alpha ), + new Sprite( chromeTexture, new Rectangle( 11, 202, 64, 10 ), TextureChannel.Alpha ), }; ready = new Animation("pips"); @@ -175,11 +178,11 @@ namespace OpenRa.Game DrawMinimap(); - chromeRenderer.DrawSprite(moneyBinSprite, new float2(Game.viewport.Width - 320, 0), PaletteType.Chrome); + rgbaRenderer.DrawSprite(moneyBinSprite, new float2(Game.viewport.Width - 320, 0), PaletteType.Chrome); DrawMoney(); DrawPower(); - chromeRenderer.Flush(); + rgbaRenderer.Flush(); DrawButtons(); int paletteHeight = DrawBuildPalette(currentTab); @@ -239,14 +242,14 @@ namespace OpenRa.Game if (y > paletteOrigin.Y + paletteHeight) x = Game.viewport.Width - tabWidth; - chromeRenderer.DrawSprite(q.Value[index], new float2(x, y), PaletteType.Chrome); + rgbaRenderer.DrawSprite(q.Value[index], new float2(x, y), PaletteType.Chrome); buttons.Add(Pair.New(new Rectangle(x, y, tabWidth, tabHeight), (Action)(isLmb => currentTab = groupName))); y += tabHeight; } - chromeRenderer.Flush(); + rgbaRenderer.Flush(); } void CheckDeadTab( string groupName ) @@ -268,7 +271,7 @@ namespace OpenRa.Game var x = Game.viewport.Width - 155; foreach (var d in moneyDigits.Reverse()) { - chromeRenderer.DrawSprite(digitSprites[d - '0'], new float2(x, 6), PaletteType.Chrome); + rgbaRenderer.DrawSprite(digitSprites[d - '0'], new float2(x, 6), PaletteType.Chrome); x -= 14; } } @@ -281,9 +284,9 @@ namespace OpenRa.Game //draw background float2 powerOrigin = Game.viewport.Location + new float2(Game.viewport.Width - 20, paletteOrigin.Y); - buildPaletteRenderer.DrawSprite(powerLevelTopSprite, powerOrigin, PaletteType.Chrome); - buildPaletteRenderer.DrawSprite(powerLevelBottomSprite, powerOrigin + new float2(0, powerLevelTopSprite.size.Y), PaletteType.Chrome); - buildPaletteRenderer.Flush(); + shpRenderer.DrawSprite(powerLevelTopSprite, powerOrigin, PaletteType.Chrome); + shpRenderer.DrawSprite(powerLevelBottomSprite, powerOrigin + new float2(0, powerLevelTopSprite.size.Y), PaletteType.Chrome); + shpRenderer.Flush(); float2 top = powerOrigin + new float2(0, 15); float2 bottom = powerOrigin + new float2(0, powerLevelTopSprite.size.Y + powerLevelBottomSprite.size.Y) - new float2(0, 50); @@ -315,8 +318,8 @@ namespace OpenRa.Game //draw indicator float2 drainedPosition = new float2(bottom.X + 2, lastPowerDrainedPos.Value + Game.viewport.Location.Y); - buildPaletteRenderer.DrawSprite(powerIndicatorSprite, drainedPosition, PaletteType.Chrome); - buildPaletteRenderer.Flush(); + shpRenderer.DrawSprite(powerIndicatorSprite, drainedPosition, PaletteType.Chrome); + shpRenderer.Flush(); } void DrawButtons() @@ -332,7 +335,7 @@ namespace OpenRa.Game else AddButton(chronoshiftRect, isLmb => HandleChronosphereButton()); - buildPaletteRenderer.DrawSprite(repairButton.Image, chronoshiftDrawPos, PaletteType.Chrome); + shpRenderer.DrawSprite(repairButton.Image, chronoshiftDrawPos, PaletteType.Chrome); // Iron Curtain Rectangle curtainRect = new Rectangle(6, 14+50, repairButton.Image.bounds.Width, repairButton.Image.bounds.Height); @@ -345,7 +348,7 @@ namespace OpenRa.Game else AddButton(curtainRect, isLmb => HandleIronCurtainButton()); - buildPaletteRenderer.DrawSprite(repairButton.Image, curtainDrawPos, PaletteType.Chrome); + shpRenderer.DrawSprite(repairButton.Image, curtainDrawPos, PaletteType.Chrome); // Repair Rectangle repairRect = new Rectangle(Game.viewport.Width - 120, 5, repairButton.Image.bounds.Width, repairButton.Image.bounds.Height); @@ -360,7 +363,7 @@ namespace OpenRa.Game repairButton.ReplaceAnim(Game.controller.orderGenerator is RepairOrderGenerator ? "pressed" : "normal"); AddButton(repairRect, isLmb => Game.controller.ToggleInputMode()); } - buildPaletteRenderer.DrawSprite(repairButton.Image, repairDrawPos, PaletteType.Chrome); + shpRenderer.DrawSprite(repairButton.Image, repairDrawPos, PaletteType.Chrome); // Sell Rectangle sellRect = new Rectangle(Game.viewport.Width - 80, 5, @@ -371,8 +374,8 @@ namespace OpenRa.Game sellButton.ReplaceAnim(Game.controller.orderGenerator is SellOrderGenerator ? "pressed" : "normal"); AddButton(sellRect, isLmb => Game.controller.ToggleInputMode()); - buildPaletteRenderer.DrawSprite(sellButton.Image, sellDrawPos, PaletteType.Chrome); - buildPaletteRenderer.Flush(); + shpRenderer.DrawSprite(sellButton.Image, sellDrawPos, PaletteType.Chrome); + shpRenderer.Flush(); if (Game.Settings.PowerDownBuildings) { @@ -385,9 +388,9 @@ namespace OpenRa.Game pwrdownButton.ReplaceAnim(Game.controller.orderGenerator is PowerDownOrderGenerator ? "pressed" : "normal"); AddButton(pwrdownRect, isLmb => Game.controller.ToggleInputMode()); - buildPaletteRenderer.DrawSprite(pwrdownButton.Image, pwrdownDrawPos, PaletteType.Chrome); + shpRenderer.DrawSprite(pwrdownButton.Image, pwrdownDrawPos, PaletteType.Chrome); } - buildPaletteRenderer.Flush(); + shpRenderer.Flush(); //Options Rectangle optionsRect = new Rectangle(0,0, optionsButton.Image.bounds.Width, @@ -398,8 +401,8 @@ namespace OpenRa.Game optionsButton.ReplaceAnim(optionsPressed ? "left-pressed" : "left-normal"); AddButton(optionsRect, isLmb => optionsPressed = !optionsPressed); - buildPaletteRenderer.DrawSprite(optionsButton.Image, optionsDrawPos, PaletteType.Chrome); - buildPaletteRenderer.Flush(); + shpRenderer.DrawSprite(optionsButton.Image, optionsDrawPos, PaletteType.Chrome); + shpRenderer.Flush(); renderer.DrawText("Options", new int2(80, -2) , Color.White); } @@ -417,22 +420,22 @@ namespace OpenRa.Game var backgroundDrawPos = menuDrawPos + new float2( (width - optionsBackground.bounds.Width)/2, (height - optionsBackground.bounds.Height)/2); //draw background - buildPaletteRenderer.DrawSprite(optionsBackground, backgroundDrawPos, PaletteType.Chrome); + shpRenderer.DrawSprite(optionsBackground, backgroundDrawPos, PaletteType.Chrome); //draw borders - buildPaletteRenderer.DrawSprite(optionsTopLeft, menuDrawPos, PaletteType.Chrome); - buildPaletteRenderer.DrawSprite(optionsLeft, menuDrawPos + new float2(0, optionsTopLeft.bounds.Height), PaletteType.Chrome); - buildPaletteRenderer.DrawSprite(optionsBottomLeft, menuDrawPos + new float2(0, optionsTopLeft.bounds.Height + optionsLeft.bounds.Height), PaletteType.Chrome); + shpRenderer.DrawSprite(optionsTopLeft, menuDrawPos, PaletteType.Chrome); + shpRenderer.DrawSprite(optionsLeft, menuDrawPos + new float2(0, optionsTopLeft.bounds.Height), PaletteType.Chrome); + shpRenderer.DrawSprite(optionsBottomLeft, menuDrawPos + new float2(0, optionsTopLeft.bounds.Height + optionsLeft.bounds.Height), PaletteType.Chrome); - buildPaletteRenderer.DrawSprite(optionsTop, menuDrawPos + new float2(optionsTopLeft.bounds.Width, 0), PaletteType.Chrome); - buildPaletteRenderer.DrawSprite(optionsTopRight, menuDrawPos + new float2(optionsTopLeft.bounds.Width + optionsTop.bounds.Width, 0), PaletteType.Chrome); + shpRenderer.DrawSprite(optionsTop, menuDrawPos + new float2(optionsTopLeft.bounds.Width, 0), PaletteType.Chrome); + shpRenderer.DrawSprite(optionsTopRight, menuDrawPos + new float2(optionsTopLeft.bounds.Width + optionsTop.bounds.Width, 0), PaletteType.Chrome); - buildPaletteRenderer.DrawSprite(optionsBottom, menuDrawPos + new float2(optionsTopLeft.bounds.Width, optionsTopLeft.bounds.Height + optionsLeft.bounds.Height +adjust), PaletteType.Chrome); - buildPaletteRenderer.DrawSprite(optionsBottomRight, menuDrawPos + new float2(optionsBottomLeft.bounds.Width + optionsBottom.bounds.Width, optionsTopLeft.bounds.Height + optionsLeft.bounds.Height), PaletteType.Chrome); + shpRenderer.DrawSprite(optionsBottom, menuDrawPos + new float2(optionsTopLeft.bounds.Width, optionsTopLeft.bounds.Height + optionsLeft.bounds.Height +adjust), PaletteType.Chrome); + shpRenderer.DrawSprite(optionsBottomRight, menuDrawPos + new float2(optionsBottomLeft.bounds.Width + optionsBottom.bounds.Width, optionsTopLeft.bounds.Height + optionsLeft.bounds.Height), PaletteType.Chrome); - buildPaletteRenderer.DrawSprite(optionsRight, menuDrawPos + new float2(optionsTopLeft.bounds.Width + optionsTop.bounds.Width + adjust + 1, optionsTopRight.bounds.Height), PaletteType.Chrome); + shpRenderer.DrawSprite(optionsRight, menuDrawPos + new float2(optionsTopLeft.bounds.Width + optionsTop.bounds.Width + adjust + 1, optionsTopRight.bounds.Height), PaletteType.Chrome); - buildPaletteRenderer.Flush(); + shpRenderer.Flush(); } } @@ -499,7 +502,7 @@ namespace OpenRa.Game var drawPos = Game.viewport.Location + new float2(rect.Location); var isBuildingSomething = queue.CurrentItem(queueName) != null; - buildPaletteRenderer.DrawSprite(sprites[item], drawPos, PaletteType.Chrome); + shpRenderer.DrawSprite(sprites[item], drawPos, PaletteType.Chrome); var firstOfThis = queue.AllItems(queueName).FirstOrDefault(a => a.Item == item); @@ -515,7 +518,7 @@ namespace OpenRa.Game * NumClockFrames / firstOfThis.TotalTime); clock.Tick(); - buildPaletteRenderer.DrawSprite(clock.Image, drawPos, PaletteType.Chrome); + shpRenderer.DrawSprite(clock.Image, drawPos, PaletteType.Chrome); if (firstOfThis.Done) { @@ -555,28 +558,28 @@ namespace OpenRa.Game { var rect = new Rectangle(origin.X + x * 64, origin.Y + 48 * y, 64, 48); var drawPos = Game.viewport.Location + new float2(rect.Location); - buildPaletteRenderer.DrawSprite(blank, drawPos, PaletteType.Chrome); + shpRenderer.DrawSprite(blank, drawPos, PaletteType.Chrome); AddButton(rect, _ => { }); if (++x == columns) { x = 0; y++; } } foreach (var ob in overlayBits) - buildPaletteRenderer.DrawSprite(ob.First, ob.Second, PaletteType.Chrome); + shpRenderer.DrawSprite(ob.First, ob.Second, PaletteType.Chrome); - buildPaletteRenderer.Flush(); + shpRenderer.Flush(); for (var j = 0; j < y; j++) - chromeRenderer.DrawSprite(shimSprites[2], new float2(origin.X - 9, origin.Y + 48 * j), PaletteType.Chrome); + rgbaRenderer.DrawSprite(shimSprites[2], new float2(origin.X - 9, origin.Y + 48 * j), PaletteType.Chrome); - chromeRenderer.DrawSprite(shimSprites[0], new float2(origin.X - 9, origin.Y - 9), PaletteType.Chrome); - chromeRenderer.DrawSprite(shimSprites[1], new float2(origin.X - 9, origin.Y - 1 + 48 * y), PaletteType.Chrome); + rgbaRenderer.DrawSprite(shimSprites[0], new float2(origin.X - 9, origin.Y - 9), PaletteType.Chrome); + rgbaRenderer.DrawSprite(shimSprites[1], new float2(origin.X - 9, origin.Y - 1 + 48 * y), PaletteType.Chrome); for (var i = 0; i < columns; i++) { - chromeRenderer.DrawSprite(shimSprites[3], new float2(origin.X + 64 * i, origin.Y - 9), PaletteType.Chrome); - chromeRenderer.DrawSprite(shimSprites[4], new float2(origin.X + 64 * i, origin.Y - 1 + 48 * y), PaletteType.Chrome); + rgbaRenderer.DrawSprite(shimSprites[3], new float2(origin.X + 64 * i, origin.Y - 9), PaletteType.Chrome); + rgbaRenderer.DrawSprite(shimSprites[4], new float2(origin.X + 64 * i, origin.Y - 1 + 48 * y), PaletteType.Chrome); } - chromeRenderer.Flush(); + rgbaRenderer.Flush(); if (tooltipItem != null) DrawProductionTooltip(tooltipItem, new int2(Game.viewport.Width, origin.Y + y * 48 + 9)/*tooltipPos*/); @@ -670,8 +673,8 @@ namespace OpenRa.Game void DrawProductionTooltip(string unit, int2 pos) { var p = pos.ToFloat2() - new float2(tooltipSprite.size.X, 0); - chromeRenderer.DrawSprite(tooltipSprite, p, PaletteType.Chrome); - chromeRenderer.Flush(); + rgbaRenderer.DrawSprite(tooltipSprite, p, PaletteType.Chrome); + rgbaRenderer.Flush(); var info = Rules.UnitInfo[unit]; @@ -708,8 +711,8 @@ namespace OpenRa.Game void DrawSupportPowers() { - chromeRenderer.DrawSprite(specialBinSprite, new float2(0,14), PaletteType.Chrome); - chromeRenderer.Flush(); + rgbaRenderer.DrawSprite(specialBinSprites[0], new float2(0,14), PaletteType.Chrome); + rgbaRenderer.Flush(); var y = 24; string tooltipItem = null; @@ -721,20 +724,20 @@ namespace OpenRa.Game if (sp.Value.IsAvailable) { var drawPos = Game.viewport.Location + new float2(5, y); - buildPaletteRenderer.DrawSprite(image, drawPos, PaletteType.Chrome); + shpRenderer.DrawSprite(image, drawPos, PaletteType.Chrome); clock.PlayFetchIndex("idle", () => (sp.Value.TotalTime - sp.Value.RemainingTime) * NumClockFrames / sp.Value.TotalTime); clock.Tick(); - buildPaletteRenderer.DrawSprite(clock.Image, drawPos, PaletteType.Chrome); + shpRenderer.DrawSprite(clock.Image, drawPos, PaletteType.Chrome); var rect = new Rectangle(5, y, 64, 48); if (sp.Value.IsDone) { ready.Play("ready"); - buildPaletteRenderer.DrawSprite(ready.Image, + shpRenderer.DrawSprite(ready.Image, drawPos + new float2((64 - ready.Image.size.X) / 2, 2), PaletteType.Chrome); @@ -752,7 +755,7 @@ namespace OpenRa.Game } } - buildPaletteRenderer.Flush(); + shpRenderer.Flush(); if (tooltipItem != null) DrawSupportPowerTooltip(tooltipItem, tooltipPos); @@ -773,8 +776,8 @@ namespace OpenRa.Game void DrawSupportPowerTooltip(string sp, int2 pos) { - chromeRenderer.DrawSprite(tooltipSprite, pos, PaletteType.Chrome); - chromeRenderer.Flush(); + rgbaRenderer.DrawSprite(tooltipSprite, pos, PaletteType.Chrome); + rgbaRenderer.Flush(); var info = Rules.SupportPowerInfo[sp]; diff --git a/OpenRa.Game/Graphics/Minimap.cs b/OpenRa.Game/Graphics/Minimap.cs index 7aa060aac5..73b619a581 100644 --- a/OpenRa.Game/Graphics/Minimap.cs +++ b/OpenRa.Game/Graphics/Minimap.cs @@ -8,7 +8,7 @@ namespace OpenRa.Game.Graphics class Minimap { Sheet sheet; - SpriteRenderer spriteRenderer; + SpriteRenderer rgbaRenderer; SpriteRenderer shpRenderer; Sprite sprite; Bitmap terrain, oreLayer; @@ -20,7 +20,7 @@ namespace OpenRa.Game.Graphics { sheet = new Sheet(r, new Size(128, 128)); shpRenderer = new SpriteRenderer(r, true); - spriteRenderer = new SpriteRenderer(r, true, r.RgbaSpriteShader); + rgbaRenderer = new SpriteRenderer(r, true, r.RgbaSpriteShader); sprite = new Sprite(sheet, new Rectangle(0, 0, 128, 128), TextureChannel.Alpha); sovietAnim = new Animation("ussrradr"); @@ -116,8 +116,8 @@ namespace OpenRa.Game.Graphics if (radarAnim.CurrentSequence.Name == "active") { - spriteRenderer.DrawSprite(sprite, pos - new float2((290-256)/2, -5), PaletteType.Chrome, new float2(256, 256)); - spriteRenderer.Flush(); + rgbaRenderer.DrawSprite(sprite, pos - new float2((290-256)/2, -5), PaletteType.Chrome, new float2(256, 256)); + rgbaRenderer.Flush(); } } } From c67f686ad7becc3dea171e5de27032372c7e8544 Mon Sep 17 00:00:00 2001 From: Chris Forbes Date: Sat, 9 Jan 2010 08:52:15 +1300 Subject: [PATCH 22/34] routed invuln & chrono powers --- OpenRa.Game/Chrome.cs | 55 ++------ OpenRa.Game/Game Code.cd | 169 ----------------------- OpenRa.Game/Graphics/Graphics.cd | 131 ------------------ OpenRa.Game/OpenRa.Game.csproj | 6 +- OpenRa.Game/SupportPowers/Chronoshift.cs | 15 ++ OpenRa.Game/SupportPowers/IronCurtain.cs | 15 ++ SequenceEditor/Program.cs | 7 +- units.ini | 4 +- 8 files changed, 51 insertions(+), 351 deletions(-) delete mode 100644 OpenRa.Game/Game Code.cd delete mode 100644 OpenRa.Game/Graphics/Graphics.cd create mode 100644 OpenRa.Game/SupportPowers/Chronoshift.cs create mode 100644 OpenRa.Game/SupportPowers/IronCurtain.cs diff --git a/OpenRa.Game/Chrome.cs b/OpenRa.Game/Chrome.cs index 3a3afc674b..e350f282f6 100644 --- a/OpenRa.Game/Chrome.cs +++ b/OpenRa.Game/Chrome.cs @@ -78,7 +78,9 @@ namespace OpenRa.Game specialBinSprites = new [] { - new Sprite(chromeTexture, new Rectangle(0, 0, 32, 192), TextureChannel.Alpha), + new Sprite(chromeTexture, new Rectangle(0, 0, 32, 51), TextureChannel.Alpha), + new Sprite(chromeTexture, new Rectangle(0, 51, 32, 51 /*144*/), TextureChannel.Alpha), + new Sprite(chromeTexture, new Rectangle(0, 192-39, 32, 39 ), TextureChannel.Alpha), }; moneyBinSprite = new Sprite(chromeTexture, new Rectangle(512 - 320, 0, 320, 32), TextureChannel.Alpha); tooltipSprite = new Sprite(chromeTexture, new Rectangle(0, 288, 272, 136), TextureChannel.Alpha); @@ -324,32 +326,6 @@ namespace OpenRa.Game void DrawButtons() { - // Chronoshift - Rectangle chronoshiftRect = new Rectangle(6, 14, repairButton.Image.bounds.Width, repairButton.Image.bounds.Height); - var chronoshiftDrawPos = Game.viewport.Location + new float2(chronoshiftRect.Location); - - var hasChronosphere = Game.world.Actors.Any(a => a.Owner == Game.LocalPlayer && a.traits.Contains()); - - if (!hasChronosphere) - repairButton.ReplaceAnim("disabled"); - else - AddButton(chronoshiftRect, isLmb => HandleChronosphereButton()); - - shpRenderer.DrawSprite(repairButton.Image, chronoshiftDrawPos, PaletteType.Chrome); - - // Iron Curtain - Rectangle curtainRect = new Rectangle(6, 14+50, repairButton.Image.bounds.Width, repairButton.Image.bounds.Height); - var curtainDrawPos = Game.viewport.Location + new float2(curtainRect.Location); - - var hasCurtain = Game.world.Actors.Any(a => a.Owner == Game.LocalPlayer && a.traits.Contains()); - - if (!hasCurtain) - repairButton.ReplaceAnim("disabled"); - else - AddButton(curtainRect, isLmb => HandleIronCurtainButton()); - - shpRenderer.DrawSprite(repairButton.Image, curtainDrawPos, PaletteType.Chrome); - // Repair Rectangle repairRect = new Rectangle(Game.viewport.Width - 120, 5, repairButton.Image.bounds.Width, repairButton.Image.bounds.Height); var repairDrawPos = Game.viewport.Location + new float2(repairRect.Location); @@ -438,19 +414,7 @@ namespace OpenRa.Game shpRenderer.Flush(); } } - - void HandleChronosphereButton() - { - if (Game.controller.ToggleInputMode()) - Sound.Play("slcttgt1.aud"); - } - - void HandleIronCurtainButton() - { - if (Game.controller.ToggleInputMode()) - Sound.Play("slcttgt1.aud"); - } - + void DrawChat() { var chatpos = new int2(400, Game.viewport.Height - 20); @@ -711,8 +675,18 @@ namespace OpenRa.Game void DrawSupportPowers() { + var numPowers = Game.LocalPlayer.SupportPowers.Values + .Where(a => a.IsAvailable).Count(); + + if (numPowers == 0) return; + rgbaRenderer.DrawSprite(specialBinSprites[0], new float2(0,14), PaletteType.Chrome); + for (var i = 1; i < numPowers; i++) + rgbaRenderer.DrawSprite(specialBinSprites[1], new float2(0, 14 + i * 51), PaletteType.Chrome); + rgbaRenderer.DrawSprite(specialBinSprites[2], new float2(0, 14 + numPowers * 51), PaletteType.Chrome); + rgbaRenderer.Flush(); + var y = 24; string tooltipItem = null; @@ -744,7 +718,6 @@ namespace OpenRa.Game AddButton(rect, HandleSupportPower( sp.Value )); } - if (rect.Contains(lastMousePos.ToPoint())) { tooltipItem = sp.Key; diff --git a/OpenRa.Game/Game Code.cd b/OpenRa.Game/Game Code.cd deleted file mode 100644 index 9121b137c1..0000000000 --- a/OpenRa.Game/Game Code.cd +++ /dev/null @@ -1,169 +0,0 @@ - - - - - - - - AAaAkDQAABJAAQEEBEECEgAQQUBAAAAAIYAKBCAAwiA= - Game.cs - - - - - - - - - - - - - - AAACAACoAAAAAAAAAAQDEgQAABAAABAAAAAAKAACCAA= - Controller.cs - - - - - - - - - - - - AAIAAAAABAAACABCAAYAEEAAAABAAAAAAAAgAEEIwBE= - Graphics\Viewport.cs - - - - - - - - AAIAACABAAABgAAAAYQABAAEAAAAAAAAAAAAAAAAQBA= - World.cs - - - - - - - - - - - AgEACACAAAAAAAAAAQIAEIAkAQQAAAAAABAgAEAAQgA= - Actor.cs - - - - - - - - - ACIAAAKAAJAgwiAAgAAAgFQAJAhQAHAAGCACAADIRAA= - GameRules\UnitInfo.cs - - - - - - - - QEEEAAQAAAIAQQAACAMAACCAAAAAAA0gCAEAAQABQAA= - Player.cs - - - - - - AAAAAAAAAAQAAAAAAAAAAAABAQAAAAAAAAAAAAAAAAg= - GameRules\UnitInfo.cs - - - - - - AAJQAAAIAAAAgAAACAAAABIAAAICAAABAAAAQAAAAgA= - GameRules\UnitInfo.cs - - - - - - AAAAAAAAAAAAEEAAAAABIAAAAAAAAAAAAAAAACAAAQA= - GameRules\UnitInfo.cs - - - - - - AAAAAAAAAAAAAEAAAAAAAAAAAAAEAAAAAAAAAAAAAAA= - GameRules\UnitInfo.cs - - - - - - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= - GameRules\ActorInfo.cs - - - - - - - - AAAAAAAAAAAAAAAgAACAAAICAAgAEoAAMAAAAAAAAgA= - PathFinder.cs - - - - - - AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAQAA= - IOrderGenerator.cs - - - - \ No newline at end of file diff --git a/OpenRa.Game/Graphics/Graphics.cd b/OpenRa.Game/Graphics/Graphics.cd deleted file mode 100644 index 54372aa050..0000000000 --- a/OpenRa.Game/Graphics/Graphics.cd +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - AAQCgACAAAAAAAAAAAAAAAAAAAAEABAEgAAAAQQIQAA= - Graphics\Animation.cs - - - - - - - - - AAAAAQAABAAAgAAAAIYAAEAAAABCAAAAAABgAAAAgAE= - Graphics\Viewport.cs - - - - - - - - - AAQAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAQAAAAA= - Graphics\HardwarePalette.cs - - - - - - AIQAAAAAAAAAggAABAIAIAQCAAAAAGAAAAAAAAAQAAA= - Graphics\Region.cs - - - - - - QACAEAAGAAAAAgMAAAAAAAAAAAAAAAAAAAAAAEAAAAA= - Graphics\Renderer.cs - - - - - - AAAAAAAAAACAgAAACAgAAAAIAAAAAgAAAAIAAAAggAA= - Graphics\Sheet.cs - - - - - - - - - AQIACAAAAAAAIQAAAAAAAAAAgAAAAIAAAEAAAAACgAA= - Graphics\SheetBuilder.cs - - - - - - - - - AAAAAAAAAQAAIAAAAIAAAAAAAAAAAAABAAACAAAEAgA= - Graphics\Sprite.cs - - - - - - - - - AAAQQAAAAECAAAAAAAAAAAAAABAQABAAAAAAAACIwAQ= - Graphics\SpriteRenderer.cs - - - - - - - - - - AAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAACAAAA= - Graphics\SpriteSheetBuilder.cs - - - - - - - - - AACQEAAAAAAAAgAAAAAACAAAABgAAAAAAAAAAAAAgAA= - Graphics\TerrainRenderer.cs - - - - - - - - - - AAAAAAAAgAAAAAAAAAAAAAAAAQAAAAAAAQAAAACAAAA= - Graphics\UnitSheetBuilder.cs - - - - - - - - - AAAAAAAAAAAAAAAAAAAAAAAAAAgAAACAAFJgAQAAAAA= - Graphics\Vertex.cs - - - - - - AAACAAAAAAAAAgAAAAAAAAAAAAAAABAAAAAAABAAAAA= - Graphics\Sprite.cs - - - - \ No newline at end of file diff --git a/OpenRa.Game/OpenRa.Game.csproj b/OpenRa.Game/OpenRa.Game.csproj index 881e1f1d31..a14b7ec48e 100644 --- a/OpenRa.Game/OpenRa.Game.csproj +++ b/OpenRa.Game/OpenRa.Game.csproj @@ -122,7 +122,9 @@ + + @@ -308,10 +310,6 @@ false - - - - - + \ No newline at end of file diff --git a/OpenRa.Game/Orders/Order.cs b/OpenRa.Game/Orders/Order.cs index 754207101b..828d44b4d8 100644 --- a/OpenRa.Game/Orders/Order.cs +++ b/OpenRa.Game/Orders/Order.cs @@ -30,7 +30,7 @@ namespace OpenRa.Game this.SubjectId = subjectId; this.TargetActorId = targetActorId; this.TargetLocation = targetLocation; - this.TargetString = targetString; + this.TargetString = targetString; } public bool Validate() diff --git a/OpenRa.Game/Sync.cs b/OpenRa.Game/Sync.cs new file mode 100755 index 0000000000..10261f506f --- /dev/null +++ b/OpenRa.Game/Sync.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Reflection; + +namespace OpenRa.Game +{ + class SyncAttribute : Attribute { } + + static class Sync + { + public static int CalculateSyncHash( object obj ) + { + int hash = 0; // TODO: start with a more interesting initial value. + + // TODO: cache the Syncable fields; maybe use DynamicMethod to make this fast? + // FIXME: does GetFields even give fields in a well-defined order? + const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; + foreach( var field in obj.GetType().GetFields( bf ).Where( x => x.GetCustomAttributes( typeof( SyncAttribute ), true ).Length != 0 ) ) + { + if( field.FieldType == typeof( int ) ) + hash ^= (int)field.GetValue( obj ); + + else if( field.FieldType == typeof( Actor ) ) + { + var a = (Actor)field.GetValue( obj ); + if( a != null ) + hash ^= (int)( a.ActorID << 16 ); + } + else if( field.FieldType == typeof( TypeDictionary ) ) + { + foreach( var o in (TypeDictionary)field.GetValue( obj ) ) + hash += CalculateSyncHash( o ); + } + else if( field.FieldType == typeof( bool ) ) + hash ^= (bool)field.GetValue( obj ) ? 0xaaa : 0x555; + + else if( field.FieldType == typeof( int2 ) ) + { + var i2 = (int2)field.GetValue( obj ); + hash ^= ( ( i2.X * 5 ) ^ ( i2.Y * 3 ) ) / 4; + } + else if( field.FieldType == typeof( Player ) ) + { + var p = (Player)field.GetValue( obj ); + if( p != null ) + hash ^= p.Index * 0x567; + } + else + throw new NotImplementedException( "SyncAttribute on unhashable field" ); + } + + return hash; + } + } +} diff --git a/OpenRa.Game/Traits/AttackBase.cs b/OpenRa.Game/Traits/AttackBase.cs index 9cc97b871f..6b78edfe9c 100644 --- a/OpenRa.Game/Traits/AttackBase.cs +++ b/OpenRa.Game/Traits/AttackBase.cs @@ -8,10 +8,12 @@ namespace OpenRa.Game.Traits { class AttackBase : IIssueOrder, IResolveOrder, ITick { - public Actor target; + [Sync] public Actor target; // time (in frames) until each weapon can fire again. + [Sync] protected int primaryFireDelay = 0; + [Sync] protected int secondaryFireDelay = 0; int primaryBurst; diff --git a/OpenRa.Game/Traits/AttackFrontal.cs b/OpenRa.Game/Traits/AttackFrontal.cs index e10b596652..a300fc308d 100644 --- a/OpenRa.Game/Traits/AttackFrontal.cs +++ b/OpenRa.Game/Traits/AttackFrontal.cs @@ -7,7 +7,7 @@ namespace OpenRa.Game.Traits public AttackFrontal(Actor self, int facingTolerance) : base(self) { FacingTolerance = facingTolerance; } - int FacingTolerance; + readonly int FacingTolerance; public override void Tick(Actor self) { diff --git a/OpenRa.Game/Traits/Building.cs b/OpenRa.Game/Traits/Building.cs index 927fc58eee..1fa3538314 100644 --- a/OpenRa.Game/Traits/Building.cs +++ b/OpenRa.Game/Traits/Building.cs @@ -13,7 +13,9 @@ namespace OpenRa.Game.Traits { readonly Actor self; public readonly BuildingInfo unitInfo; + [Sync] bool isRepairing = false; + [Sync] bool manuallyDisabled = false; public bool ManuallyDisabled { get { return manuallyDisabled; } } public bool Disabled { get { return (manuallyDisabled || (unitInfo.Powered && self.Owner.GetPowerState() != PowerState.Normal)); } } diff --git a/OpenRa.Game/Traits/ChronoshiftDeploy.cs b/OpenRa.Game/Traits/ChronoshiftDeploy.cs index 16aeb0d9fe..2cc8a2a9a4 100644 --- a/OpenRa.Game/Traits/ChronoshiftDeploy.cs +++ b/OpenRa.Game/Traits/ChronoshiftDeploy.cs @@ -7,8 +7,9 @@ namespace OpenRa.Game.Traits class ChronoshiftDeploy : IIssueOrder, IResolveOrder, ISpeedModifier, ITick, IPips { // Recharge logic + [Sync] int chargeTick = 0; // How long until we can chronoshift again? - int chargeLength = (int)(Rules.Aftermath.ChronoTankDuration * 60 * 25); // How long between shifts? + readonly int chargeLength = (int)(Rules.Aftermath.ChronoTankDuration * 60 * 25); // How long between shifts? public ChronoshiftDeploy(Actor self) { } diff --git a/OpenRa.Game/Traits/Chronoshiftable.cs b/OpenRa.Game/Traits/Chronoshiftable.cs index 82792b2bcf..2df077e0bb 100644 --- a/OpenRa.Game/Traits/Chronoshiftable.cs +++ b/OpenRa.Game/Traits/Chronoshiftable.cs @@ -8,9 +8,11 @@ namespace OpenRa.Game.Traits class Chronoshiftable : IResolveOrder, ISpeedModifier, ITick { // Return-to-sender logic + [Sync] int2 chronoshiftOrigin; + [Sync] int chronoshiftReturnTicks = 0; - + public Chronoshiftable(Actor self) { } public void Tick(Actor self) @@ -65,7 +67,7 @@ namespace OpenRa.Game.Traits self.QueueActivity(new Activities.Teleport(order.TargetLocation)); var power = self.Owner.SupportPowers[order.TargetString].Impl; - power.OnFireNotification(self, self.Location); + power.OnFireNotification(self, self.Location); } } diff --git a/OpenRa.Game/Traits/Cloak.cs b/OpenRa.Game/Traits/Cloak.cs index 491962f89d..5b225438d6 100644 --- a/OpenRa.Game/Traits/Cloak.cs +++ b/OpenRa.Game/Traits/Cloak.cs @@ -6,6 +6,7 @@ namespace OpenRa.Game.Traits { class Cloak : IRenderModifier, INotifyAttack, ITick { + [Sync] int remainingUncloakTime = 2; /* setup for initial cloak */ public Cloak(Actor self) {} diff --git a/OpenRa.Game/Traits/Harvester.cs b/OpenRa.Game/Traits/Harvester.cs index a7607e43aa..aa374e943c 100644 --- a/OpenRa.Game/Traits/Harvester.cs +++ b/OpenRa.Game/Traits/Harvester.cs @@ -5,7 +5,9 @@ namespace OpenRa.Game.Traits { class Harvester : IIssueOrder, IResolveOrder, IPips { + [Sync] public int oreCarried = 0; /* sum of these must not exceed capacity */ + [Sync] public int gemsCarried = 0; public bool IsFull { get { return oreCarried + gemsCarried == Rules.General.BailCount; } } diff --git a/OpenRa.Game/Traits/IronCurtainable.cs b/OpenRa.Game/Traits/IronCurtainable.cs index 1783136810..4feda533ad 100644 --- a/OpenRa.Game/Traits/IronCurtainable.cs +++ b/OpenRa.Game/Traits/IronCurtainable.cs @@ -5,6 +5,7 @@ namespace OpenRa.Game.Traits { class IronCurtainable : IResolveOrder, IDamageModifier, ITick { + [Sync] int RemainingTicks = 0; public IronCurtainable(Actor self) { } diff --git a/OpenRa.Game/Traits/LimitedAmmo.cs b/OpenRa.Game/Traits/LimitedAmmo.cs index b5c18c55a2..b3ffe3535f 100644 --- a/OpenRa.Game/Traits/LimitedAmmo.cs +++ b/OpenRa.Game/Traits/LimitedAmmo.cs @@ -4,6 +4,7 @@ namespace OpenRa.Game.Traits { class LimitedAmmo : INotifyAttack, IPips { + [Sync] int ammo; Actor self; diff --git a/OpenRa.Game/Traits/Mobile.cs b/OpenRa.Game/Traits/Mobile.cs index 4e53190603..de1f0dca25 100644 --- a/OpenRa.Game/Traits/Mobile.cs +++ b/OpenRa.Game/Traits/Mobile.cs @@ -9,6 +9,7 @@ namespace OpenRa.Game.Traits { readonly Actor self; + [Sync] int2 __fromCell; public int2 fromCell { diff --git a/OpenRa.Game/Traits/ProductionQueue.cs b/OpenRa.Game/Traits/ProductionQueue.cs index e42bd59a3f..eabd106c8c 100755 --- a/OpenRa.Game/Traits/ProductionQueue.cs +++ b/OpenRa.Game/Traits/ProductionQueue.cs @@ -74,6 +74,7 @@ namespace OpenRa.Game.Traits } // Key: Production category. + // TODO: sync this readonly Cache> production = new Cache>( _ => new List() ); diff --git a/OpenRa.Game/Traits/RallyPoint.cs b/OpenRa.Game/Traits/RallyPoint.cs index eebcef0b7e..fb2006fa5d 100644 --- a/OpenRa.Game/Traits/RallyPoint.cs +++ b/OpenRa.Game/Traits/RallyPoint.cs @@ -6,6 +6,7 @@ namespace OpenRa.Game.Traits { class RallyPoint : IRender, IIssueOrder, IResolveOrder, ITick { + [Sync] public int2 rallyPoint; public Animation anim; diff --git a/OpenRa.Game/Traits/RenderBuildingWarFactory.cs b/OpenRa.Game/Traits/RenderBuildingWarFactory.cs index 4237ef5867..074d058068 100644 --- a/OpenRa.Game/Traits/RenderBuildingWarFactory.cs +++ b/OpenRa.Game/Traits/RenderBuildingWarFactory.cs @@ -7,7 +7,9 @@ namespace OpenRa.Game.Traits class RenderWarFactory : IRender, INotifyBuildComplete, INotifyDamage, ITick, INotifyProduction { public Animation roof; + [Sync] bool doneBuilding; + [Sync] bool isOpen; public readonly Actor self; diff --git a/OpenRa.Game/Traits/Submarine.cs b/OpenRa.Game/Traits/Submarine.cs index 46da5d9a93..3183072b85 100644 --- a/OpenRa.Game/Traits/Submarine.cs +++ b/OpenRa.Game/Traits/Submarine.cs @@ -6,6 +6,7 @@ namespace OpenRa.Game.Traits { class Submarine : IRenderModifier, INotifyAttack, ITick, INotifyDamage { + [Sync] int remainingSurfaceTime = 2; /* setup for initial dive */ public Submarine(Actor self) { } diff --git a/OpenRa.Game/Traits/TakeCover.cs b/OpenRa.Game/Traits/TakeCover.cs index 59cba709aa..192f2e899b 100644 --- a/OpenRa.Game/Traits/TakeCover.cs +++ b/OpenRa.Game/Traits/TakeCover.cs @@ -8,6 +8,7 @@ namespace OpenRa.Game.Traits const float proneDamage = .5f; const float proneSpeed = .5f; + [Sync] int remainingProneTime = 0; public bool IsProne { get { return remainingProneTime > 0; } } diff --git a/OpenRa.Game/Traits/TraitsInterfaces.cs b/OpenRa.Game/Traits/TraitsInterfaces.cs index 8ac3f3258b..849679042b 100644 --- a/OpenRa.Game/Traits/TraitsInterfaces.cs +++ b/OpenRa.Game/Traits/TraitsInterfaces.cs @@ -10,18 +10,18 @@ namespace OpenRa.Game.Traits // depends on the order of pips in WorldRenderer.cs! enum PipType { Transparent, Green, Yellow, Red, Gray }; enum TagType { None, Fake, Primary }; - + interface ITick { void Tick(Actor self); } interface IRender { IEnumerable Render(Actor self); } + interface IIssueOrder { Order IssueOrder( Actor self, int2 xy, MouseInput mi, Actor underCursor ); } + interface IResolveOrder { void ResolveOrder( Actor self, Order order ); } + interface INotifySold { void Sold(Actor self); } interface INotifyDamage { void Damaged(Actor self, AttackInfo e); } interface INotifyBuildComplete { void BuildingComplete (Actor self); } interface INotifyProduction { void UnitProduced(Actor self, Actor other); } interface IAcceptThief { void OnSteal(Actor self, Actor thief); } - - interface IIssueOrder { Order IssueOrder(Actor self, int2 xy, MouseInput mi, Actor underCursor); } - interface IResolveOrder { void ResolveOrder(Actor self, Order order); } - + interface IProducer { bool Produce( Actor self, UnitInfo producee ); diff --git a/OpenRa.Game/Traits/Turreted.cs b/OpenRa.Game/Traits/Turreted.cs index ee2fde30c7..b20de37e63 100644 --- a/OpenRa.Game/Traits/Turreted.cs +++ b/OpenRa.Game/Traits/Turreted.cs @@ -3,6 +3,7 @@ namespace OpenRa.Game.Traits { class Turreted : ITick { + [Sync] public int turretFacing = 0; public int? desiredFacing; diff --git a/OpenRa.Game/Traits/Unit.cs b/OpenRa.Game/Traits/Unit.cs index 98f005c8d3..ebfc56cf31 100755 --- a/OpenRa.Game/Traits/Unit.cs +++ b/OpenRa.Game/Traits/Unit.cs @@ -3,7 +3,9 @@ namespace OpenRa.Game.Traits { class Unit : INotifyDamage { + [Sync] public int Facing; + [Sync] public int Altitude; public Unit( Actor self ) { } diff --git a/OpenRa.Game/World.cs b/OpenRa.Game/World.cs index f8db600406..1b963211bb 100644 --- a/OpenRa.Game/World.cs +++ b/OpenRa.Game/World.cs @@ -12,15 +12,15 @@ namespace OpenRa.Game public void Add(Actor a) { - a.IsInWorld = true; - actors.Add(a); + a.IsInWorld = true; + actors.Add(a); ActorAdded(a); } public void Remove(Actor a) { - a.IsInWorld = false; - actors.Remove(a); + a.IsInWorld = false; + actors.Remove(a); ActorRemoved(a); } @@ -52,5 +52,14 @@ namespace OpenRa.Game { return nextAID++; } + + public int SyncHash() + { + int ret = 0; + foreach( var a in Actors ) + ret += (int)a.ActorID * Sync.CalculateSyncHash( a ); + + return ret; + } } } From ae979466a8d9f2a7a4b7ca21594196e27ed07826 Mon Sep 17 00:00:00 2001 From: Bob Date: Sat, 9 Jan 2010 15:03:24 +1300 Subject: [PATCH 31/34] made Sync faster (a lot) --- OpenRa.Game/Sync.cs | 94 ++++++++++++++++++++++++++++++++++----------- 1 file changed, 72 insertions(+), 22 deletions(-) diff --git a/OpenRa.Game/Sync.cs b/OpenRa.Game/Sync.cs index 10261f506f..607dc5a509 100755 --- a/OpenRa.Game/Sync.cs +++ b/OpenRa.Game/Sync.cs @@ -3,6 +3,8 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; +using System.Reflection.Emit; +using IjwFramework.Collections; namespace OpenRa.Game { @@ -10,48 +12,96 @@ namespace OpenRa.Game static class Sync { + static Cache> hashFuncCache = new Cache>( t => GenerateHashFunc( t ) ); + public static int CalculateSyncHash( object obj ) { - int hash = 0; // TODO: start with a more interesting initial value. + return hashFuncCache[ obj.GetType() ]( obj ); + } + + public static Func GenerateHashFunc( Type t ) + { + var d = new DynamicMethod( "hash_{0}".F( t.Name ), typeof( int ), new Type[] { typeof( object ) }, t ); + var il = d.GetILGenerator(); + var this_ = il.DeclareLocal( t ).LocalIndex; + il.Emit( OpCodes.Ldarg_0 ); + il.Emit( OpCodes.Castclass, t ); + il.Emit( OpCodes.Stloc, this_ ); + il.Emit( OpCodes.Ldc_I4_0 ); - // TODO: cache the Syncable fields; maybe use DynamicMethod to make this fast? - // FIXME: does GetFields even give fields in a well-defined order? const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; - foreach( var field in obj.GetType().GetFields( bf ).Where( x => x.GetCustomAttributes( typeof( SyncAttribute ), true ).Length != 0 ) ) + foreach( var field in t.GetFields( bf ).Where( x => x.GetCustomAttributes( typeof( SyncAttribute ), true ).Length != 0 ) ) { - if( field.FieldType == typeof( int ) ) - hash ^= (int)field.GetValue( obj ); + il.Emit( OpCodes.Ldloc, this_ ); + il.Emit( OpCodes.Ldfld, field ); - else if( field.FieldType == typeof( Actor ) ) + if( field.FieldType == typeof( int ) ) { - var a = (Actor)field.GetValue( obj ); - if( a != null ) - hash ^= (int)( a.ActorID << 16 ); + il.Emit( OpCodes.Xor ); + } + else if( field.FieldType == typeof( bool ) ) + { + var l = il.DefineLabel(); + il.Emit( OpCodes.Ldc_I4, 0xaaa ); + il.Emit( OpCodes.Brtrue, l ); + il.Emit( OpCodes.Pop ); + il.Emit( OpCodes.Ldc_I4, 0x555 ); + il.MarkLabel( l ); + il.Emit( OpCodes.Xor ); + } + else if( field.FieldType == typeof( int2 ) ) + { + il.EmitCall( OpCodes.Call, ( (Func)hash_int2 ).Method, null ); + il.Emit( OpCodes.Xor ); } else if( field.FieldType == typeof( TypeDictionary ) ) { - foreach( var o in (TypeDictionary)field.GetValue( obj ) ) - hash += CalculateSyncHash( o ); + il.EmitCall( OpCodes.Call, ( (Func)hash_tdict ).Method, null ); + il.Emit( OpCodes.Xor ); } - else if( field.FieldType == typeof( bool ) ) - hash ^= (bool)field.GetValue( obj ) ? 0xaaa : 0x555; - - else if( field.FieldType == typeof( int2 ) ) + else if( field.FieldType == typeof( Actor ) ) { - var i2 = (int2)field.GetValue( obj ); - hash ^= ( ( i2.X * 5 ) ^ ( i2.Y * 3 ) ) / 4; + il.EmitCall( OpCodes.Call, ( (Func)hash_actor ).Method, null ); + il.Emit( OpCodes.Xor ); } else if( field.FieldType == typeof( Player ) ) { - var p = (Player)field.GetValue( obj ); - if( p != null ) - hash ^= p.Index * 0x567; + il.EmitCall( OpCodes.Call, ( (Func)hash_player ).Method, null ); + il.Emit( OpCodes.Xor ); } else throw new NotImplementedException( "SyncAttribute on unhashable field" ); } - return hash; + il.Emit( OpCodes.Ret ); + return (Func)d.CreateDelegate( typeof( Func ) ); + } + + internal static int hash_int2( int2 i2 ) + { + return ( ( i2.X * 5 ) ^ ( i2.Y * 3 ) ) / 4; + } + + internal static int hash_tdict( TypeDictionary d ) + { + int ret = 0; + foreach( var o in d ) + ret += CalculateSyncHash( o ); + return ret; + } + + internal static int hash_actor( Actor a ) + { + if( a != null ) + return (int)( a.ActorID << 16 ); + return 0; + } + + internal static int hash_player( Player p ) + { + if( p != null ) + return p.Index * 0x567; + return 0; } } } From 66b5277a73c865c5c2c4fc2025b8a22bda6bf7cb Mon Sep 17 00:00:00 2001 From: Chris Forbes Date: Sat, 9 Jan 2010 15:09:30 +1300 Subject: [PATCH 32/34] perf counter for synchash --- OpenRa.Game/World.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/OpenRa.Game/World.cs b/OpenRa.Game/World.cs index 1b963211bb..83ce8d292f 100644 --- a/OpenRa.Game/World.cs +++ b/OpenRa.Game/World.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using OpenRa.Game.Effects; +using OpenRa.Game.Support; namespace OpenRa.Game { @@ -55,11 +56,14 @@ namespace OpenRa.Game public int SyncHash() { - int ret = 0; - foreach( var a in Actors ) - ret += (int)a.ActorID * Sync.CalculateSyncHash( a ); + using (new PerfSample("synchash")) + { + int ret = 0; + foreach (var a in Actors) + ret += (int)a.ActorID * Sync.CalculateSyncHash(a); - return ret; + return ret; + } } } } From a9b730599ed14b074da1a2f1fbb14d61c8c5e317 Mon Sep 17 00:00:00 2001 From: Chris Forbes Date: Sat, 9 Jan 2010 19:03:25 +1300 Subject: [PATCH 33/34] added yaml library --- thirdparty/yaml/AssemblyInfo.cs | 55 ++ thirdparty/yaml/Binary.cs | 154 +++++ thirdparty/yaml/Boolean.cs | 132 +++++ thirdparty/yaml/COPYING | 504 +++++++++++++++++ thirdparty/yaml/Float.cs | 295 ++++++++++ thirdparty/yaml/Integer.cs | 266 +++++++++ thirdparty/yaml/Mapping.cs | 292 ++++++++++ thirdparty/yaml/Node.cs | 469 ++++++++++++++++ thirdparty/yaml/Null.cs | 100 ++++ thirdparty/yaml/ParseException.cs | 63 +++ thirdparty/yaml/ParseStream.cs | 899 ++++++++++++++++++++++++++++++ thirdparty/yaml/Scalar.cs | 137 +++++ thirdparty/yaml/Sequence.cs | 197 +++++++ thirdparty/yaml/String.cs | 449 +++++++++++++++ thirdparty/yaml/Timestamp.cs | 356 ++++++++++++ thirdparty/yaml/WriteStream.cs | 121 ++++ thirdparty/yaml/Yaml.csproj | 188 +++++++ thirdparty/yaml/Yaml.sln | 19 + thirdparty/yaml/test.yaml | 24 + 19 files changed, 4720 insertions(+) create mode 100644 thirdparty/yaml/AssemblyInfo.cs create mode 100644 thirdparty/yaml/Binary.cs create mode 100644 thirdparty/yaml/Boolean.cs create mode 100644 thirdparty/yaml/COPYING create mode 100644 thirdparty/yaml/Float.cs create mode 100644 thirdparty/yaml/Integer.cs create mode 100644 thirdparty/yaml/Mapping.cs create mode 100644 thirdparty/yaml/Node.cs create mode 100644 thirdparty/yaml/Null.cs create mode 100644 thirdparty/yaml/ParseException.cs create mode 100644 thirdparty/yaml/ParseStream.cs create mode 100644 thirdparty/yaml/Scalar.cs create mode 100644 thirdparty/yaml/Sequence.cs create mode 100644 thirdparty/yaml/String.cs create mode 100644 thirdparty/yaml/Timestamp.cs create mode 100644 thirdparty/yaml/WriteStream.cs create mode 100644 thirdparty/yaml/Yaml.csproj create mode 100644 thirdparty/yaml/Yaml.sln create mode 100644 thirdparty/yaml/test.yaml diff --git a/thirdparty/yaml/AssemblyInfo.cs b/thirdparty/yaml/AssemblyInfo.cs new file mode 100644 index 0000000000..467ce787b3 --- /dev/null +++ b/thirdparty/yaml/AssemblyInfo.cs @@ -0,0 +1,55 @@ +// ==================================================================================================== +// YAML Parser for the .NET Framework +// ==================================================================================================== +// +// Copyright (c) 2006 +// Christophe Lambrechts +// Jonathan Slenders +// +// ==================================================================================================== +// This file is part of the .NET YAML Parser. +// +// This .NET YAML parser is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// The .NET YAML parser is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Foobar; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USAusing System.Reflection; +// ==================================================================================================== + +using System.Reflection; +using System.Runtime.CompilerServices; + +// +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +// +[assembly: AssemblyTitle("Yaml Parser")] +[assembly: AssemblyDescription("Yaml .NET library")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("UHasselt students")] +[assembly: AssemblyProduct("")] +[assembly: AssemblyCopyright("Christophe Lambrechts and Jonathan Slenders")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: + +[assembly: AssemblyVersion("1.0.*")] diff --git a/thirdparty/yaml/Binary.cs b/thirdparty/yaml/Binary.cs new file mode 100644 index 0000000000..e1bd9bf30d --- /dev/null +++ b/thirdparty/yaml/Binary.cs @@ -0,0 +1,154 @@ +// ==================================================================================================== +// YAML Parser for the .NET Framework +// ==================================================================================================== +// +// Copyright (c) 2006 +// Christophe Lambrechts +// Jonathan Slenders +// +// ==================================================================================================== +// This file is part of the .NET YAML Parser. +// +// This .NET YAML parser is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// The .NET YAML parser is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Foobar; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USAusing System.Reflection; +// ==================================================================================================== + +using System; + +namespace Yaml +{ + /// + /// A Yaml Boolean node + /// tag:yaml.org,2002:binary + /// + public class Binary : Scalar + { + private byte [] content; + + /// Binary constructor from byte array + /// This constructor only sets the reference, no new memory is allocated + public Binary (byte[] val) : + base ("tag:yaml.org,2002:binary", NodeType.Binary) + { + content = val; + } + + /// Parse a binary node + public Binary (ParseStream stream) : + base ("tag:yaml.org,2002:binary", NodeType.Binary) + { + try + { + content = Parse (stream); + } + catch (FormatException e) + { + throw new ParseException (stream, e); + } + } + + /// Binary content + /// There is no new memory allocated in the 'set'. + public byte [] Content + { + get { return content; } + set { content = value; } + } + + /// Parses a binairy node. + /// + /// This is not an efficient method. First the stream is placed + /// in a string. And after that the string is converted in a byte[]. + /// If there is a fault in the binairy string then that will only be detected + /// after reading the whole stream and after coneverting. + /// + public static new byte [] Parse (ParseStream stream) + { + bool quoted = false; + bool block = false; + System.Text.StringBuilder input = new System.Text.StringBuilder(); + + if (stream.EOF) + throw new ParseException (stream, "Empty node"); + + // Detect block scalar + stream.SkipSpaces (); + if (stream.Char == '|') + { + block = true; + stream.Next (); + stream.SkipSpaces (); + } + + while ( ! stream.EOF) + { + // Detect quotes + if (stream.Char == '\"') + if (quoted) + break; //End of stream + else + quoted = true; //Start of quoted stream + // Detect and ignore newline char's + else if (!(stream.Char == '\n' && block)) + input.Append( stream.Char ); + + stream.Next (); + } + + //Console.WriteLine("convert [" + input.ToString() + "]"); + + return System.Convert.FromBase64String (input.ToString ()); + } + + /// To String + /// The hexadecimal notation, 20 bytes for each line + public override string ToString () + { + System.Text.StringBuilder output = new System.Text.StringBuilder (); + + output.Append ("[BINARY]\n\t"); + for (uint i = 0; i < content.Length; i++) + { + if ((i%16) == 0) + output.Append( "\n\t" ); + output.AppendFormat ("{0:X2} ", content[i]); + } + output.Append ("\n[/BINARY]"); + + return output.ToString (); + } + + /// + /// Write the base64 content to YAML + /// + /// The lines are splitted in blocks of 20 bytes + protected internal override void Write (WriteStream stream) + { + stream.Append("!!binary |" + "\n" ); + + string bin = System.Convert.ToBase64String(content); + + while (bin.Length > 75) + { + stream.Append(" " + bin.Substring(0, 75) + "\n"); + bin = bin.Substring(75); + } + stream.Append(" " + bin ); + + // Old coden, everything on one line + // stream.Append ("!!binary \"" + System.Convert.ToBase64String (content) + "\""); + } + } + +} diff --git a/thirdparty/yaml/Boolean.cs b/thirdparty/yaml/Boolean.cs new file mode 100644 index 0000000000..a87172c0fc --- /dev/null +++ b/thirdparty/yaml/Boolean.cs @@ -0,0 +1,132 @@ +// ==================================================================================================== +// YAML Parser for the .NET Framework +// ==================================================================================================== +// +// Copyright (c) 2006 +// Christophe Lambrechts +// Jonathan Slenders +// +// ==================================================================================================== +// This file is part of the .NET YAML Parser. +// +// This .NET YAML parser is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// The .NET YAML parser is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Foobar; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USAusing System.Reflection; +// ==================================================================================================== + +using System; + +namespace Yaml +{ + /// + /// Class for storing a Yaml Boolean node + /// tag:yaml.org,2002:bool + /// + public class Boolean : Scalar + { + private bool content; + + /// New boolean + public Boolean (bool val) : + base ("tag:yaml.org,2002:bool", NodeType.Boolean) + { + content = val; + } + + /// Parse boolean + public Boolean (ParseStream stream) : + base ("tag:yaml.org,2002:bool", NodeType.Boolean) + { + // Read the first 8 chars + char [] chars = new char [8]; + + int length = 0; + for (int i = 0; i < chars.Length && ! stream.EOF; i ++) + { + chars [i] = stream.Char; + length ++; + stream.Next (true); + } + + // Compare + if (length == 1) + { + if (chars[0] == 'Y' || chars[0] == 'y') + { content = true; return; } + + if (chars[0] == 'N' || chars[0] == 'n') + { content = false; return; } + } + if (length == 2) + { + string s = "" + chars [0] + chars [1]; + + if (s == "ON" || s == "On" || s == "on") + { content = true; return; } + + if (s == "NO" || s == "No" || s == "no") + { content = false; return; } + } + if (length == 3) + { + string s = "" + chars [0] + chars [1] + chars [2]; + + if (s == "YES" || s == "Yes" || s == "yes") + { content = true; return; } + + if (s == "OFF" || s == "Off" || s == "off") + { content = false; return; } + } + if (length == 4) + { + string s = "" + chars [0] + chars [1] + chars [2] + chars [3]; + + if (s == "TRUE" || s == "True" || s == "true") + { content = true; return; } + } + if (length == 5) + { + string s = "" + chars [0] + chars [1] + chars [2] + chars [3] + chars[4]; + + if (s == "FALSE" || s == "False" || s == "false") + { content = false; return; } + } + + // No boolean + throw new Exception ("No valid boolean"); + } + + /// Node content + public bool Content + { + get { return content; } + set { content = value; } + } + + /// To String + public override string ToString () + { + return "[BOOLEAN]" + content.ToString () + "[/BOOLEAN]"; + } + + /// Write to YAML + protected internal override void Write (WriteStream stream) + { + if (Content) + stream.Append ("y"); + else + stream.Append ("n"); + } + + } +} diff --git a/thirdparty/yaml/COPYING b/thirdparty/yaml/COPYING new file mode 100644 index 0000000000..5faba9d48c --- /dev/null +++ b/thirdparty/yaml/COPYING @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/thirdparty/yaml/Float.cs b/thirdparty/yaml/Float.cs new file mode 100644 index 0000000000..4ca857aabd --- /dev/null +++ b/thirdparty/yaml/Float.cs @@ -0,0 +1,295 @@ +// ==================================================================================================== +// YAML Parser for the .NET Framework +// ==================================================================================================== +// +// Copyright (c) 2006 +// Christophe Lambrechts +// Jonathan Slenders +// +// ==================================================================================================== +// This file is part of the .NET YAML Parser. +// +// This .NET YAML parser is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// The .NET YAML parser is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Foobar; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USAusing System.Reflection; +// ==================================================================================================== + +using System; + +namespace Yaml +{ + /// + /// Class for storing a Yaml Float node + /// tag:yaml.org,2002:float + /// + public class Float : Scalar + { + private double content; + + /// New float + public Float (float val) : base ("tag:yaml.org,2002:float", NodeType.Float) + { + content = val; + } + + /// Parse float + public Float (ParseStream stream) : + base ("tag:yaml.org,2002:float", NodeType.Float) + { + // NaN + if (stream.Char == '.') + { + stream.Next (true); + ParseNaN (stream); + } + else + { + // By default positief + int sign = 1; + + // Negative sign + if (stream.Char == '-') + { + sign = -1; + stream.Next (true); + } + // Positive sign + else if (stream.Char == '+') + stream.Next (true); + + // Test for inf, Inf and INF + if ( ! stream.EOF && stream.Char == '.') + { + stream.Next (true); + ParseInf (stream, sign); + } + // Parse the numbers + else if (!stream.EOF) + ParseNumber (stream, sign); + + else + throw new ParseException (stream, + "No valid float, no data behind the sign"); + } + } + + #region Parse special formats (NaN and Inf) + /// + /// Test for the value's nan, NaN and NAN in the stream. If + /// found then it is placed inside the content. + /// There is no more data excepted behind it + /// + private void ParseNaN (ParseStream stream) + { + // Read the first 8 chars + char [] chars = new char [8]; + + int length = 0; + for (int i = 0; i < chars.Length && ! stream.EOF; i ++) + { + chars [i] = stream.Char; + length ++; + stream.Next (true); + } + + // Compare + if (length == 3) + { + string s = "" + chars [0] + chars [1] + chars [2]; + + if (s == "NAN" || s == "NaN" || s == "nan") + { + content = double.NaN; + return; + } + } + + throw new ParseException (stream, "No valid NaN"); + } + + /// + /// Test for the value's inf, Inf and INF in the stream. If + /// found then it 'merged' with the sign and placed in the content. + /// There is no more data excepted behind it. + /// + private void ParseInf (ParseStream stream, int sign) + { + // Read the first 8 chars + char [] chars = new char [8]; + + int length = 0; + for (int i = 0; i < chars.Length && ! stream.EOF; i ++) + { + chars [i] = stream.Char; + length ++; + stream.Next (true); + } + + // Compare + if (length == 3) + { + string s = "" + chars [0] + chars [1] + chars [2]; + + if (s == "INF" || s == "Inf" || s == "inf") + { + if (sign < 0) + content = double.NegativeInfinity; + else + content = double.PositiveInfinity; + + return; + } + } + + throw new ParseException (stream, "No valid infinity"); + } + #endregion + + /// + /// If it is not Infinity or NaN, then parse as a number + /// + private void ParseNumber (ParseStream stream, int sign) + { + bool base60 = false; // Base 60 with ':' + bool afterDecimal = false; // Before or after the decimal point + + double factor = 0.1; + double part; // If base60 different parts, else output value + + // Set sign + content = sign >= 0 ? 1 : -1; + + // First char must 0-9 + if (stream.Char >= '0' && stream.Char <= '9') + { + part = (uint) (stream.Char - '0'); + stream.Next (true); + } + else + throw new ParseException (stream, + "No valid float: Invalid first character of float: " + stream.Char); + + while (! stream.EOF) + { + // Decimal + if (stream.Char >= '0' && stream.Char <= '9') + if (afterDecimal) + { + part += (uint) (stream.Char - '0') * factor; + factor *= 0.1; + } + else + part = (part * 10) + (uint) (stream.Char - '0'); + + // Base60 detected + else if (stream.Char == ':') + { + if ( ! base60) // First time + { + content *= part; // Multiply to get sign + part = 0; + base60 = true; // We are now sure base 60 + } + else + { + if (part > 59) + throw new ParseException (stream, + "Part of base 60 can't be larger then 59"); + content = (60 * content) + part; + part = 0; + } + } + // If first '.', then after decimal, else it is ignored if not in Base60 + else if ( (!base60 || (base60 && !afterDecimal)) && stream.Char == '.' ) + afterDecimal = true; + + // Determine scientific notation + else if ( (stream.Char == 'E' || stream.Char == 'e') && ! base60 ) + { + stream.Next (true); + content *= Math.Pow (10, ParseScient (stream)); + } + // Ignore underscores if before the decimal point, special case if base 60 + else if ((!afterDecimal || (afterDecimal && base60)) && stream.Char != '_') + throw new ParseException (stream, "Unknown char"); + + stream.Next (true); + } + + // Add last part of base to content + if (base60) + content = (60 * content) + part; + else + content *= part; // Multiply to get sign + } + + /// Parses the exponential part of the float + private static long ParseScient (ParseStream stream) + { + ulong output = 0; + short sign; + + if (stream.Char == '-') + sign = -1; + else if (stream.Char == '+') + sign = 1; + else + throw new ParseException (stream, + "Excepted + or - for the exponential part"); + + stream.Next (true); + + while (! stream.EOF) + { + if (stream.Char >= '0' && stream.Char <= '9') + output = (10 * output) + (uint) stream.Char - '0'; + else + throw new ParseException (stream, + "Unexepted char in exponential part: >" + + stream.Char + "<"); + + stream.Next (true); + } + + return sign * (long) output; + } + + /// Content + public double Content + { + get { return content; } + set { content = value; } + } + + /// To string + public override string ToString() + { + return "[FLOAT]" + content + "[/FLOAT]"; + } + + /// Write to a YAML node + protected internal override void Write (WriteStream stream) + { + if (content.Equals( double.NaN )) + stream.Append ("!!float .NaN"); + + else if (content.Equals( double.NegativeInfinity )) + stream.Append ("!!float -.Inf"); + + else if (content.Equals( double.PositiveInfinity )) + stream.Append ("!!float +.Inf"); + + else stream.Append ("!!float " + content); + } + } +} diff --git a/thirdparty/yaml/Integer.cs b/thirdparty/yaml/Integer.cs new file mode 100644 index 0000000000..948984e983 --- /dev/null +++ b/thirdparty/yaml/Integer.cs @@ -0,0 +1,266 @@ +// ==================================================================================================== +// YAML Parser for the .NET Framework +// ==================================================================================================== +// +// Copyright (c) 2006 +// Christophe Lambrechts +// Jonathan Slenders +// +// ==================================================================================================== +// This file is part of the .NET YAML Parser. +// +// This .NET YAML parser is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// The .NET YAML parser is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Foobar; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USAusing System.Reflection; +// ==================================================================================================== + +using System; + +namespace Yaml +{ + /// + /// Class for storing a Yaml Integer node + /// uri: tag:yaml.org,2002:int + /// + public class Integer : Scalar + { + private long content; + + /// New Integer + public Integer (long val) : + base ("tag:yaml.org,2002:int", NodeType.Integer) + { + content = val; + } + + /// Content + public long Content + { + get { return content; } + set { content = value; } + } + + /// Parse an integer + public Integer (ParseStream stream) : + base ("tag:yaml.org,2002:int", NodeType.Integer) + { + short sign = 1; // Positive sign by default + + // Negative sign + if (stream.Char == '-') + { + sign = -1; + stream.Next (); + } + // Positive sign + else if (stream.Char == '+') + stream.Next (); + + try + { + // Determine base + if (stream.Char == '0') + { + stream.Next (); + + // Base 2 + if (stream.Char == 'b') + { + stream.Next (); + content = ParseBase (stream, 2, sign); + return; + } + // Base 16 + else if (stream.Char == 'x') + { + stream.Next (); + content = Parse16 (stream, sign); + return; + } + // Base 8 + else + { + content = ParseBase (stream, 8, sign); + return; + } + } + + // Other base + stream.BuildLookaheadBuffer (); + + // First, try to parse with base 10 + try + { + content = ParseBase (stream, 10, sign); + stream.DestroyLookaheadBuffer (); + return; + } + catch { } + + // If not parseable with base 10, then try base 60 + stream.RewindLookaheadBuffer (); + stream.DestroyLookaheadBuffer (); + + content = Parse60 (stream, sign); + } + catch (Exception ex) + { + throw new ParseException (stream, ex.ToString ()); + } + } + + /// Hexadecimal string + private static long Parse16 (ParseStream stream, short sign) + { + uint output = 0; + + while (! stream.EOF) + { + // 0 .. 9 + if (stream.Char >= '0' && stream.Char <= '9') + { + output = (output * 16) + (uint) (stream.Char - '0'); + OverflowTest (output, sign); + } + // a .. f + else if (stream.Char >= 'a' && stream.Char <= 'f') + { + output = (output * 16) + (uint) (stream.Char - 'a') + 10; + OverflowTest (output, sign); + } + // A .. F + else if (stream.Char >= 'A' && stream.Char <= 'F') + { + output = (output * 16) + (uint) (stream.Char - 'A') + 10; + OverflowTest(output, sign); + } + // Ignore underscores, other chars are not allowed + else if (stream.Char != '_') + throw new Exception ("Unknown char in base 16"); + + stream.Next (); + } + + return (long) (sign * output); + } + + /// Parses a string with a given base (maximum 10) + /// + /// This is not completly correct. For base10 the first char may not be a '_' + /// The other bases allow this... + /// + private static long ParseBase (ParseStream stream, uint basis, short sign) + { + // Base must be <= 10 + if (basis > 10) + throw new Exception ("Base to large. Maximum 10"); + + ulong output = 0; + char max = (char) ((basis - 1) + (int) '0'); + + // Parse + while (! stream.EOF) + { + // Decimal + if (stream.Char >= '0' && stream.Char <= max) + { + output = (output * basis) + (uint) (stream.Char - '0'); + OverflowTest (output, sign); + } + // Ignore underscores, but other chars are not allowed + // see remarks + else if (stream.Char != '_') + throw new Exception ("Unknown char in base " + basis); + + stream.Next (); + } + return sign * (long) output; + } + + /// Parses a string with base 60, without sign + private static long Parse60 (ParseStream stream, short sign) + { + ulong output = 0; + + // Parse + ulong part = 0; + bool firstPart = true; // Only the first part can be larger then 59 + + while (! stream.EOF) + { + // Decimal + if (stream.Char >= '0' && stream.Char <= '9') + part = (part * 10) + (uint) (stream.Char - '0'); + + // New part + else if (stream.Char == ':') + { + // Only the first part can be largen then 60 + if ( ! firstPart) + if (part >= 60) + throw new + Exception ("Part of base 60 scalar is too large (max. 59)"); + else + firstPart = false; + + output = (output * 60) + part; + OverflowTest(output, sign); + part = 0; + } + + // Ignore underscores, other chars are not allowed + else if (stream.Char != '_') + throw new Exception ("Unknown char in base 16"); + + stream.Next (); + } + + // Add last part to the output + if (!firstPart) + if (part >= 60) + throw new Exception ( + "Part of base 60 scalar is too large (max. 59)"); + else + firstPart = false; + + output = (output * 60) + part; + OverflowTest (output, sign); + + return sign * (long) output; + } + + /// Test that the unsigned int fits in a signed int + /// Value to test + /// Sign of the int where it must fit in + private static void OverflowTest (ulong number, short sign) + { + // NOTE: Negatif numbers can be one larger + if ((sign >= 0 && number > System.Int64.MaxValue) || + (sign < 0 && number > (ulong) System.Int64.MaxValue + 1) ) + + throw new Exception ("YAML overflow exception"); + } + + /// To String + public override string ToString () + { + return "[INTEGER]" + content.ToString () + "[/INTEGER]"; + } + + /// Write to YAML + protected internal override void Write (WriteStream stream) + { + stream.Append (content.ToString ()); + } + } +} diff --git a/thirdparty/yaml/Mapping.cs b/thirdparty/yaml/Mapping.cs new file mode 100644 index 0000000000..c91133cfab --- /dev/null +++ b/thirdparty/yaml/Mapping.cs @@ -0,0 +1,292 @@ +// ==================================================================================================== +// YAML Parser for the .NET Framework +// ==================================================================================================== +// +// Copyright (c) 2006 +// Christophe Lambrechts +// Jonathan Slenders +// +// ==================================================================================================== +// This file is part of the .NET YAML Parser. +// +// This .NET YAML parser is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// The .NET YAML parser is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Foobar; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USAusing System.Reflection; +// ==================================================================================================== + +using System; +using System.Collections; + + +// TODO Access to nodes via the [] overload + +namespace Yaml +{ + /// + /// Yaml Mapping + /// + public class Mapping : Node + { + private ArrayList childNodes = new ArrayList (); + + /// New empty mapping + public Mapping () : base ("tag:yaml.org,2002:map", NodeType.Mapping) { } + + /// New mapping from a mappingnode array + public Mapping (MappingNode [] nodes) : + base ("tag:yaml.org,2002:map", NodeType.Mapping) + { + foreach (MappingNode node in nodes) + childNodes.Add (node); + } + + /// Parse a mapping + public Mapping (ParseStream stream) : + base ("tag:yaml.org,2002:map", NodeType.Mapping) + { + // Mapping with eplicit key, (implicit mappings are threaded + // in Node.cs) + if (stream.Char == '?') + { + // Parse recursively + do { + Node key, val; + + // Skip over '?' + stream.Next (); + stream.SkipSpaces (); + + // Parse recursively. The false param avoids + // looking recursively for implicit mappings. + stream.StopAt (new char [] {':'}); + stream.Indent (); + key = Parse (stream, false); + stream.UnIndent (); + stream.DontStop (); + + // Parse recursively. The false param avoids + // looking for implit nodes + if (stream.Char == ':') + { + // Skip over ':' + stream.Next (); + stream.SkipSpaces (); + + // Parse recursively + stream.Indent (); + val = Parse (stream); + stream.UnIndent (); + } + else + val = new Null (); + + AddMappingNode (key, val); + + // Skip possible newline + // NOTE: this can't be done by the drop-newline + // method since this is not the end of a block + if (stream.Char == '\n') + stream.Next (); + } + while ( ! stream.EOF && stream.Char == '?'); + } + // Inline mapping + else if (stream.Char == '{') + { + // Override the parent's stop chars, never stop + stream.StopAt (new char [] { }); + + // Skip '{' + stream.Next (); + + do { + Node key, val; + + // Skip '?' + // (NOTE: it's not obligated to use this '?', + // especially because this is an inline mapping) + if (stream.Char == '?') + { + stream.Next (); + stream.SkipSpaces (); + } + + // Parse recursively the key + stream.StopAt (new char [] {':', ',', '}'}); + stream.Indent (); + key = Parse (stream, false); + stream.UnIndent (); + stream.DontStop (); + + // Value + if (stream.Char == ':') + { + // Skip colon + stream.Next (); + stream.SkipSpaces (); + + // Parse recursively the value + stream.StopAt (new char [] {'}', ','}); + stream.Indent (); + val = Parse (stream, false); + stream.UnIndent (); + stream.DontStop (); + } + else + val = new Null (); + + AddMappingNode (key, val); + + // Skip comma (key sepatator) + if (stream.Char != '}' && stream.Char != ',') + { + stream.DontStop (); + throw new ParseException (stream, "Comma expected in inline sequence"); + } + + if (stream.Char == ',') + { + stream.Next (); + stream.SkipSpaces (); + } + } + while ( ! stream.EOF && stream.Char != '}' ); + + // Re-accept the parent's stop chars + stream.DontStop (); + + // Skip '}' + if (stream.Char == '}') + stream.Next (); + else + throw new ParseException (stream, "Inline mapping not closed"); + } + } + + /// Add a node to this mapping + public void AddMappingNode (Node key, Node val) + { + childNodes.Add (new MappingNode (key, val)); + } + + /// Add a node to this mapping + public void AddMappingNode (MappingNode node) + { + if (node != null) + childNodes.Add (node); + else + childNodes.Add (new MappingNode (null, null)); + } + + /// Number of mappings + public int Count + { + get { return childNodes.Count; } + } + + /// To String + public override string ToString () + { + string result = ""; + foreach (MappingNode node in childNodes) + result += node.ToString (); + + return "[MAPPING]" + result + "[/MAPPING]"; + } + + /// Node info + public override Node Info () + { + Mapping mapping = new Mapping (); + mapping.AddMappingNode (new String ("kind"), new String ("mapping")); + mapping.AddMappingNode (new String ("type_id"), new String (URI)); + + Mapping childs = new Mapping (); + int i = 0; + foreach (MappingNode child in childNodes) + { + Sequence keyvaluepair = new Sequence (); + keyvaluepair.AddNode (child.Key.Info () ); + keyvaluepair.AddNode (child.Value.Info ()); + + childs.AddMappingNode (new String ("key_" + i), keyvaluepair); + i ++; + } + + mapping.AddMappingNode (new String ("value"), childs); + return mapping; + } + + /// Write to YAML + protected internal override void Write (WriteStream stream) + { + foreach (MappingNode node in childNodes) + { + stream.Append ("? "); + + stream.Indent (); + Yaml.Node key = node.Key; + key.Write (stream); + stream.UnIndent (); + + stream.Append (": "); + + stream.Indent (); + node.Value.Write (stream); + stream.UnIndent (); + } + } + + } + + /// + /// Node pair (key, value) of a mapping + /// + public class MappingNode + { + private Node key; + private Node val; + + /// Create a new mappingnode + public MappingNode (Node key, Node val) + { + if (key == null) key = new Null (); + if (val == null) val = new Null (); + + this.key = key; + this.val = val; + } + + /// Key property + public Node Key + { + get { return key; } + set { key = (value == null ? new Null () : value); } + } + + /// Value property + public Node Value + { + get { return val; } + set { val = (value == null ? new Null () : value); } + } + + /// To String + public override string ToString () + { + return + "[KEY]" + key.ToString () + "[/KEY]" + + "[VAL]" + val.ToString () + "[/VAL]"; + } + } +} diff --git a/thirdparty/yaml/Node.cs b/thirdparty/yaml/Node.cs new file mode 100644 index 0000000000..ea19cd6ddd --- /dev/null +++ b/thirdparty/yaml/Node.cs @@ -0,0 +1,469 @@ +// ==================================================================================================== +// YAML Parser for the .NET Framework +// ==================================================================================================== +// +// Copyright (c) 2006 +// Christophe Lambrechts +// Jonathan Slenders +// +// ==================================================================================================== +// This file is part of the .NET YAML Parser. +// +// This .NET YAML parser is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// The .NET YAML parser is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Foobar; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USAusing System.Reflection; +// ==================================================================================================== + +#define UNSTABLE +#define SUPPORT_EXPLICIT_TYPES +#define SUPPORT_IMPLICIT_MAPPINGS + +using System; +using System.Text; +using System.Collections; + +using System.IO; + +namespace Yaml +{ + /// + /// Kind of node, used to determine the type of node. + /// + public enum NodeType + { + /// A Yaml mapping - collection type + Mapping, + /// A Yaml sequence - collection type + Sequence, + + /// A Yaml binary scalar + Binary, + /// A Yaml boolean scalar + Boolean, + /// A Yaml float scalar + Float, + /// A Yaml integer scalar + Integer, + /// A Yaml null scalar + Null, + /// A Yaml string scalar + String, + /// A Yaml timestamp scalar + Timestamp + }; + + /// + /// Node in the Yaml tree + /// + + public abstract class Node + { + /// The uri given by http://yaml.org/type/ + protected readonly string uri; + + /// Determines wich node we are talking about + protected NodeType nodetype; + + /// Node Constructor + /// URI of the node + /// The type of node that we want to store + public Node (string uri, NodeType nodetype) + { + this.uri = uri; + this.nodetype = nodetype; + } + + /// Parse a Yaml string and return a Yaml tree + public static Node Parse (string lines) + { + StringReader reader = new StringReader (lines); + Node node = Parse (new ParseStream (reader)); + reader.Close (); + return node; + } + + /// Parse a Yaml string from a textreader and return a Yaml tree + public static Node Parse (TextReader textreader) + { + return Parse (new ParseStream (textreader)); + } + + /// Return a Yaml string + public string Write () + { + StringWriter stringWriter = new StringWriter (); + WriteStream writeStream = new WriteStream (stringWriter); + + Write (writeStream); + + stringWriter.Close (); + return stringWriter.ToString (); + } + + /// + /// Parse a Yaml string from a textfile and return a Yaml tree + /// + public static Node FromFile (string filename) + { + // Open YAML file + StreamReader reader = File.OpenText (filename); + ParseStream parsestream = new ParseStream (reader); + + // Parse + Node node = Parse (parsestream); + + // Close YAML file + reader.Close (); + return node; + } + + /// + /// Write a YAML tree to a file using UTF-8 encoding + /// + public void ToFile (string filename) + { + ToFile (filename, Encoding.UTF8); + } + + /// + /// Write a YAML tree to a file + /// + public void ToFile (string filename, Encoding enc) + { + // Open YAML file + StreamWriter writer = new StreamWriter (filename, false, enc); + WriteStream writestream = new WriteStream (writer); + + // Write + Write (writestream); + + // Close YAML file + writer.Close (); + } + + /// Parse function + protected static Node Parse (ParseStream stream) { return Parse (stream, true); } + + /// Internal parse method + /// + /// Avoids ethernal loops while parsing implicit mappings. Implicit mappings are + /// not rocognized by a leading character. So while trying to parse the key of + /// something we think that could be a mapping, we're sure that if it is a mapping, + /// the key of this implicit mapping is not a mapping itself. + /// + /// NOTE: Implicit mapping still belong to unstable code and require the UNSTABLE and + /// IMPLICIT_MAPPINGS preprocessor flags. + /// + /// + protected static Node Parse (ParseStream stream, bool parseImplicitMappings) + { + // ---------------- + // Skip Whitespace + // ---------------- + if (! stream.EOF) + { + // Move the firstindentation pointer after the whitespaces of this line + stream.SkipSpaces (); + while (stream.Char == '\n' && ! stream.EOF) + { + // Skip newline and next whitespaces + stream.Next (); + stream.SkipSpaces (); + } + } + + // ----------------- + // No remaining chars (Null/empty stream) + // ----------------- + if (stream.EOF) + return new Null (); + + // ----------------- + // Explicit type + // ----------------- + +#if SUPPORT_EXPLICIT_TYPES + stream.BuildLookaheadBuffer (); + + char a = '\0', b = '\0'; + + a = stream.Char; stream.Next (); + b = stream.Char; stream.Next (); + + // Starting with !! + if (a == '!' && b == '!' && ! stream.EOF) + { + stream.DestroyLookaheadBuffer (); + + // Read the tagname + string tag = ""; + + while (stream.Char != ' ' && stream.Char != '\n' && ! stream.EOF) + { + tag += stream.Char; + stream.Next (); + } + + // Skip Whitespace + if (! stream.EOF) + { + stream.SkipSpaces (); + while (stream.Char == '\n' && ! stream.EOF) + { + stream.Next (); + stream.SkipSpaces (); + } + } + + // Parse + Node n; + switch (tag) + { + // Mappings and sequences + // NOTE: + // - sets are mappings without values + // - Ordered maps are ordered sequence of key: value + // pairs without duplicates. + // - Pairs are ordered sequence of key: value pairs + // allowing duplicates. + + // TODO: Create new datatypes for omap and pairs + // derived from sequence with a extra duplicate + // checking. + + case "seq": n = new Sequence (stream); break; + case "map": n = new Mapping (stream); break; + case "set": n = new Mapping (stream); break; + case "omap": n = new Sequence (stream); break; + case "pairs": n = new Sequence (stream); break; + + // Scalars + // + // TODO: do we have to move this to Scalar.cs + // in order to get the following working: + // + // !!str "...": "..." + // !!str "...": "..." + + case "timestamp": n = new Timestamp (stream); break; + case "binary": n = new Binary (stream); break; + case "null": n = new Null (stream); break; + case "float": n = new Float (stream); break; + case "int": n = new Integer (stream); break; + case "bool": n = new Boolean (stream); break; + case "str": n = new String (stream); break; + + // Unknown data type + default: + throw new Exception ("Incorrect tag '!!" + tag + "'"); + } + + return n; + } + else + { + stream.RewindLookaheadBuffer (); + stream.DestroyLookaheadBuffer (); + } +#endif + // ----------------- + // Sequence + // ----------------- + + if (stream.Char == '-' || stream.Char == '[') + return new Sequence (stream); + + // ----------------- + // Mapping + // ----------------- + + if (stream.Char == '?' || stream.Char == '{') + return new Mapping (stream); + + // ----------------- + // Try implicit mapping + // ----------------- + + // This are mappings which are not preceded by a question + // mark. The keys have to be scalars. + +#if (UNSTABLE && SUPPORT_IMPLICIT_MAPPINGS) + + // NOTE: This code can't be included in Mapping.cs + // because of the way we are using to rewind the buffer. + + Node key, val; + + if (parseImplicitMappings) + { + // First Key/value pair + + stream.BuildLookaheadBuffer (); + + stream.StopAt (new char [] {':'}); + + // Keys of implicit mappings can't be sequences, or other mappings + // just look for scalars + key = Scalar.Parse (stream, false); + stream.DontStop (); + +Console.WriteLine ("key: " + key); + + // Followed by a colon, so this is a real mapping + if (stream.Char == ':') + { + stream.DestroyLookaheadBuffer (); + + Mapping mapping = new Mapping (); + + // Skip colon and spaces + stream.Next (); + stream.SkipSpaces (); + + // Parse the value +Console.Write ("using buffer: " + stream.UsingBuffer ()); + stream.Indent (); +Console.Write ("using buffer: " + stream.UsingBuffer ()); +// val = Parse (stream, false); +Console.Write ("<<"); +while (!stream.EOF) {Console.Write (stream.Char);stream.Next (true);} +Console.Write (">>"); + +val = new String (stream); + + +Console.Write ("using buffer: " + stream.UsingBuffer ()); + stream.UnIndent (); +Console.Write ("using buffer: " + stream.UsingBuffer ()); + +Console.Write ("<<"); +while (!stream.EOF) {Console.Write (stream.Char);stream.Next (true);} +Console.Write (">>"); + + + + +Console.WriteLine ("val: " + val); + mapping.AddMappingNode (key, val); + + // Skip possible newline + // NOTE: this can't be done by the drop-newline + // method since this is not the end of a block + while (stream.Char == '\n') + stream.Next (true); + + // Other key/value pairs + while (! stream.EOF) + { + stream.StopAt (new char [] {':'} ); + stream.Indent (); + key = Scalar.Parse (stream); + stream.UnIndent (); + stream.DontStop (); + +Console.WriteLine ("key 2: " + key); + if (stream.Char == ':') + { + // Skip colon and spaces + stream.Next (); + stream.SkipSpaces (); + + // Parse the value + stream.Indent (); + val = Parse (stream); + stream.UnIndent (); + +Console.WriteLine ("val 2: " + val); + mapping.AddMappingNode (key, val); + } + else // TODO: Is this an error? + { + // NOTE: We can't recover from this error, + // the last buffer has been destroyed, so + // rewinding is impossible. + throw new ParseException (stream, + "Implicit mapping without value node"); + } + + // Skip possible newline + while (stream.Char == '\n') + stream.Next (); + } + + return mapping; + } + + stream.RewindLookaheadBuffer (); + stream.DestroyLookaheadBuffer (); + } + +#endif + // ----------------- + // No known data structure, assume this is a scalar + // ----------------- + + Scalar scalar = Scalar.Parse (stream); + + // Skip trash + while (! stream.EOF) + stream.Next (); + + + return scalar; + } + + /// + /// URI of this node, according to the YAML documentation. + /// + public string URI + { + get { return uri; } + } + + /// + /// Kind of node: mapping, sequence, string, ... + /// + public NodeType Type + { + get { return nodetype; } + } + + /// + /// Writes a Yaml tree back to a file or stream + /// + /// + /// should not be called from outside the parser. This method + /// is only public from inside the Sequence and Mapping Write + /// methods. + /// + /// Were the output data go's + protected internal virtual void Write (WriteStream stream) {} + + /// + /// The ToString method here, and in all the classses + /// derived from this class, is used mainly for debugging + /// purpose. ToString returns a xml-like textual representation + /// of the objects. It's very useful to see how a Yaml document + /// has been parsed because of the disambiguous representation + /// of this notation. + /// + public override abstract string ToString (); + + /// + /// Node info returns a YAML node and is also mostly used + /// for debugging the parser. This could be used for + /// traversing the meta-info of another YAML tree + /// + public abstract Node Info (); + } +} diff --git a/thirdparty/yaml/Null.cs b/thirdparty/yaml/Null.cs new file mode 100644 index 0000000000..f68eb5fbaa --- /dev/null +++ b/thirdparty/yaml/Null.cs @@ -0,0 +1,100 @@ +// ==================================================================================================== +// YAML Parser for the .NET Framework +// ==================================================================================================== +// +// Copyright (c) 2006 +// Christophe Lambrechts +// Jonathan Slenders +// +// ==================================================================================================== +// This file is part of the .NET YAML Parser. +// +// This .NET YAML parser is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// The .NET YAML parser is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Foobar; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USAusing System.Reflection; +// ==================================================================================================== + +using System; + +namespace Yaml +{ + /// + /// Class for storing a Yaml Null node + /// tag:yaml.org,2002:null + /// + public class Null : Scalar + { + /// Null Constructor + public Null () : base ("tag:yaml.org,2002:null", NodeType.Null) { } + + /// Parse a null node + public Null (ParseStream stream) : + base ("tag:yaml.org,2002:null", NodeType.Null) + { + // An empty string is a valid null node + if (stream.EOF) + return; + + else + { + // Read the first 4 chars + char [] chars = new char [8]; + int length = 0; + for (int i = 0; i < chars.Length && ! stream.EOF; i ++) + { + chars [i] = stream.Char; + length ++; + stream.Next (); + } + + // Compare + if (length == 1) + { + string s = "" + chars [0]; + + // Canonical notation + if (s == "~") + return; + } + if (length == 4) + { + string s = "" + chars [0] + chars [1] + chars [2] + chars [3]; + + // null, Null, NULL + if (s == "NULL" || s == "Null" || s == "null") + return; + } + + throw new ParseException (stream, "Not NULL"); + } + } + + /// Content property + public object Content + { + get { return null; } + } + + /// To String + public override string ToString () + { + return "[NULL]~[/NULL]"; + } + + /// Write to YAML + protected internal override void Write (WriteStream stream) + { + stream.Append ("~"); + } + } +} diff --git a/thirdparty/yaml/ParseException.cs b/thirdparty/yaml/ParseException.cs new file mode 100644 index 0000000000..b4298a0ed4 --- /dev/null +++ b/thirdparty/yaml/ParseException.cs @@ -0,0 +1,63 @@ +// ==================================================================================================== +// YAML Parser for the .NET Framework +// ==================================================================================================== +// +// Copyright (c) 2006 +// Christophe Lambrechts +// Jonathan Slenders +// +// ==================================================================================================== +// This file is part of the .NET YAML Parser. +// +// This .NET YAML parser is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// The .NET YAML parser is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Foobar; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USAusing System.Reflection; +// ==================================================================================================== + +using System; + +namespace Yaml +{ + /// + /// ParseException, could be thrown while parsing a YAML stream + /// + public class ParseException : Exception + { + // Line of the Yaml stream/file where the fault occures + private readonly int linenr; + + /// Constructor + /// The parse stream (contains the line number where it went wrong) + /// Info about the exception + public ParseException (ParseStream stream, string message) : + base ("Parse error near line " + stream.CurrentLine + ": " + message) + { + this.linenr = stream.CurrentLine; + } + + /// Constructor + /// The parse stream (contains the line number where it went wrong) + /// The exception that is for example throwed again + public ParseException (ParseStream stream, Exception child) : + base ( "Parse error near line " + stream.CurrentLine, child ) + { + this.linenr = stream.CurrentLine; + } + + /// The line where the error occured + public int LineNumber + { + get { return linenr; } + } + } +} diff --git a/thirdparty/yaml/ParseStream.cs b/thirdparty/yaml/ParseStream.cs new file mode 100644 index 0000000000..271a59e5ec --- /dev/null +++ b/thirdparty/yaml/ParseStream.cs @@ -0,0 +1,899 @@ +// ==================================================================================================== +// YAML Parser for the .NET Framework +// ==================================================================================================== +// +// Copyright (c) 2006 +// Christophe Lambrechts +// Jonathan Slenders +// +// ==================================================================================================== +// This file is part of the .NET YAML Parser. +// +// This .NET YAML parser is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// The .NET YAML parser is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Foobar; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USAusing System.Reflection; +// ==================================================================================================== + +using System; +using System.Collections; + +using System.IO; + +namespace Yaml +{ + /// + /// The Preprocessor class + /// Given a character stream, this class will + /// walk through that stream. + /// NOTE: Comments are not longer skipped at this level, + /// but now in the last level instead. (because of + /// problems with comments within the buffer) + /// NOTE: Null characters are skipped, read nulls should + /// be escaped. \0 + /// + public class Preprocessor + { + private TextReader stream; + private int currentline = 1; // Line numbers start with one + private bool literal = false; // Parse literal/verbatim + + /// Constuctor + public Preprocessor (TextReader stream) + { + this.stream = stream; + } + + /// Jump to the next character + public void Next () + { + // Transition to the next line? + if (Char == '\n') + currentline ++; + + // Not yet passed the end of file + if (! EOF) + { + // Next + stream.Read (); + + // Skip null chars + while (stream.Peek () == '\0') + stream.Read (); + } + } + + /// Start parsing literal + public void StartLiteral () + { + literal = true; + } + + /// Stop parsing literal + public void StopLiteral () + { + if (literal) + literal = false; + else + throw new Exception ("Called StopLiteral without " + + "calling StartLiteral before"); + } + + /// Literal parsing + public bool Literal + { + get { return literal; } + // No set method, setting must by using the {Start,Stop}Literal + // methods. They provide mory symmetry in the parser. + } + + /// The current character + public char Char + { + get + { + if (EOF) + return '\0'; + else + return (char) stream.Peek (); + } + } + + /// End of file/stream + public bool EOF + { + get { return stream.Peek () == -1; } + } + + /// Returns the current line number + public int CurrentLine + { + get { return currentline; } + } + } + + /// + /// The indentation processor, + /// This class divides the stream from the preprocessor + /// in substreams, according to the current level + /// of indentation. + /// + public class IndentationProcessor : Preprocessor + { + // While trying to readahead over whitespaces, + // This is how many whitespaces were skipped that weren't yet read + private int whitespaces = 0; + private int whitespacesSkipped = 0; + + // Reached the end + private bool endofstream = false; + + // Current level of indentation + private int indentationLevel = 0; + private bool indentationRequest = false; + private Stack indentationStack = new Stack (); + + /// Constructor + public IndentationProcessor (TextReader stream) : base (stream) { } + + /// + /// Request an indentation. When we meet a \n and the following + /// line is more indented then the current indentationlever, then + /// save this request + /// + public void Indent () + { + if (Literal) + throw new Exception ("Cannot (un)indent while literal parsing " + + "has been enabled"); + else + { + // Handle double requests + if (indentationRequest) + indentationStack.Push ((object) indentationLevel); + + // Remember + indentationRequest = true; + } + } + + /// Cancel the last indentation + public void UnIndent () + { + if (Literal) + throw new Exception ("Cannot (un)indent while literal parsing " + + "has been enabled"); + else + { + // Cancel the indentation request + if (indentationRequest) + { + indentationRequest = false; + return; + } + + // Unpop the last indentation + if (indentationStack.Count > 0) + indentationLevel = (int) indentationStack.Pop (); + + // When not indented + else + throw new Exception ("Unable to unindent a not indented parse stream"); + + // Parent stream not yet finished + // Skipped whitespaces in the childstream (at that time assumed to be + // indentation) can become content. + if (endofstream && indentationLevel <= whitespaces) + { + endofstream = false; + if (whitespaces == this.indentationLevel) + whitespaces = 0; + } + } + } + + /// Go to the next parsable char in the stream + public new void Next () + { + if (endofstream) + return; + + // Are there still whitespaces to skip + if (whitespaces > 0) + { + // All whitespaces were skipped + if (whitespaces == whitespacesSkipped + this.indentationLevel) + whitespaces = 0; + + // Else, skip one + else + { + whitespacesSkipped ++; + return; + } + } + + // All whitespaces have been skipped + if (whitespaces == 0 && ! base.EOF) + { + // When a char is positioned at a newline '\n', + // then skip 'indentation' chars and continue. + // When there are less spaces available, then we are + // at the end of the (sub)stream + if (! base.EOF && base.Char == '\n' && ! Literal) + { + // Skip over newline + base.Next (); + + // Skip indentation (and count the spaces) + int i = 0; + while (! base.EOF && base.Char == ' ' && i < this.indentationLevel) + { + i ++; + base.Next (); + } + + // Not enough indented? + if (i < this.indentationLevel) + { + // Remember the number of whitespaces, and + // continue at the moment that the indentationlevel + // drops below this number of whitespaces + whitespaces = i; + whitespacesSkipped = 0; + endofstream = true; + return; + } + // Indentation request + else if (indentationRequest) + { + while (! base.EOF && base.Char == ' ') + { + i ++; + base.Next (); + } + + // Remember current indentation + indentationStack.Push ((object) indentationLevel); + indentationRequest = false; + + // Number of spaces before this line is equal to the + // current level of indentation, so the + // indentation request cannot be fulfilled + if (indentationLevel == i) + { + whitespaces = i; + whitespacesSkipped = 0; + endofstream = true; + return; + } + else // i > indentationLevel + indentationLevel = i; + } + } + else + // Next char + base.Next (); + } + else + endofstream = true; + } + + /// Reads the current char from the stream + public new char Char + { + get + { + // In case of spaces + if (whitespaces > 0) + return ' '; + + // \0 at the end of the stream + else if (base.EOF || endofstream) + return '\0'; + + // Return the char + else + return base.Char; + } + } + + /// End of File/Stream + public new bool EOF + { + get { return endofstream || base.EOF; } + } + } + + /// + /// Third stream processor, this class adds a buffer with a maximum + /// size of 1024 chars. The buffer cannot encapsulate multiple lines + /// because that could do strange things while rewinding/indenting + /// + + public class BufferStream : IndentationProcessor + { + LookaheadBuffer buffer = new LookaheadBuffer (); + + // When the buffer is used, this is true + private bool useLookaheadBuffer = false; + + // In use, but requested to destroy. The buffer will keep to exists + // (only in this layer) and shall be destroyed when we move out of + // the buffer + private bool destroyRequest = false; + + /// Constructor + public BufferStream (TextReader stream) : base (stream) { } + + /// Build lookahead buffer + public void BuildLookaheadBuffer () + { + if (Literal) + throw new Exception ("Cannot build a buffer while " + + "literal parsing is enabled"); + else + { + // When the buffer is already in use + if (useLookaheadBuffer && ! destroyRequest) + throw new Exception ("Buffer already exist, cannot rebuild " + + "the buffer at this level"); + + // Cancel the destroy request + if (destroyRequest) + destroyRequest = false; + + // Or start a new buffer + else + { + buffer.Clear (); + buffer.Append (Char); + } + + useLookaheadBuffer = true; + } + } + + /// Move to the next character in the parse stream. + public new void Next () + { + // End of file (This check is not really necessary because base.next + // would skip this anyway) + if (EOF) return; + + // When it's not allowed to leave the buffer + if (useLookaheadBuffer && ! destroyRequest && ! NextInBuffer () ) + return; + + // When using the lookahead buffer + if (useLookaheadBuffer) + { + // Requested to destroy + if (destroyRequest) + { + // But not yet reached the end of the buffer + if (buffer.Position < buffer.LastPosition) + { + buffer.Position ++; + buffer.ForgetThePast (); + } + // Reached the end + else + { + buffer.Clear (); + useLookaheadBuffer = false; + destroyRequest = false; + + base.Next (); + } + } + // Continue in the buffer + else + { + // We've been here before + if (buffer.Position < buffer.LastPosition) + buffer.Position ++; + + // This is new to the buffer, but there is place + // to remember new chars + else if ( + buffer.Position == buffer.LastPosition && + ! buffer.Full) + { + // Save the next char in the buffer + base.Next(); + buffer.Append (base.Char); + } + // Otherwise, the buffer is full + else + throw new Exception ("buffer overflow"); + } + } + // Not using the buffer + else + base.Next(); + } + + /// Returns true when using a buffer + public bool UsingBuffer () + { + return useLookaheadBuffer && ! destroyRequest; + } + + /// + /// Returns true when the next char will still be in the buffer + /// (after calling next) + /// + private bool NextInBuffer () + { + return + // Using the buffer + useLookaheadBuffer && + + // Next char has been read before + (buffer.Position < buffer.LastPosition || + + // Or the next char will also be in the buffer + (Char != '\n' && ! base.EOF && + + // There is still unused space + ! buffer.Full)); + } + + /// Destroys the current lookaheadbuffer, if there is one + public void DestroyLookaheadBuffer () + { + if (useLookaheadBuffer && ! destroyRequest) + { + buffer.ForgetThePast (); + destroyRequest = true; + } + else + throw new Exception ("Called destroy buffer before building the buffer"); + } + + /// Rewind the buffer + public void RewindLookaheadBuffer () + { + if (! useLookaheadBuffer || destroyRequest) + throw new Exception ("Cannot rewind the buffer. No buffer in use"); + + else + buffer.Rewind (); + } + + /// The current character + public new char Char + { + get + { + // When using a buffer + if (useLookaheadBuffer) + return buffer.Char; + + else + return base.Char; + } + } + + /// End of stream/file + public new bool EOF + { + get + { + return + // When it's not allowed to run out of the buffer + (useLookaheadBuffer && ! destroyRequest && ! NextInBuffer () ) || + + // Not using the buffer, but the end of stream has been reached + (! useLookaheadBuffer && base.EOF); + } + } + + /// Current position in the lookahead buffer + protected int LookaheadPosition + { + get + { + if (useLookaheadBuffer) + return buffer.Position; + + else + throw new Exception ("Not using a lookahead buffer"); + } + set + { + if (useLookaheadBuffer) + { + if (value >= 0 && value <= buffer.LastPosition) + buffer.Position = value; + + else + throw new Exception ("Lookahead position not between 0 " + + "and the buffer size"); + } + else + throw new Exception ("Not using a lookahead buffer"); + } + } + } + + /// Parsestream with multilever buffer + public class MultiBufferStream : BufferStream + { + private Stack bufferStack = new Stack (); // Top is current buffer start + + /// Constructor + public MultiBufferStream (TextReader stream) : base (stream) { } + + /// Destroy the current buffer + public new void BuildLookaheadBuffer () + { + if (Literal) + throw new Exception ("Cannot build a buffer while " + + "literal parsing is enabled"); + else + { + // Already using a buffer + if (base.UsingBuffer ()) + // Remember the current position + bufferStack.Push ((object) base.LookaheadPosition); + + // Otherwise, create a new buffer + else + { + // Remember the current position (= 0) + bufferStack .Push ((object) 0); + + base.BuildLookaheadBuffer (); + } + } + } + + /// Destroy the current buffer + public new void DestroyLookaheadBuffer () + { + // Clear the buffer info when we runned out of the buffer, + if ( ! base.UsingBuffer () ) + bufferStack.Clear (); + + else + { + // Unpop the buffers start index + bufferStack.Pop (); + + // Destroy it when the last buffer is gone + if (bufferStack.Count == 0) + base.DestroyLookaheadBuffer (); + } + } + + /// Rewind the current buffer + public new void RewindLookaheadBuffer () + { + if (base.UsingBuffer () ) + base.LookaheadPosition = (int) bufferStack.Peek (); + else + throw new Exception ("Rewinding not possible. Not using a " + + "lookahead buffer."); + } + } + + /// + /// Drop the comments + /// (This is disabled when literal parsing is enabled) + /// + public class DropComments : MultiBufferStream + { + /// Constructor + public DropComments (TextReader stream) : base (stream) { } + + /// Move to the next character in the parse stream. + public new void Next () + { + base.Next (); + + // Skip comments + if (base.Char == '#' && ! Literal) + while (! base.EOF && base.Char != '\n') + base.Next (); + } + } + + /// + /// This layer removes the trailing newline at the end of each (sub)stream + /// + public class DropTrailingNewline : DropComments + { + // One char buffer + private bool newline = false; + + /// Constructor + public DropTrailingNewline (TextReader stream) : base (stream) { } + + /// The current character + public new char Char + { + get + { + if (EOF) + return '\0'; + else if (newline) + return '\n'; + else + return base.Char; + } + } + + /// End of File/Stream + public new bool EOF + { + get { return ! newline && base.EOF; } + } + + /// Skip space characters + public int SkipSpaces () + { + int count = 0; + while (Char == ' ') + { + Next (); + count ++; + } + return count; + } + + /// Move to the next character in the parse stream. + public new void Next () + { + Next (false); + } + + /// Move to the next character in the parse stream. + /// Forget the last newline + public void Next (bool dropLastNewLine) + { + if (newline) + newline = false; + else + { + base.Next (); + + if (dropLastNewLine && ! base.EOF && Char == '\n') + { + base.Next (); + + if (base.EOF) + newline = false; + else + newline = true; + } + } + } + } + + + /// + /// Stops parsing at specific characters, useful for parsing inline + /// structures like (for instance): + /// + /// [aaa, bbb, ccc, {ddd: eee, "fff": ggg}] + /// + public class ParseStream : DropTrailingNewline + { + private Stack stopstack = new Stack (); + + /// Constructor + public ParseStream (TextReader stream) : base (stream) { } + + /// Set the characters where we should stop. + public void StopAt (char [] characters) + { + stopstack.Push (characters); + } + + /// Unset the characters where we should stop. + public void DontStop () + { + if (stopstack.Count > 0) + stopstack.Pop (); + else + throw new Exception ("Called DontStop without " + + "calling StopAt before"); + } + + /// True when we have to stop here + private bool StopNow + { + get { + if (stopstack.Count > 0) + foreach (char c in (char []) stopstack.Peek ()) + if (c == base.Char) + return true; + + return false; + } + } + + /// Start parsing literal + public new void StartLiteral () + { + base.StartLiteral (); + + // Parsing literal disables stopping + StopAt (new Char [] { }); + } + + /// Stop parsing literal + public new void StopLiteral () + { + base.StopLiteral (); + + DontStop (); + } + /// Move to the next character in the parse stream. + public new void Next () + { + Next (false); + } + + /// Move to the next character in the parse stream. + public new void Next (bool dropLastNewLine) + { + if ( ! StopNow ) + base.Next (dropLastNewLine); + } + + /// The current character + public new char Char + { + get + { + if (StopNow) + return '\0'; + + else + return base.Char; + } + } + + /// End of stream/file + public new bool EOF + { + get { return StopNow || base.EOF; } + } + } + + /// + /// The lookahead buffer, used by the buffer layer in the parser + /// + class LookaheadBuffer + { + // The buffer array + private char [] buffer = new char [1024]; + + private int size = 0; // 0 = Nothing in the buffer + private int position = -1; // Current position + private int rotation = 0; // Start of circular buffer + + /// Character at the current position + public char Char + { + get + { + if (size > 0) + return buffer [(position + rotation) % buffer.Length]; + + else + throw new Exception ("Trying to read from an emty buffer"); + } + } + + /// The current position + public int Position + { + get { return position; } + + set + { + if (value >= 0 && value < size) + position = value; + else + throw new Exception ("Buffer position should be " + + "between zero and 'size' "); + } + } + + /// The last possible postition which could be set + public int LastPosition + { + get { return size - 1; } + } + + /// + /// The last possible position which could be set if + /// the buffer where full + /// + public int MaxPosition + { + get { return buffer.Length - 1; } + } + + /// True when the buffer is full + public bool Full + { + get { return size == buffer.Length; } + } + + /// Current buffer size + public int Size + { + get { return size; } + } + + /// Append a character to the buffer + public void Append (char c) + { + // Appending is only possible when the current position is the + // last in the buffer + if (position < LastPosition) + throw new Exception ("Appending to buffer only possible " + + "when the position is the last"); + + // Buffer overflow + if (size == buffer.Length) + throw new Exception ("Buffer full"); + + // Append + position ++; + size ++; + buffer [(position + rotation) % buffer.Length] = c; + } + + /// Rewind the buffer + public void Rewind () + { + position = 0; + } + + /// Reset (clear) the buffer + public void Clear () + { + position = -1; + size = 0; + } + + /// Move to the next character + public void Next () + { + if (Position < Size) + Position ++; + + else throw new Exception ("Cannot move past the buffer"); + } + + /// + /// Remove characters from the buffer before the current character + /// + public void ForgetThePast () + { + // Size becomes smaller, characters before the position should be dropped + size -= position; + + // The current position becomes the new startposition + rotation = (rotation + position + buffer.Length) % buffer.Length; + + // The current position in the new buffer becomes zero + position = 0; + } + } +} diff --git a/thirdparty/yaml/Scalar.cs b/thirdparty/yaml/Scalar.cs new file mode 100644 index 0000000000..9d2cb849c0 --- /dev/null +++ b/thirdparty/yaml/Scalar.cs @@ -0,0 +1,137 @@ +// ==================================================================================================== +// YAML Parser for the .NET Framework +// ==================================================================================================== +// +// Copyright (c) 2006 +// Christophe Lambrechts +// Jonathan Slenders +// +// ==================================================================================================== +// This file is part of the .NET YAML Parser. +// +// This .NET YAML parser is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// The .NET YAML parser is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Foobar; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USAusing System.Reflection; +// ==================================================================================================== + +#define SUPPORT_NULL_NODES +#define SUPPORT_INTEGER_NODES +#define SUPPORT_FLOAT_NODES +#define SUPPORT_BOOLEAN_NODES +#define SUPPORT_TIMESTAMP_NODES + +using System; + +namespace Yaml +{ + /// + /// All Yaml scalars are derived from this class + /// + public abstract class Scalar : Node + { + /// Constructor + public Scalar (string uri, NodeType nodetype) : base (uri, nodetype) { } + + + /// + /// Parses a scalar + /// + /// Integer + /// String + /// Boolean + /// Null + /// Timestamp + /// Float + /// Binary + /// + /// + /// + /// Binary is only parsed behind an explicit !!binary tag (in Node.cs) + /// + public static new Scalar Parse (ParseStream stream) + { + // ----------------- + // Parse scalars + // ----------------- + + stream.BuildLookaheadBuffer (); + + // Try Null +#if SUPPORT_NULL_NODES + try + { + Scalar s = new Null (stream); + stream.DestroyLookaheadBuffer (); + return s; + } catch { } +#endif + // Try boolean +#if SUPPORT_BOOLEAN_NODES + stream.RewindLookaheadBuffer (); + try + { + Scalar scalar = new Boolean (stream); + stream.DestroyLookaheadBuffer (); + return scalar; + } + catch { } +#endif + // Try integer +#if SUPPORT_INTEGER_NODES + stream.RewindLookaheadBuffer (); + try + { + Scalar scalar = new Integer (stream); + stream.DestroyLookaheadBuffer (); + return scalar; + } catch { } +#endif + // Try Float +#if SUPPORT_FLOAT_NODES + stream.RewindLookaheadBuffer (); + try + { + Scalar scalar = new Float (stream); + stream.DestroyLookaheadBuffer (); + return scalar; + } + catch { } +#endif + // Try timestamp +#if SUPPORT_TIMESTAMP_NODES + stream.RewindLookaheadBuffer (); + try { + Scalar scalar = new Timestamp (stream); + stream.DestroyLookaheadBuffer (); + return scalar; + } catch { } +#endif + // Other scalars are strings + stream.RewindLookaheadBuffer (); + stream.DestroyLookaheadBuffer (); + + return new String (stream); + } + + /// Node info +// TODO, move to each induvidual child + public override Node Info () + { + Mapping mapping = new Mapping (); + mapping.AddMappingNode (new String ("kind"), new String ("scalar")); + mapping.AddMappingNode (new String ("type_id"), new String (URI)); + mapping.AddMappingNode (new String ("value"), this); + return mapping; + } + } +} diff --git a/thirdparty/yaml/Sequence.cs b/thirdparty/yaml/Sequence.cs new file mode 100644 index 0000000000..e26bdbd8aa --- /dev/null +++ b/thirdparty/yaml/Sequence.cs @@ -0,0 +1,197 @@ +// ==================================================================================================== +// YAML Parser for the .NET Framework +// ==================================================================================================== +// +// Copyright (c) 2006 +// Christophe Lambrechts +// Jonathan Slenders +// +// ==================================================================================================== +// This file is part of the .NET YAML Parser. +// +// This .NET YAML parser is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// The .NET YAML parser is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Foobar; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USAusing System.Reflection; +// ==================================================================================================== + +using System; +using System.Collections; + +namespace Yaml +{ + /// + /// Represents a Yaml Sequence + /// + public class Sequence : Node + { + private ArrayList childNodes = new ArrayList (); + + /// New, empty sequence + public Sequence ( ) : base ("tag:yaml.org,2002:seq", NodeType.Sequence) { } + + /// New sequence from a node array + public Sequence (Node [] nodes) : + base ("tag:yaml.org,2002:seq", NodeType.Sequence) + { + foreach (Node node in nodes) + childNodes.Add (node); + } + + /// Parse a sequence + public Sequence (ParseStream stream) : + base ("tag:yaml.org,2002:seq", NodeType.Sequence) + { + // Is this really a sequence? + if (stream.Char == '-') + { + // Parse recursively + do { + // Override the parent's stop chars, never stop + stream.StopAt (new char [] { } ); + + // Skip over '-' + stream.Next (); + + // Parse recursively + stream.Indent (); + AddNode (Parse (stream)); + stream.UnIndent (); + + // Re-accept the parent's stop chars + stream.DontStop (); + } + while ( ! stream.EOF && stream.Char == '-' ); + } + // Or inline Sequence + else if (stream.Char == '[') + { + // Override the parent's stop chars, never stop + stream.StopAt (new char [] { }); + + // Skip '[' + stream.Next (); + + do { + stream.StopAt (new char [] {']', ','}); + stream.Indent (); + AddNode (Parse (stream, false)); + stream.UnIndent (); + stream.DontStop (); + + // Skip ',' + if (stream.Char != ']' && stream.Char != ',') + { + stream.DontStop (); + throw new ParseException (stream, "Comma expected in inline sequence"); + } + + if (stream.Char == ',') + { + stream.Next (); + stream.SkipSpaces (); + } + } + while ( ! stream.EOF && stream.Char != ']'); + + // Re-accept the parent's stop chars + stream.DontStop (); + + // Skip ']' + if (stream.Char == ']') + stream.Next (true); + else + throw new ParseException (stream, "Inline sequence not closed"); + + } + // Throw an exception when not + else + throw new Exception ("This is not a sequence"); + } + + /// Add a node to this sequence + public void AddNode (Node node) + { + if (node != null) + childNodes.Add (node); + else + childNodes.Add (new Null ()); + } + + /// Get a node + public Node this [int index] + { + get + { + if (index > 0 && index < childNodes.Count) + return (Node) childNodes [index]; + + else + throw new IndexOutOfRangeException (); + } + } + + /// The node array + public Node [] Nodes + { + get + { + Node [] nodes = new Node [childNodes.Count]; + + for (int i = 0; i < childNodes.Count; i ++) + nodes [i] = (Node) childNodes [i]; + + return nodes; + } + } + + /// Textual destription of this node + public override string ToString () + { + string result = ""; + foreach (Node node in childNodes) + result += node.ToString (); + + return "[SEQUENCE]" + result + "[/SEQUENCE]"; + } + + /// Node info + public override Node Info () + { + Mapping mapping = new Mapping (); + mapping.AddMappingNode (new String ("kind"), new String ("sequence")); + mapping.AddMappingNode (new String ("type_id"), new String (URI)); + + Sequence childs = new Sequence (); + + foreach (Node child in childNodes) + childs.AddNode (child.Info ()); + + mapping.AddMappingNode (new String ("value"), childs); + return mapping; + } + + /// Write back to a stream + protected internal override void Write (WriteStream stream) + { + foreach (Node node in childNodes) + { + stream.Append ("- "); + + stream.Indent (); + node.Write (stream); + stream.UnIndent (); + } + } + + } +} diff --git a/thirdparty/yaml/String.cs b/thirdparty/yaml/String.cs new file mode 100644 index 0000000000..25243dfbe2 --- /dev/null +++ b/thirdparty/yaml/String.cs @@ -0,0 +1,449 @@ +// ==================================================================================================== +// YAML Parser for the .NET Framework +// ==================================================================================================== +// +// Copyright (c) 2006 +// Christophe Lambrechts +// Jonathan Slenders +// +// ==================================================================================================== +// This file is part of the .NET YAML Parser. +// +// This .NET YAML parser is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// The .NET YAML parser is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Foobar; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USAusing System.Reflection; +// ==================================================================================================== + +using System; + +// Unicode support: +// http://www.yoda.arachsys.com/csharp/unicode.html + +namespace Yaml +{ + /// + /// Yaml String node + /// + public class String : Scalar + { + private string content; + private bool block = false; + private bool folded = false; + + /// New string constructor + public String (string val) : + base ("tag:yaml.org,2002:str", NodeType.String) + { + content = val; + } + + /// Parse a string + public String (ParseStream stream) : + base ("tag:yaml.org,2002:str", NodeType.String) + { + // set flags for folded or block scalar + if (stream.Char == '>') // TODO: '+' and '-' chomp chars + folded = true; + + else if (stream.Char == '|') + block = true; + + if (block || folded) + { + stream.Next (); + stream.SkipSpaces (); + } + + // ----------------- + // Folded Scalar + // ----------------- + if (folded) + { + System.Text.StringBuilder builder = new System.Text.StringBuilder (); + + // First line (the \n after the first line is always ignored, + // not replaced with a whitespace) + while (! stream.EOF && stream.Char != '\n') + { + builder.Append (stream.Char); + stream.Next (); + } + + // Skip the first newline + stream.Next (); + + // Next lines (newlines will be replaced by spaces in folded scalars) + while (! stream.EOF) + { + if (stream.Char == '\n') + builder.Append (' '); + else + builder.Append (stream.Char); + + stream.Next (true); + } + content = builder.ToString (); + } + + // ----------------- + // Block Scalar (verbatim block without folding) + // ----------------- + else if (block) + { +/* +Console.Write(">>"); +while (! stream.EOF) +{ + Console.Write (stream.Char); + stream.Next(); +} +Console.Write("<<"); +// */ + + System.Text.StringBuilder builder = new System.Text.StringBuilder (); + while (! stream.EOF) + { + builder.Append (stream.Char); + stream.Next (true); + } + content = builder.ToString (); + } + + // String between double quotes + if (stream.Char == '\"') + content = ParseDoubleQuoted (stream); + + // Single quoted string + else if (stream.Char == '\'') + content = ParseSingleQuoted (stream); + + // String without quotes + else + content = ParseUnQuoted (stream); + } + + /// + /// Parses a String surrounded with single quotes + /// + private string ParseSingleQuoted (ParseStream stream) + { + System.Text.StringBuilder builder = new System.Text.StringBuilder (); + + // Start literal parsing + stream.StartLiteral (); + + // Skip ''' + stream.Next (true); + + while (! stream.EOF) + { + if (stream.Char == '\'') + { + stream.Next (); + + // Escaped single quote + if (stream.Char == '\'') + builder.Append (stream.Char); + + // End of string + else + break; + } + else + builder.Append (stream.Char); + + stream.Next (); + + // Skip \' + if (stream.EOF) + { + stream.StopLiteral (); + throw new ParseException (stream, + "Single quoted string not closed"); + } + } + + // Stop literal parsing + stream.StopLiteral (); + + return builder.ToString(); + } + + /// + /// Parses a String surrounded with double quotes + /// + private string ParseDoubleQuoted(ParseStream stream) + { + System.Text.StringBuilder builder = new System.Text.StringBuilder (); + + // Skip '"' + stream.Next (); + + // Stop at " + stream.StopAt (new char [] {'\"'} ); + + while (! stream.EOF) + { + if (stream.Char == '\n') + { + builder.Append (' '); + stream.Next (); + } + else + builder.Append (NextUnescapedChar (stream)); + } + + // Don't stop at " + stream.DontStop (); + + // Skip '"' + if (stream.Char != '\"') + throw new ParseException (stream, + "Double quoted string not closed"); + else + stream.Next (true); + + return builder.ToString(); + } + + /// + /// Parses a String surrounded without nothing + /// + private string ParseUnQuoted(ParseStream stream) + { + System.Text.StringBuilder builder = new System.Text.StringBuilder (); + + while (! stream.EOF) + builder.Append (NextUnescapedChar (stream)); + + // Trimming left + int count = 0; + while (count < builder.Length && + (builder [count] == ' ' || builder [count] == '\t')) + count ++; + + if (count >= 0) + builder.Remove (0, count); + + // Trimming right + count = 0; + while (count < builder.Length && + (builder [builder.Length - count - 1] == ' ' || + builder [builder.Length - count - 1] == '\t')) + count ++; + + if (count >= 0) + builder.Remove (builder.Length - count, count); + + return builder.ToString(); + } + + /// + /// Reads a character from the stream, unescapes it, + /// and moves to the next character. + /// + private char NextUnescapedChar (ParseStream stream) + { + char c = stream.Char; + + // If escaped + if (c == '\\') + { + // Never stop, every special character + // looses its meaning behind a backslash. + stream.StopAt (new Char [] { }); + + stream.Next (true); + c = stream.Char; + + // ASCII null + if (c == '0') c = '\0'; + + // ASCII bell + else if (c == 'a') c = (char) 0x7; + + // ASCII backspace + else if (c == 'b') c = (char) 0x8; + + // ASCII horizontal tab + else if (c == 't') c = (char) 0x9; + + // ASCII newline + else if (c == 'n') c = (char) 0xA; + + // ASCII vertical tab + else if (c == 'v') c = (char) 0xB; + + // ASCII form feed + else if (c == 'f') c = (char) 0xC; + + // ASCII carriage return + else if (c == 'r') c = (char) 0xD; + + // ASCII escape + else if (c == 'e') c = (char) 0x1D; + + // Unicode next line + else if (c == 'N') c = (char) 0x85; + + // Unicode non breaking space + else if (c == '_') c = (char) 0xA0; + + // TODO larger unicode characters + + // Unicode line separator + // else if (c == 'L') c = (char) 0x20282028; + + // 8 bit hexadecimal + else if (c == 'x') + { + int c_int = (char) 0; + + for (int i = 0; i < 2; i ++) + { + c_int *= 16; + + stream.Next (); + char d = stream.Char; + + if (d >= '0' && d <= '9') + c_int += d - '0'; + + else if (d >= 'a' && d <= 'f') + c_int += d - 'a'; + + else if (d >= 'A' && d <= 'F') + c_int += d - 'A'; + else + { + stream.DontStop (); + throw new ParseException (stream, + "Invalid escape sequence"); + } + } + c = (char) c_int; + } + + stream.Next (true); + + // Restore last stop settings + stream.DontStop (); + } + else + stream.Next (true); + + return c; + } + + /// Content property + public string Content + { + get { return content; } + set { content = value; } + } + + /// To String + public override string ToString () + { + return "[STRING]" + content + "[/STRING]"; + } + + /// Write + protected internal override void Write (WriteStream stream) + { + // TODO, not required, but writing to block or folded scalars + // generates a little more neat code. + + // Analyze string + bool multiline = false; + bool mustbequoted = false; + + for (int i = 0; i < content.Length; i ++) + { + char c = content [i]; + + if (c == '\n') + multiline = true; + + // We quote everything except strings like /[a-zA-Z]*/ + // However there are more strings which don't require + // quotes. + if ( ! ( c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) + mustbequoted = true; + } + + // Double quoted strings + if (mustbequoted) + { + stream.Append ("\""); + + for (int i = 0; i < content.Length; i ++) + { + char c = content [i]; + + // Backslash + if (c == '\\') stream.Append ("\\" + "\\"); + + // Double quote + else if (c == '\"') stream.Append ("\\" + "\""); + + // Single quote + else if (c == '\'') stream.Append ("\\" + "\'"); + + // ASCII null + else if (c == '\0') stream.Append ("\\0"); + + // ASCII bell + else if (c == (char) 0x7) stream.Append ("\\a"); + + // ASCII backspace + else if (c == (char) 0x8) stream.Append ("\\b"); + + // ASCII horizontal tab + else if (c == (char) 0x9) stream.Append ("\\t"); + + // ASCII newline + else if (c == (char) 0xA) stream.Append ("\\n"); + + // ASCII vertical tab + else if (c == (char) 0xB) stream.Append ("\\v"); + + // ASCII form feed + else if (c == (char) 0xC) stream.Append ("\\f"); + + // ASCII carriage return + else if (c == (char) 0xD) stream.Append ("\\r"); + + // ASCII escape + else if (c == (char) 0x1D) stream.Append ("\\e"); + + // Unicode next line + else if (c == (char) 0x85) stream.Append ("\\N"); + + // Unicode non breaking space + else if (c == (char) 0xA0) stream.Append ("\\_"); + + // TODO larger unicode characters + + else + stream.Append ("" + c); + } + stream.Append ("\""); + } + + // Simple non-quoted strings + else + stream.Append (content); + } + } +} diff --git a/thirdparty/yaml/Timestamp.cs b/thirdparty/yaml/Timestamp.cs new file mode 100644 index 0000000000..d8dc3f8e6f --- /dev/null +++ b/thirdparty/yaml/Timestamp.cs @@ -0,0 +1,356 @@ +// ==================================================================================================== +// YAML Parser for the .NET Framework +// ==================================================================================================== +// +// Copyright (c) 2006 +// Christophe Lambrechts +// Jonathan Slenders +// +// ==================================================================================================== +// This file is part of the .NET YAML Parser. +// +// This .NET YAML parser is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// The .NET YAML parser is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Foobar; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USAusing System.Reflection; +// ==================================================================================================== + +using System; + +namespace Yaml +{ + /// + /// Yaml Timestamp node + /// uri: tag:yaml.org,2002:timestamp + /// + public class Timestamp : Scalar + { + private System.DateTime content; + + /// + /// Represents the offset from the UTC time in hours + /// + /// + /// We use this extra variable for compatibility with Mono + /// and .NET 1.0. .NET 2.0 has an extra property for + /// System.Datetime for the timezone. + /// + private double timezone = 0; + + /// + /// Basic constructor that takes a given datetime + /// + /// A .NET 1.0 datetime + public Timestamp (DateTime datetime) : + base ("tag:yaml.org,2002:timestamp", NodeType.Timestamp) + { + this.content = datetime; + this.timezone = 0; + } + + /// + /// Basic constructor, that also gives the posibility to set a timezone + /// + /// A .NET 1.0 datetime + /// The offset, in hours,r to UTC that determine the timezone + public Timestamp (DateTime datetime, double timezone) : + base ("tag:yaml.org,2002:timestamp", NodeType.Timestamp) + { + this.content = datetime; + this.timezone = timezone; + } + + /// Content property + public System.DateTime Content + { + get { return content; } + set { content = value; } + } + + /// Timezone, an offset in hours + public double Timezone + { + get { return timezone; } + set { timezone = value; } + } + + /// To String + public override string ToString () + { + return "[TIMESTAMP]" + YamlString () + "[/TIMESTAMP]"; + } + + /// Parse a DateTime + public Timestamp (ParseStream stream) : + base ("tag:yaml.org,2002:timestamp", NodeType.Timestamp) + { + int year = 0; + int month = 0; + int day = 0; + int hour = 0; + int minutes = 0; + int seconds = 0; + int ms = 0; + + try + { + // Parse year + year = ParseNumber (stream, 4); + SkipChar (stream, '-'); + + // Parse month + month = ParseNumber (stream, 2); + SkipChar (stream, '-'); + + // Parse day + day = ParseNumber (stream, 2); + + // Additional, the time + if ( ! stream.EOF) + ParseTime (stream, out hour, out minutes, out seconds); + + // Additional, milliseconds + if ( ! stream.EOF) + ms = ParseMilliSeconds (stream); + + // Additional, the timezone + if ( ! stream.EOF) + timezone = ParseTimezone (stream); + + // If there is more, then a format exception + if ( ! stream.EOF) + throw new Exception ("More data then excepted"); + + content = new DateTime (year, month, day, hour, minutes, seconds, ms); + } + catch (Exception ex) + { + throw new ParseException (stream, ex.ToString ()); + } + } + + /// + /// Parse the time (hours, minutes, seconds) + /// + private void ParseTime (ParseStream stream, + out int hour, out int minutes, out int seconds) + { + if (stream.Char == 't' || stream.Char == 'T') + stream.Next (true); + else + SkipWhitespace (stream); + + // Parse hour + // Note: A hour can be represented by one or two digits. + string hulp = ""; + while (stream.Char >= '0' && stream.Char <= '9' && + ! stream.EOF && hulp.Length <= 2) + { + hulp += stream.Char; + stream.Next (true); + } + hour = Int32.Parse (hulp); + + SkipChar (stream, ':'); + + // Parse minutes + minutes = ParseNumber (stream, 2); + SkipChar (stream, ':'); + + // Parse seconds + seconds = ParseNumber (stream, 2); + } + + /// + /// Parse the milliseconds + /// + private int ParseMilliSeconds (ParseStream stream) + { + int ms = 0; + + // Look for fraction + if (stream.Char == '.') + { + stream.Next (true); + + // Parse fraction, can consists of an + // unlimited sequence of numbers, we only + // look to the first three (max 1000) + int count = 0; + + while (stream.Char >= '0' && stream.Char <= '9' && + count < 3 && ! stream.EOF) + { + ms *= 10; + ms += stream.Char - '0'; + + stream.Next (true); + count ++; + } + + if (count == 1) ms *= 100; + if (count == 2) ms *= 10; + if (count == 3) ms *= 1; + + // Ignore the rest + while (stream.Char >= '0' && stream.Char <= '9' && + ! stream.EOF) + stream.Next (true); + } + return ms; + } + + /// + /// Parse the time zone + /// + private double ParseTimezone (ParseStream stream) + { + double timezone = 0; + + SkipWhitespace (stream); + + // Timezone = UTC, use by default 0 + if (stream.Char == 'Z') + stream.Next (true); + else + { + // Find the sign of the offset + int sign = 0; + + if (stream.Char == '-') + sign = -1; + + else if (stream.Char == '+') + sign = +1; + + else + throw new Exception ("Invalid time zone: " + + "unexpected character"); + + // Read next char and test for more chars + stream.Next (true); + if (stream.EOF) + throw new Exception ("Invalid time zone"); + + // Parse hour offset + // Note: A hour can be represented by one or two digits. + string hulp = ""; + while (stream.Char >= '0' && + stream.Char <= '9' && + !stream.EOF && hulp.Length <= 2) + { + hulp += (stream.Char); + stream.Next (true); + } + timezone = sign * Double.Parse (hulp); + + // Parse the minutes of the timezone + // when there is still more to parse + if ( ! stream.EOF) + { + SkipChar (stream, ':'); + int temp = ParseNumber (stream, 2); + + timezone += (temp / 60.0); + } + } + + return timezone; + } + + /// + /// Parse an integer + /// + /// + /// The number of characters that the integer is expected to be. + /// + /// The stream that will be parsed + private int ParseNumber (ParseStream stream, int length) + { + System.Text.StringBuilder hulp = new System.Text.StringBuilder (); + + int i; + for (i = 0; i < length && !stream.EOF; i++) + { + hulp.Append (stream.Char); + stream.Next (true); + } + if (i == length) + return Int32.Parse (hulp.ToString ()); + else + throw new Exception ("Can't parse number"); + + } + + /// + /// Skips a specified char, and throws an exception when + /// another char was found. + /// + private void SkipChar (ParseStream stream, char toSkip) + { + if (stream.Char == toSkip) + stream.Next (true); + else + throw new Exception ("Unexpected character"); + } + + /// + /// Skips the spaces * and tabs * in the current stream + /// + private void SkipWhitespace (ParseStream stream) + { + while ((stream.Char == ' ' || stream.Char == '\t') && ! stream.EOF) + stream.Next (true); + } + + /// Yaml notation for this datetime + private string YamlString () + { + string date = content.ToString ("yyyy-MM-ddTHH:mm:ss"); + int ms = content.Millisecond; + if (ms != 0) + { + string hulp = "" + (ms / 1000.0); + hulp = hulp.Substring(2); // Cut of the '0,', first 2 digits + + date += "." + hulp; + } + string zone = ""; + + if (timezone != 0) + { + int timezoneHour = (int) Math.Floor (timezone); + int timezoneMinutes = (int) (60 * (timezone - timezoneHour)); + + // if positif offset add '+', a '-' is default added + if (timezone > 0) + zone = "+"; + + zone += timezoneHour.ToString (); + if (timezoneMinutes != 0) + zone += ":" + timezoneMinutes; + } + else + zone = "Z"; // UTC timezone as default and if offset == 0 + + return date + zone; + } + + /// Write to YAML + protected internal override void Write (WriteStream stream) + { + stream.Append (YamlString ()); + } + } +} + + diff --git a/thirdparty/yaml/WriteStream.cs b/thirdparty/yaml/WriteStream.cs new file mode 100644 index 0000000000..508250d311 --- /dev/null +++ b/thirdparty/yaml/WriteStream.cs @@ -0,0 +1,121 @@ +// ==================================================================================================== +// YAML Parser for the .NET Framework +// ==================================================================================================== +// +// Copyright (c) 2006 +// Christophe Lambrechts +// Jonathan Slenders +// +// ==================================================================================================== +// This file is part of the .NET YAML Parser. +// +// This .NET YAML parser is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// The .NET YAML parser is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with Foobar; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USAusing System.Reflection; +// ==================================================================================================== + +#define ENABLE_COMPRESSION + +using System; +using System.Collections; + +using System.IO; + +namespace Yaml +{ + /// + /// Help class for writing a Yaml tree to a string + /// + public class WriteStream + { + private TextWriter stream; + private int indentation = 0; + private bool lastcharisnewline = false; + + private static string indentationChars = " "; + + /// Constructor + public WriteStream (TextWriter stream) + { + this.stream = stream; + } + + /// Append a string + public void Append (string s) + { + // Just add the text to the output stream when + // there is no indentation + if (indentation == 0) + stream.Write (s); + + // Otherwise process each individual char + else + for (int i = 0; i < s.Length; i ++) + { + // Indent after a newline + if (lastcharisnewline) + { + WriteIndentation (); + lastcharisnewline = false; + } + + // Add char + stream.Write (s [i]); + + // Remember newlines + if (s [i] == '\n') + lastcharisnewline = true; + } + } + + /// Indentation + public void Indent () + { + // Increase indentation level + indentation ++; + + // Add a newline +#if ENABLE_COMPRESSION + lastcharisnewline = false; +#else + stream.Write ("\n"); + lastcharisnewline = true; +#endif + } + + /// Write the indentation to the output stream + private void WriteIndentation () + { + for (int i = 0; i < indentation; i ++) + stream.Write (indentationChars); + } + + /// Unindent + public void UnIndent () + { + if (indentation > 0) + { + // Decrease indentation level + indentation --; + + // Add a newline + if (! lastcharisnewline) + stream.Write ("\n"); + lastcharisnewline = true; + } + else + throw new Exception ("Cannot unindent a not indented writestream."); + + } + } +} diff --git a/thirdparty/yaml/Yaml.csproj b/thirdparty/yaml/Yaml.csproj new file mode 100644 index 0000000000..ee12932481 --- /dev/null +++ b/thirdparty/yaml/Yaml.csproj @@ -0,0 +1,188 @@ + + + Local + 9.0.30729 + 2.0 + {D4424F4D-7939-4247-98F5-6A7F6DEBA7C9} + Debug + AnyCPU + + + + + Yaml + + + JScript + Grid + IE50 + false + Library + Yaml + OnBuildSuccess + + + + + 0.0 + + + v3.5 + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + bin\Debug\ + false + 285212672 + false + + + DEBUG;TRACE + + + true + 4096 + false + + + false + false + false + false + 4 + full + prompt + + + .\ + false + 285212672 + false + + + TRACE + + + false + 4096 + false + + + true + false + false + false + 4 + none + prompt + + + + System + + + 3.5 + + + System.Data + + + System.XML + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + False + .NET Framework Client Profile + false + + + False + .NET Framework 2.0 %28x86%29 + true + + + False + .NET Framework 3.0 %28x86%29 + false + + + False + .NET Framework 3.5 + false + + + False + .NET Framework 3.5 SP1 + false + + + + + + + + + + \ No newline at end of file diff --git a/thirdparty/yaml/Yaml.sln b/thirdparty/yaml/Yaml.sln new file mode 100644 index 0000000000..a451a53232 --- /dev/null +++ b/thirdparty/yaml/Yaml.sln @@ -0,0 +1,19 @@ +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Yaml", "Yaml.csproj", "{D4424F4D-7939-4247-98F5-6A7F6DEBA7C9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D4424F4D-7939-4247-98F5-6A7F6DEBA7C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D4424F4D-7939-4247-98F5-6A7F6DEBA7C9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D4424F4D-7939-4247-98F5-6A7F6DEBA7C9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D4424F4D-7939-4247-98F5-6A7F6DEBA7C9}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/thirdparty/yaml/test.yaml b/thirdparty/yaml/test.yaml new file mode 100644 index 0000000000..0271bb757e --- /dev/null +++ b/thirdparty/yaml/test.yaml @@ -0,0 +1,24 @@ +? boolean: y +? float: 8.6e2 +? integer: 174832 +? null: ~ +? inline sequence: [item1, item2] +? inline mappings: {key: value, key2: value2} +? sequence: + - item 1 + - item 2 +? tricky situations: + - ? block scalar: | + regel 1 + regel 2 + - ? folded scalar: > + regel 1 + nog steeds regel 1 + - ? double quoted: "met veel escapes aa\"bb\n\'cc" + - ? met tags: + - !!int 2 + - !!string 2 + - !!float 2 + - { key: value, key 3: "{a: b}", key 2: a } + - ? [aaa]: bbb + - ? single quotes: 'regel 1 regel 2' From 7f928603797370f01d821c180aa444ed65a3f519 Mon Sep 17 00:00:00 2001 From: Chris Forbes Date: Sat, 9 Jan 2010 19:27:17 +1300 Subject: [PATCH 34/34] V2 in yaml --- ra.yaml | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 ra.yaml diff --git a/ra.yaml b/ra.yaml new file mode 100644 index 0000000000..c6e03e0b9b --- /dev/null +++ b/ra.yaml @@ -0,0 +1,17 @@ +# +# Red Alert rules +# + +Vehicles: + V2RL: + Buildable: { Description="V2 Rocket", Prerequisites=[weap,dome], TechLevel=4, Cost=700, + LongDesc="Long-range rocket artillery.\n Strong vs Infantry, Buildings\n Weak vs Tanks, Aircraft" } + Unit: { HP=150, Armor=light, Crewed=yes, Voice=VehicleVoice } + Mobile: { Sight=5, ROT=5, Speed=7, UMT=Track } + AttackBase: { Primary=SCUD, Ammo=1 } + RenderUnitReload: {} + AutoTarget: {} + Repairable: {} + Chronoshiftable: {} + Passenger: {} + IronCurtainable: {} \ No newline at end of file