Inheritance: MonoBehaviour
        public void Universe_SetInitialState_ValidStringWith4Cells_CellCountIs4()
        {
            var universe = new Universe();
            universe.SetInitialState(".OOO");

            Assert.IsTrue(universe.Cells.Count == 4);
        }
Beispiel #2
0
 void Start()
 {
     if (Network.isServer) {
         bossPrefabs = Resources.LoadAll("enemies/bosses/Prefabs", typeof(GameObject));
         positions = transform.parent.FindChild("OriginManager").GetComponent<Universe>();
     }
 }
        public void Universe_SetInitialState_StringContainsInvalidChars_CellCountIs0()
        {
            var universe = new Universe();
            universe.SetInitialState(".x.");

            Assert.IsTrue(universe.Cells.Count == 0);
        }
        public void Universe_SetInitialState_OneDeadCell_CellCountIs1()
        {
            var universe = new Universe();
            universe.SetInitialState(".");

            Assert.IsTrue(universe.Cells.Count == 1);
        }
    public List<AttackPlan> BuildActionPlan(Universe uni)
    {
        currentUniverse = uni;
        StartOfTurn();
        DefendOnwedPlanets();
        DefendNeutralPlanets(MaxTurnLookaheadForNeutralDefense);
        List<AttackPlan> battleplan = new List<AttackPlan>();
        foreach (Planet onwedPlanet in currentUniverse.Me.Planets.Where(OwnedPlanetCanSendAttackForce))
        {
            if (SourcePlanetSelected(onwedPlanet))
            {
                var planetTravelMap = Universe.TravelMap[onwedPlanet.PlanetID];
                if (PlanetRouteSelected(onwedPlanet, planetTravelMap))
                {
                    bool continueRoute = true;
                    AttackPlan attack = new AttackPlan();
                    foreach (Route route in planetTravelMap)
                    {
                        Planet hostile = currentUniverse.AllPlanetsOnPlanetId[route.TagetPlanetId];
                        if (!hostile.IsMine)
                        {
                            attack.Distance = route.DistanceInTurns;
                            attack.Source = onwedPlanet;
                            attack.Target = hostile;
                            attack.Enabled = false;

                            CreateAttackPlanForOwnedPlanet(attack, route, planetTravelMap, ref continueRoute);

                            if (attack.Enabled)
                            {
                                battleplan.Add(attack);
                                attack = new AttackPlan();
                            }
                        }
                        if (!continueRoute) { break; }
                    }
                }
                PlanetRouteDeSelected(onwedPlanet, planetTravelMap);
            }
        }
        if (!TakeGamble_DoNotCountOutgoingShipsForOneTurn)
        {
            //attack planets for all fleets in transit
            foreach (Planet planet in uni.All.Planets)
            {
                if (!(planet.IsLost || planet.Armada.Count == 0))
                {
                    foreach (Fleet attackforce in planet.Armada)
                    {
                        if (attackforce.IsMine)
                        {
                            planet.RemoveShips(attackforce.NumShips);
                        }
                    }
                }
            }
        }
        TakeGamble_DoNotCountOutgoingShipsForOneTurn = false;
        return battleplan;
    }
        public void Universe_SetInitialState_NullString_CellsCountIs0()
        {
            var universe = new Universe();
            universe.SetInitialState(null);

            Assert.IsTrue(universe.Cells.Count == 0);
        }
Beispiel #7
0
 void modifyName(string name)
 {
     gameObject.name = name;
     int universeNb = int.Parse(name.Substring(name.Length-1, 1));
     gameObject.transform.parent = GameObject.Find("Universe"+universeNb+"/Enemies").transform;
     Positions = transform.parent.parent.FindChild("Managers/OriginManager").GetComponent<Universe>();
     gameObject.rigidbody.AddForce(Vector3.left * (astBaseForce + Random.Range(-forceOffset, forceOffset)));
 }
Beispiel #8
0
 public void TestGetEmptyNeighbor()
 {
     Universe universe = new Universe();
     Cell cell = new Cell(1, 1);
     universe.Add(cell);
     IEnumerable<Cell> expected = universe.GetNeighbors(cell);
     Assert.IsTrue(!expected.Any());
 }
Beispiel #9
0
 public void GetCellInUniverse()
 {
     Universe universe = new Universe();
     Cell cell = new Cell(1, 1);
     universe.Add(cell);
     Cell expected = universe.GetCell(cell);
     Assert.IsTrue(expected.Equals(cell));
 }
Beispiel #10
0
        public Game(Universe universe, IEnumerable<TickRegistrationFactory> tickRegistrationFactories)
        {
            Universe = universe;

            _updateFunctions = tickRegistrationFactories.SelectMany(f => f(universe)).ToList();
            _idle = new IdleTimer();
            _tick = 0;
        }
Beispiel #11
0
 public void UniverseAddDuplicatedLivingCells()
 {
     Universe universe = new Universe();
     universe.Add(new Cell(1, 1));
     universe.Add(new Cell(1, 1));
     List<Cell> cells = universe.GetAllLivingCells();
     Assert.IsTrue(cells.Count == 1);
 }
        public void GetNeigboursCountTest(int x, int y, int expectedCount)
        {
            var universe = new Universe(0, 0, 128, 128, Oscillators.GetBlinkerAt(1, 1));

            var count = universe.GetNeighborCount(x, y);

            Assert.AreEqual(expectedCount, count);
        }
 /// <summary>
 /// Does the turn.
 /// </summary>
 /// <param name="uni">The uni.</param>
 public static void DoTurn(Universe uni)
 {
     ChooseStrategy(uni);
     List<AttackPlan> actionPlan = strategy.BuildActionPlan(uni);
     if (!SortAndMakeMoves(uni, actionPlan))
     {
         strategy.AttackPlanFailed();
     }
 }
Beispiel #14
0
        public void AddUniverse(Universe universe)
        {
            if (Universes.Any(item => item.Equals(universe)))
            {
                throw new InvalidOperationException();
            }

            universes.Add(universe);
        }
Beispiel #15
0
 public void TestGetManyNeiborghs()
 {
     Universe universe = new Universe();
     universe.Add(new Cell(1, 1));
     universe.Add(new Cell(2, 1));
     universe.Add(new Cell(1, 2));
     IEnumerable<Cell> expected = universe.GetNeighbors(new Cell(1, 1));
     Assert.IsTrue(expected.Count() == 2);
 }
Beispiel #16
0
 public void TestLivingCellDie()
 {
     Universe universe = new Universe();
     Cell cell = new Cell(1, 1);
     universe.Add(cell);
     universe.Tick();
     Cell expected = universe.GetCell(cell);
     Assert.IsTrue(expected == null);
 }
Beispiel #17
0
 /// <param name="u">A Universe to display.</param>
 public Canvas(Universe u)
     : base(1920, 1080, new OpenTK.Graphics.GraphicsMode(16, 16))
 {
     universe = u;
     m_camera = new rope.camera (CoordinateEngine.toVector3(universe.bro.x), new Vector3(0,0,-1), new Vector3(0,1,0));
     printer = new OpenTK.Graphics.TextPrinter();
     stats = Stats.Instance();
     stats.AddValue(FPS_TAG, -1);
 }
Beispiel #18
0
 public void TestDyingCellBecomeALive()
 {
     Universe universe = new Universe();
     universe.Add(new Cell(1, 1));
     universe.Add(new Cell(2, 1));
     universe.Add(new Cell(1, 2));
     universe.Tick();
     Cell expected = universe.GetCell(new Cell(2, 2));
     Assert.IsTrue(expected != null);
 }
 private static void ChooseStrategy(Universe uni)
 {
     if (Universe.IsDominating || Universe.TurnCount > 100)
     {
         if (strategy is DefensiveBotStrategy)
         {
             //strategy = new AverageAggressionStrategy();
         }
     }
 }
Beispiel #20
0
 internal ModuleReader(AssemblyReader assembly, Universe universe, Stream stream, string location)
     : base(universe)
 {
     this.stream = universe != null && universe.MetadataOnly ? null : stream;
     this.location = location;
     Read(stream);
     if (assembly == null && AssemblyTable.records.Length != 0)
     {
         assembly = new AssemblyReader(location, this);
     }
     this.assembly = assembly;
 }
	static void Main(string[] args)
	{
		Universe universe = new Universe();
		AssemblyName name = new AssemblyName("System.Core");
		name.Version = new Version(3, 5);
		name.SetPublicKey(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
		AssemblyBuilder ab = universe.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save);
		ModuleBuilder modb = ab.DefineDynamicModule("System.Core", "System.Core.dll");
		TypeBuilder tb = modb.DefineType("System.Runtime.CompilerServices.ExtensionAttribute", TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed, universe.Import(typeof(Attribute)));
		tb.DefineDefaultConstructor(MethodAttributes.Public);
		tb.CreateType();
		ab.Save("System.Core.dll");
	}
Beispiel #22
0
    // Use this for initialization
    void Start()
    {
        if (Network.isServer)
        {
            if (!gameObject.name.StartsWith("rock"))
            {
                networkView.RPC("modifyName", RPCMode.All, gameObject.name);
                Debug.Log("Problem" + gameObject.name);

                Positions = transform.parent.parent.FindChild("Managers/OriginManager").GetComponent<Universe>();
            }
            gameObject.rigidbody.AddForce(Vector3.left * (astBaseForce + Random.Range(-forceOffset, forceOffset)));
        }
    }
Beispiel #23
0
        public MainForm()
        {
            InitializeComponent();

            _universe = new Universe();
            _simulation = new Simulation();
            _universeRules = new UniverseRules(_universe);
            _universeView = new UniverseView(_universe);

            Button_StartSimulation.Text = Resources.GUIStrings.Button_StartSimulation;
            Button_StopSimulation.Text = Resources.GUIStrings.Button_StopSimulation;
            Button_PauseSimulation.Text = Resources.GUIStrings.Button_PauseSimulation;

            _simulation.RegisterTickEventHandler(SimulationStep);
        }
    public void enteredRealm(Universe u)
    {
        realmTextUI.text = "You have entered the " + u.type + " well.";
        missedPortalAudioBlockTimeStart = Time.realtimeSinceStartup;
        missedPortalAudioBlock = true;
        if( heldWish != null && u.type == heldWish.type )
        {
            secretsTextUI.text = "You have granted the wish by bringing it to the correct well!";
            successfulWishDropSound.Play();
            if (wishesGranted < 2)
            {
                wishesGranted++;
                if (wishesGranted == 2)
                {
                    preventFinalWish = false;
                }
            }
            else
            {
                if( heldWish.secretText == Wish.winWish && !gameEnded )
                {
                    secretsTextUI.text = "You have granted your lover's wish. You win!";
                    this.enabled = false;
                    gameEnded = true;
                    currentWellMusic.Stop();
                    gameEndMusic.Play();

                    // show the end movie quad
                    endMovieQuad.gameObject.SetActive(true);
                    // REALLY show it - workaround for portal teleport bug
                    endMovieQuad.transform.localPosition = new Vector3(0f, -8.19f, 8.9f);

                    StartCoroutine(waitLoadEndMovie());
                }
            }
            heldWish.enabled = true;
            heldWish = null;
        }
        else if( heldWish != null )
        {
            wrongWishDropSound.Play();
        }

        if(!gameEnded)
        {
            StartCoroutine("ChangeMusic", u.wellMusic);
        }
    }
Beispiel #25
0
 internal ModuleReader(AssemblyReader assembly, Universe universe, Stream stream, string location, bool mapped)
     : base(universe)
 {
     this.stream = universe != null && universe.MetadataOnly ? null : stream;
     this.location = location;
     Read(stream, mapped);
     if (universe != null && universe.WindowsRuntimeProjection && imageRuntimeVersion.StartsWith("WindowsRuntime ", StringComparison.Ordinal))
     {
         WindowsRuntimeProjection.Patch(this, strings, ref imageRuntimeVersion, ref blobHeap);
     }
     if (assembly == null && AssemblyTable.records.Length != 0)
     {
         assembly = new AssemblyReader(location, this);
     }
     this.assembly = assembly;
 }
Beispiel #26
0
 internal AssemblyBuilder(Universe universe, AssemblyName name, string dir, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions, IEnumerable<CustomAttributeBuilder> customAttributes)
     : base(universe)
 {
     this.name = name.Name;
     SetVersionHelper(name.Version);
     if (!string.IsNullOrEmpty(name.Culture))
     {
         this.culture = name.Culture;
     }
     this.flags = name.RawFlags;
     this.hashAlgorithm = name.HashAlgorithm;
     if (this.hashAlgorithm == AssemblyHashAlgorithm.None)
     {
         this.hashAlgorithm = AssemblyHashAlgorithm.SHA1;
     }
     this.keyPair = name.KeyPair;
     if (this.keyPair != null)
     {
         this.publicKey = this.keyPair.PublicKey;
     }
     else
     {
         byte[] publicKey = name.GetPublicKey();
         if (publicKey != null && publicKey.Length != 0)
         {
             this.publicKey = (byte[])publicKey.Clone();
         }
     }
     this.dir = dir ?? ".";
     this.requiredPermissions = requiredPermissions;
     this.optionalPermissions = optionalPermissions;
     this.refusedPermissions = refusedPermissions;
     if (customAttributes != null)
     {
         this.customAttributes.AddRange(customAttributes);
     }
     if (universe.HasMscorlib && !universe.Mscorlib.__IsMissing && universe.Mscorlib.ImageRuntimeVersion != null)
     {
         this.imageRuntimeVersion = universe.Mscorlib.ImageRuntimeVersion;
     }
     else
     {
         this.imageRuntimeVersion = typeof(object).Assembly.ImageRuntimeVersion;
     }
     universe.RegisterDynamicAssembly(this);
 }
        public static void Main()
        {
            //System.Diagnostics.Debugger.Launch();
            int c;
            Universe universe = new Universe(null);
            try
            {

                StringBuilder input = new StringBuilder();
                StringBuilder line = new StringBuilder();

                while ((c = Console.Read()) >= 0)
                {
                    switch (c)
                    {
                        case '\r':
                            break;
                        case '\n':
                            string thisLine = line.ToString();
                            if (thisLine.Equals("go"))
                            {
                                universe.StartTurn(input.ToString());
                                input.Length = 0;
                                universe.FinishTurn();
                            }
                            else
                            {
                                input.Append(thisLine + "\n");
                            }
                            line.Length = 0;
                            break;
                        default:
                            line.Append((char)c);
                            break;
                    }
                }
            }
            catch (Exception)
            {
                // Owned.
            }
        }
    public static void Main()
    {
        int c;
        try
        {

            StringBuilder input = new StringBuilder();
            StringBuilder line = new StringBuilder();

            while ((c = Console.Read()) >= 0)
            {
                switch (c)
                {
                    case '\r':
                        break;
                    case '\n':
                        string thisLine = line.ToString();
                        if (thisLine.Equals("go"))
                        {
                            Universe uni = new Universe(input.ToString(), null);
                            input.Length = 0;

                            FannyHeirdooBot.DoTurn(uni);
                            uni.FinishTurn();
                        }
                        else
                        {
                            input.Append(thisLine + "\n");
                        }
                        line.Length = 0;
                        break;
                    default:
                        line.Append((char)c);
                        break;
                }
            }
        }
        catch (Exception)
        {
            // Owned.
        }
    }
Beispiel #29
0
		internal AssemblyBuilder(Universe universe, AssemblyName name, string dir, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions)
			: base(universe)
		{
			this.name = name.Name;
			SetVersionHelper(name.Version);
			if (name.CultureInfo != null && !string.IsNullOrEmpty(name.CultureInfo.Name))
			{
				this.culture = name.CultureInfo.Name;
			}
			this.flags = name.Flags;
			this.hashAlgorithm = name.HashAlgorithm;
			if (this.hashAlgorithm == AssemblyHashAlgorithm.None)
			{
				this.hashAlgorithm = AssemblyHashAlgorithm.SHA1;
			}
			this.keyPair = name.KeyPair;
			if (this.keyPair != null)
			{
				this.publicKey = this.keyPair.PublicKey;
			}
			else
			{
				byte[] publicKey = name.GetPublicKey();
				if (publicKey != null && publicKey.Length != 0)
				{
					this.publicKey = (byte[])publicKey.Clone();
				}
			}
			this.dir = dir ?? ".";
			this.requiredPermissions = requiredPermissions;
			this.optionalPermissions = optionalPermissions;
			this.refusedPermissions = refusedPermissions;
			if (universe.HasMscorlib && universe.Mscorlib.ImageRuntimeVersion != null)
			{
				this.imageRuntimeVersion = universe.Mscorlib.ImageRuntimeVersion;
			}
			else
			{
				this.imageRuntimeVersion = typeof(object).Assembly.ImageRuntimeVersion;
			}
		}
Beispiel #30
0
    int Main3(string [] args)
    {
        bool          show_help = false;
        bool          zero_copy = false;
        string        basedir = null;
        string        tmpdir = null;
        string        ns = null;
        bool          delete_temp = true, debug = false;
        bool          unsafef          = true;
        bool          external         = false;
        bool          public_mode      = true;
        bool          nostdlib         = false;
        bool?         inline_selectors = null;
        List <string> sources;
        var           resources          = new List <string> ();
        var           linkwith           = new List <string> ();
        var           references         = new List <string> ();
        var           api_sources        = new List <string> ();
        var           core_sources       = new List <string> ();
        var           extra_sources      = new List <string> ();
        var           defines            = new List <string> ();
        string        generate_file_list = null;
        bool          process_enums      = false;
        string        compiler           = "/Library/Frameworks/Mono.framework/Versions/Current/bin/csc";

        ErrorHelper.ClearWarningLevels();

        var os = new OptionSet()
        {
            { "h|?|help", "Displays the help", v => show_help = true },
            { "a", "Include alpha bindings (Obsolete).", v => {}, true },
            { "outdir=", "Sets the output directory for the temporary binding files", v => { basedir = v; } },
            { "o|out=", "Sets the name of the output library", v => outfile = v },
            { "tmpdir=", "Sets the working directory for temp files", v => { tmpdir = v; delete_temp = false; } },
            { "debug", "Generates a debugging build of the binding", v => debug = true },
            { "sourceonly=", "Only generates the source", v => generate_file_list = v },
            { "ns=", "Sets the namespace for storing helper classes", v => ns = v },
            { "unsafe", "Sets the unsafe flag for the build", v => unsafef = true },
            { "core", "Use this to build product assemblies", v => BindThirdPartyLibrary = false },
            { "r|reference=", "Adds a reference", v => references.Add(v) },
            { "lib=", "Adds the directory to the search path for the compiler", v => libs.Add(v) },
            { "compiler=", "Sets the compiler to use (Obsolete) ", v => compiler = v, true },
            { "sdk=", "Sets the .NET SDK to use (Obsolete)", v => {}, true },
            { "new-style", "Build for Unified (Obsolete).", v => { Console.WriteLine("The --new-style option is obsolete and ignored."); }, true },
            { "d=", "Defines a symbol", v => defines.Add(v) },
            { "api=", "Adds a API definition source file", v => api_sources.Add(v) },
            { "s=", "Adds a source file required to build the API", v => core_sources.Add(v) },
            { "q", "Quiet", v => Driver.Verbosity++ },
            { "v", "Sets verbose mode", v => Driver.Verbosity-- },
            { "x=", "Adds the specified file to the build, used after the core files are compiled", v => extra_sources.Add(v) },
            { "e", "Generates smaller classes that can not be subclassed (previously called 'external mode')", v => external = true },
            { "p", "Sets private mode", v => public_mode = false },
            { "baselib=", "Sets the base library", v => baselibdll = v },
            { "attributelib=", "Sets the attribute library", v => attributedll = v },
            { "use-zero-copy", v => zero_copy = true },
            { "nostdlib", "Does not reference mscorlib.dll library", l => nostdlib = true },
            { "no-mono-path", "Launches compiler with empty MONO_PATH", l => { }, true },
            { "native-exception-marshalling", "Enable the marshalling support for Objective-C exceptions", (v) => { /* no-op */ } },
            { "inline-selectors:", "If Selector.GetHandle is inlined and does not need to be cached (enabled by default in Xamarin.iOS, disabled in Xamarin.Mac)",
              v => inline_selectors = string.Equals("true", v, StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(v) },
            { "process-enums", "Process enums as bindings, not external, types.", v => process_enums = true },
            { "link-with=,", "Link with a native library {0:FILE} to the binding, embedded as a resource named {1:ID}",
              (path, id) => {
                  if (path == null || path.Length == 0)
                  {
                      throw new Exception("-link-with=FILE,ID requires a filename.");
                  }

                  if (id == null || id.Length == 0)
                  {
                      id = Path.GetFileName(path);
                  }

                  if (linkwith.Contains(id))
                  {
                      throw new Exception("-link-with=FILE,ID cannot assign the same resource id to multiple libraries.");
                  }

                  resources.Add(string.Format("-res:{0},{1}", path, id));
                  linkwith.Add(id);
              } },
            { "unified-full-profile", "Launches compiler pointing to XM Full Profile", l => { /* no-op*/ }, true },
            { "unified-mobile-profile", "Launches compiler pointing to XM Mobile Profile", l => { /* no-op*/ }, true },
            { "target-framework=", "Specify target framework to use. Always required, and the currently supported values are: 'Xamarin.iOS,v1.0', 'Xamarin.TVOS,v1.0', 'Xamarin.WatchOS,v1.0', 'XamMac,v1.0', 'Xamarin.Mac,Version=v2.0,Profile=Mobile', 'Xamarin.Mac,Version=v4.5,Profile=Full' and 'Xamarin.Mac,Version=v4.5,Profile=System')", v => SetTargetFramework(v) },
            { "warnaserror:", "An optional comma-separated list of warning codes that should be reported as errors (if no warnings are specified all warnings are reported as errors).", v => {
                  try {
                      if (!string.IsNullOrEmpty(v))
                      {
                          foreach (var code in v.Split(new char [] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                          {
                              ErrorHelper.SetWarningLevel(ErrorHelper.WarningLevel.Error, int.Parse(code));
                          }
                      }
                      else
                      {
                          ErrorHelper.SetWarningLevel(ErrorHelper.WarningLevel.Error);
                      }
                  } catch (Exception ex) {
                      throw ErrorHelper.CreateError(26, ex.Message);
                  }
              } },
            { "nowarn:", "An optional comma-separated list of warning codes to ignore (if no warnings are specified all warnings are ignored).", v => {
                  try {
                      if (!string.IsNullOrEmpty(v))
                      {
                          foreach (var code in v.Split(new char [] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                          {
                              ErrorHelper.SetWarningLevel(ErrorHelper.WarningLevel.Disable, int.Parse(code));
                          }
                      }
                      else
                      {
                          ErrorHelper.SetWarningLevel(ErrorHelper.WarningLevel.Disable);
                      }
                  } catch (Exception ex) {
                      throw ErrorHelper.CreateError(26, ex.Message);
                  }
              } },
            new Mono.Options.ResponseFileSource(),
        };

        try {
            sources = os.Parse(args);
        } catch (Exception e) {
            Console.Error.WriteLine("{0}: {1}", ToolName, e.Message);
            Console.Error.WriteLine("see {0} --help for more information", ToolName);
            return(1);
        }

        if (show_help)
        {
            ShowHelp(os);
            return(0);
        }

        if (!target_framework.HasValue)
        {
            throw ErrorHelper.CreateError(86);
        }

        switch (target_framework.Value.Platform)
        {
        case ApplePlatform.iOS:
            CurrentPlatform = PlatformName.iOS;
            nostdlib        = true;
            if (string.IsNullOrEmpty(baselibdll))
            {
                baselibdll = Path.Combine(GetSDKRoot(), "lib/mono/Xamarin.iOS/Xamarin.iOS.dll");
            }
            if (!IsDotNet)
            {
                references.Add("Facades/System.Drawing.Common");
                ReferenceFixer.FixSDKReferences(GetSDKRoot(), "lib/mono/Xamarin.iOS", references);
            }
            break;

        case ApplePlatform.TVOS:
            CurrentPlatform = PlatformName.TvOS;
            nostdlib        = true;
            if (string.IsNullOrEmpty(baselibdll))
            {
                baselibdll = Path.Combine(GetSDKRoot(), "lib/mono/Xamarin.TVOS/Xamarin.TVOS.dll");
            }
            if (!IsDotNet)
            {
                references.Add("Facades/System.Drawing.Common");
                ReferenceFixer.FixSDKReferences(GetSDKRoot(), "lib/mono/Xamarin.TVOS", references);
            }
            break;

        case ApplePlatform.WatchOS:
            CurrentPlatform = PlatformName.WatchOS;
            nostdlib        = true;
            if (string.IsNullOrEmpty(baselibdll))
            {
                baselibdll = Path.Combine(GetSDKRoot(), "lib/mono/Xamarin.WatchOS/Xamarin.WatchOS.dll");
            }
            if (!IsDotNet)
            {
                references.Add("Facades/System.Drawing.Common");
                ReferenceFixer.FixSDKReferences(GetSDKRoot(), "lib/mono/Xamarin.WatchOS", references);
            }
            break;

        case ApplePlatform.MacOSX:
            CurrentPlatform = PlatformName.MacOSX;
            nostdlib        = true;
            if (string.IsNullOrEmpty(baselibdll))
            {
                if (target_framework == TargetFramework.Xamarin_Mac_2_0_Mobile)
                {
                    baselibdll = Path.Combine(GetSDKRoot(), "lib", "reference", "mobile", "Xamarin.Mac.dll");
                }
                else if (target_framework == TargetFramework.Xamarin_Mac_4_5_Full || target_framework == TargetFramework.Xamarin_Mac_4_5_System)
                {
                    baselibdll = Path.Combine(GetSDKRoot(), "lib", "reference", "full", "Xamarin.Mac.dll");
                }
                else
                {
                    throw ErrorHelper.CreateError(1053, target_framework);
                }
            }
            if (target_framework == TargetFramework.Xamarin_Mac_2_0_Mobile)
            {
                skipSystemDrawing = true;
                references.Add("Facades/System.Drawing.Common");
                ReferenceFixer.FixSDKReferences(GetSDKRoot(), "lib/mono/Xamarin.Mac", references);
            }
            else if (target_framework == TargetFramework.Xamarin_Mac_4_5_Full)
            {
                skipSystemDrawing = true;
                references.Add("Facades/System.Drawing.Common");
                ReferenceFixer.FixSDKReferences(GetSDKRoot(), "lib/mono/4.5", references);
            }
            else if (target_framework == TargetFramework.Xamarin_Mac_4_5_System)
            {
                skipSystemDrawing = false;
                ReferenceFixer.FixSDKReferences("/Library/Frameworks/Mono.framework/Versions/Current/lib/mono/4.5", references, forceSystemDrawing: true);
            }
            else if (target_framework == TargetFramework.DotNet_5_0_macOS)
            {
                skipSystemDrawing = false;
            }
            else
            {
                throw ErrorHelper.CreateError(1053, target_framework);
            }

            break;

        default:
            throw ErrorHelper.CreateError(1053, target_framework);
        }

        if (sources.Count > 0)
        {
            api_sources.Insert(0, sources [0]);
            for (int i = 1; i < sources.Count; i++)
            {
                core_sources.Insert(i - 1, sources [i]);
            }
        }

        if (api_sources.Count == 0)
        {
            Console.WriteLine("Error: no api file provided");
            ShowHelp(os);
            return(1);
        }

        if (tmpdir == null)
        {
            tmpdir = GetWorkDir();
        }

        string firstApiDefinitionName = Path.GetFileNameWithoutExtension(api_sources [0]);

        firstApiDefinitionName = firstApiDefinitionName.Replace('-', '_');          // This is not exhaustive, but common.
        if (outfile == null)
        {
            outfile = firstApiDefinitionName + ".dll";
        }

        var refs  = references.Select((v) => "-r:" + v);
        var paths = libs.Select((v) => "-lib:" + v);

        try {
            var tmpass = Path.Combine(tmpdir, "temp.dll");

            // -nowarn:436 is to avoid conflicts in definitions between core.dll and the sources
            // Keep source files at the end of the command line - csc will create TWO assemblies if any sources preceed the -out parameter
            var cargs = new List <string> ();

            cargs.Add("-debug");
            cargs.Add("-unsafe");
            cargs.Add("-target:library");
            cargs.Add("-nowarn:436");
            cargs.Add("-out:" + tmpass);
            cargs.Add("-r:" + GetAttributeLibraryPath());
            cargs.AddRange(refs);
            if (unsafef)
            {
                cargs.Add("-unsafe");
            }
            cargs.Add("-r:" + baselibdll);
            foreach (var def in defines)
            {
                cargs.Add("-define:" + def);
            }
            cargs.AddRange(paths);
            if (nostdlib)
            {
                cargs.Add("-nostdlib");
                cargs.Add("-noconfig");
            }
            cargs.AddRange(api_sources);
            cargs.AddRange(core_sources);
            if (!string.IsNullOrEmpty(Path.GetDirectoryName(baselibdll)))
            {
                cargs.Add("-lib:" + Path.GetDirectoryName(baselibdll));
            }

            if (Driver.RunCommand(compiler, cargs, null, out var compile_output, true, Driver.Verbosity) != 0)
            {
                throw ErrorHelper.CreateError(2, compile_output.ToString().Replace("\n", "\n\t"));
            }


            universe = new Universe(UniverseOptions.EnableFunctionPointers | UniverseOptions.ResolveMissingMembers | UniverseOptions.MetadataOnly);
            if (IsDotNet)
            {
                // IKVM tries uses reflection to locate assemblies on disk, but .NET doesn't include reflection so that fails.
                // Instead intercept assembly resolution and look for assemblies where we know they are.
                var resolved_assemblies = new Dictionary <string, Assembly> ();
                universe.AssemblyResolve += (object sender, IKVM.Reflection.ResolveEventArgs rea) => {
                    var an = new AssemblyName(rea.Name);

                    // Check if we've already found this assembly
                    if (resolved_assemblies.TryGetValue(an.Name, out var rv))
                    {
                        return(rv);
                    }

                    // Check if the assembly has already been loaded into IKVM
                    var assemblies = universe.GetAssemblies();
                    foreach (var asm in assemblies)
                    {
                        if (asm.GetName().Name == an.Name)
                        {
                            resolved_assemblies [an.Name] = asm;
                            return(asm);
                        }
                    }

                    // Look in the references to find a matching one and get the path from there.
                    foreach (var r in references)
                    {
                        var fn = Path.GetFileNameWithoutExtension(r);
                        if (fn == an.Name)
                        {
                            rv = universe.LoadFile(r);
                            resolved_assemblies [an.Name] = rv;
                            return(rv);
                        }
                    }

                    throw ErrorHelper.CreateError(1081, rea.Name);
                };
            }

            Assembly api;
            try {
                api = universe.LoadFile(tmpass);
            } catch (Exception e) {
                if (Driver.Verbosity > 0)
                {
                    Console.WriteLine(e);
                }

                Console.Error.WriteLine("Error loading API definition from {0}", tmpass);
                return(1);
            }

            Assembly baselib;
            try {
                baselib = universe.LoadFile(baselibdll);
            } catch (Exception e) {
                if (Driver.Verbosity > 0)
                {
                    Console.WriteLine(e);
                }

                Console.Error.WriteLine("Error loading base library {0}", baselibdll);
                return(1);
            }

            AttributeManager = new AttributeManager(this);
            Frameworks       = new Frameworks(CurrentPlatform);

            Assembly corlib_assembly = universe.LoadFile(LocateAssembly("mscorlib"));
            // Explicitly load our attribute library so that IKVM doesn't try (and fail) to find it.
            universe.LoadFile(GetAttributeLibraryPath());

            TypeManager.Initialize(this, api, corlib_assembly, baselib);

            foreach (var linkWith in AttributeManager.GetCustomAttributes <LinkWithAttribute> (api))
            {
                if (!linkwith.Contains(linkWith.LibraryName))
                {
                    Console.Error.WriteLine("Missing native library {0}, please use `--link-with' to specify the path to this library.", linkWith.LibraryName);
                    return(1);
                }
            }

            foreach (var r in references)
            {
                // IKVM has a bug where it doesn't correctly compare assemblies, which means it
                // can end up loading the same assembly (in particular any System.Runtime whose
                // version > 4.0, but likely others as well) more than once. This is bad, because
                // we compare types based on reference equality, which breaks down when there are
                // multiple instances of the same type.
                //
                // So just don't ask IKVM to load assemblies that have already been loaded.
                var fn         = Path.GetFileNameWithoutExtension(r);
                var assemblies = universe.GetAssemblies();
                if (assemblies.Any((v) => v.GetName().Name == fn))
                {
                    continue;
                }

                if (File.Exists(r))
                {
                    try {
                        universe.LoadFile(r);
                    } catch (Exception ex) {
                        ErrorHelper.Warning(1104, r, ex.Message);
                    }
                }
            }

            var types = new List <Type> ();
            var strong_dictionaries = new List <Type> ();
            foreach (var t in api.GetTypes())
            {
                if ((process_enums && t.IsEnum) ||
                    AttributeManager.HasAttribute <BaseTypeAttribute> (t) ||
                    AttributeManager.HasAttribute <ProtocolAttribute> (t) ||
                    AttributeManager.HasAttribute <StaticAttribute> (t) ||
                    AttributeManager.HasAttribute <PartialAttribute> (t))
                {
                    types.Add(t);
                }
                if (AttributeManager.HasAttribute <StrongDictionaryAttribute> (t))
                {
                    strong_dictionaries.Add(t);
                }
            }

            var nsManager = new NamespaceManager(
                this,
                ns == null ? firstApiDefinitionName : ns,
                skipSystemDrawing
                );

            var g = new Generator(this, nsManager, public_mode, external, debug, types.ToArray(), strong_dictionaries.ToArray())
            {
                BaseDir         = basedir != null ? basedir : tmpdir,
                ZeroCopyStrings = zero_copy,
                InlineSelectors = inline_selectors ?? (CurrentPlatform != PlatformName.MacOSX),
            };

            g.Go();

            if (generate_file_list != null)
            {
                using (var f = File.CreateText(generate_file_list)){
                    foreach (var x in g.GeneratedFiles.OrderBy((v) => v))
                    {
                        f.WriteLine(x);
                    }
                }
                return(0);
            }

            cargs.Clear();
            if (unsafef)
            {
                cargs.Add("-unsafe");
            }
            cargs.Add("-target:library");
            cargs.Add("-out:" + outfile);
            foreach (var def in defines)
            {
                cargs.Add("-define:" + def);
            }
            cargs.AddRange(g.GeneratedFiles);
            cargs.AddRange(core_sources);
            cargs.AddRange(extra_sources);
            cargs.AddRange(refs);
            cargs.Add("-r:" + baselibdll);
            cargs.AddRange(resources);
            if (nostdlib)
            {
                cargs.Add("-nostdlib");
                cargs.Add("-noconfig");
            }
            if (!string.IsNullOrEmpty(Path.GetDirectoryName(baselibdll)))
            {
                cargs.Add("-lib:" + Path.GetDirectoryName(baselibdll));
            }

            if (Driver.RunCommand(compiler, cargs, null, out var generated_compile_output, true, Driver.Verbosity) != 0)
            {
                throw ErrorHelper.CreateError(1000, generated_compile_output.ToString().Replace("\n", "\n\t"));
            }
        } finally {
            if (delete_temp)
            {
                Directory.Delete(tmpdir, true);
            }
        }
        return(0);
    }
Beispiel #31
0
 /// <summary>
 /// Switches from the current camera view to a new view using a cinematic effect.
 /// </summary>
 /// <param name="name">The <see cref="Positionable{TCoordinates}.Name"/> of a <see cref="CameraState{TCoordinates}"/> stored in the <see cref="PresenterBase{TUniverse,TCoordinates}.Universe"/>.</param>
 public void SwingCameraTo(string name)
 {
     View.SwingCameraTo(CreateCamera(Universe.GetCamera(name)), duration: 4);
 }
Beispiel #32
0
 ///<summary>Initial constructor</summary>
 ///<param name="universe">The universe of this ear peduncle.</param>
 ///<param name="i">The index of this phytomer (= FinalLeafNumber + 1).</param>
 public EarPeduncle(Universe universe, int i, double cumulTTShoot, int roundedFinalNumber, double finalLeafNumber)
     : base(universe, i, cumulTTShoot)
 {
     InterNode_ = new InterNode(universe, roundedFinalNumber, isSmallPhytomer(finalLeafNumber, roundedFinalNumber), Index, PhytoNum);
 }
Beispiel #33
0
 ///<summary>Clone this ear peduncle</summary>
 ///<param name="universe"></param>
 ///<returns></returns>
 public override Phytomer Clone(Universe universe)
 {
     return(new EarPeduncle(universe, this));
 }
Beispiel #34
0
 /// <summary>
 /// Spawns a new entity
 /// </summary>
 /// <param name="location"></param>
 /// <param name="tile"></param>
 /// <param name="universe"></param>
 /// <returns></returns>
 public Entity Instance(Vector3I location, Tile tile, Universe universe)
 {
     return(BetterSignTileStateEntityBuilder.Spawn(universe, tile, location));
 }
Beispiel #35
0
        /// <summary>
        /// Applies universe selection the the data feed and algorithm
        /// </summary>
        /// <param name="universe">The universe to perform selection on</param>
        /// <param name="dateTimeUtc">The current date time in utc</param>
        /// <param name="universeData">The data provided to perform selection with</param>
        public SecurityChanges ApplyUniverseSelection(Universe universe, DateTime dateTimeUtc, BaseDataCollection universeData)
        {
            var algorithmEndDateUtc = _algorithm.EndDate.ConvertToUtc(_algorithm.TimeZone);

            if (dateTimeUtc > algorithmEndDateUtc)
            {
                return(SecurityChanges.None);
            }

            IEnumerable <Symbol> selectSymbolsResult;

            // check if this universe must be filtered with fine fundamental data
            var fineFiltered = universe as FineFundamentalFilteredUniverse;

            if (fineFiltered != null)
            {
                // perform initial filtering and limit the result
                selectSymbolsResult = universe.SelectSymbols(dateTimeUtc, universeData);

                if (!ReferenceEquals(selectSymbolsResult, Universe.Unchanged))
                {
                    // prepare a BaseDataCollection of FineFundamental instances
                    var fineCollection = new BaseDataCollection();

                    // Create a dictionary of CoarseFundamental keyed by Symbol that also has FineFundamental
                    // Coarse raw data has SID collision on: CRHCY R735QTJ8XC9X
                    var allCoarse  = universeData.Data.OfType <CoarseFundamental>();
                    var coarseData = allCoarse.Where(c => c.HasFundamentalData)
                                     .DistinctBy(c => c.Symbol)
                                     .ToDictionary(c => c.Symbol);

                    // Remove selected symbols that does not have fine fundamental data
                    var anyDoesNotHaveFundamentalData = false;
                    // only pre filter selected symbols if there actually is any coarse data. This way we can support custom universe filtered by fine fundamental data
                    // which do not use coarse data as underlying, in which case it could happen that we try to load fine fundamental data that is missing, but no problem,
                    // 'FineFundamentalSubscriptionEnumeratorFactory' won't emit it
                    if (allCoarse.Any())
                    {
                        selectSymbolsResult = selectSymbolsResult
                                              .Where(
                            symbol =>
                        {
                            var result = coarseData.ContainsKey(symbol);
                            anyDoesNotHaveFundamentalData |= !result;
                            return(result);
                        }
                            );
                    }

                    if (!_anyDoesNotHaveFundamentalDataWarningLogged && anyDoesNotHaveFundamentalData)
                    {
                        _algorithm.Debug("Note: Your coarse selection filter was updated to exclude symbols without fine fundamental data. Make sure your coarse filter excludes symbols where HasFundamental is false.");
                        _anyDoesNotHaveFundamentalDataWarningLogged = true;
                    }

                    // use all available threads, the entire system is waiting for this to complete
                    var options = new ParallelOptions {
                        MaxDegreeOfParallelism = Environment.ProcessorCount
                    };
                    Parallel.ForEach(selectSymbolsResult, options, symbol =>
                    {
                        var config   = FineFundamentalUniverse.CreateConfiguration(symbol);
                        var security = _securityService.CreateSecurity(symbol,
                                                                       config,
                                                                       addToSymbolCache: false);

                        var localStartTime = dateTimeUtc.ConvertFromUtc(config.ExchangeTimeZone).AddDays(-1);
                        var factory        = new FineFundamentalSubscriptionEnumeratorFactory(_algorithm.LiveMode, x => new[] { localStartTime });
                        var request        = new SubscriptionRequest(true, universe, security, new SubscriptionDataConfig(config), localStartTime, localStartTime);
                        using (var enumerator = factory.CreateEnumerator(request, _dataProvider))
                        {
                            if (enumerator.MoveNext())
                            {
                                lock (fineCollection.Data)
                                {
                                    fineCollection.Data.Add(enumerator.Current);
                                }
                            }
                        }
                    });

                    // WARNING -- HACK ATTACK -- WARNING
                    // Fine universes are considered special due to their chaining behavior.
                    // As such, we need a means of piping the fine data read in here back to the data feed
                    // so that it can be properly emitted via a TimeSlice.Create call. There isn't a mechanism
                    // in place for this function to return such data. The following lines are tightly coupled
                    // to the universeData dictionaries in SubscriptionSynchronizer and LiveTradingDataFeed and
                    // rely on reference semantics to work.

                    universeData.Data = new List <BaseData>();
                    foreach (var fine in fineCollection.Data.OfType <FineFundamental>())
                    {
                        var fundamentals = new Fundamentals
                        {
                            Symbol              = fine.Symbol,
                            Time                = fine.Time,
                            EndTime             = fine.EndTime,
                            DataType            = fine.DataType,
                            AssetClassification = fine.AssetClassification,
                            CompanyProfile      = fine.CompanyProfile,
                            CompanyReference    = fine.CompanyReference,
                            EarningReports      = fine.EarningReports,
                            EarningRatios       = fine.EarningRatios,
                            FinancialStatements = fine.FinancialStatements,
                            OperationRatios     = fine.OperationRatios,
                            SecurityReference   = fine.SecurityReference,
                            ValuationRatios     = fine.ValuationRatios,
                            Market              = fine.Symbol.ID.Market
                        };

                        CoarseFundamental coarse;
                        if (coarseData.TryGetValue(fine.Symbol, out coarse))
                        {
                            // the only time the coarse data won't exist is if the selection function
                            // doesn't use the data provided, and instead returns a constant list of
                            // symbols -- coupled with a potential hole in the data
                            fundamentals.Value              = coarse.Value;
                            fundamentals.Volume             = coarse.Volume;
                            fundamentals.DollarVolume       = coarse.DollarVolume;
                            fundamentals.HasFundamentalData = coarse.HasFundamentalData;

                            // set the fine fundamental price property to yesterday's closing price
                            fine.Value = coarse.Value;
                        }

                        universeData.Data.Add(fundamentals);
                    }

                    // END -- HACK ATTACK -- END

                    // perform the fine fundamental universe selection
                    selectSymbolsResult = fineFiltered.FineFundamentalUniverse.PerformSelection(dateTimeUtc, fineCollection);
                }
            }
            else
            {
                // perform initial filtering and limit the result
                selectSymbolsResult = universe.PerformSelection(dateTimeUtc, universeData);
            }

            // materialize the enumerable into a set for processing
            var selections = selectSymbolsResult.ToHashSet();

            var additions = new List <Security>();
            var removals  = new List <Security>();

            // first check for no pending removals, even if the universe selection
            // didn't change we might need to remove a security because a position was closed
            RemoveSecurityFromUniverse(
                _pendingRemovalsManager.CheckPendingRemovals(selections, universe),
                removals,
                dateTimeUtc,
                algorithmEndDateUtc);

            // check for no changes second
            if (ReferenceEquals(selectSymbolsResult, Universe.Unchanged))
            {
                return(SecurityChanges.None);
            }

            // determine which data subscriptions need to be removed from this universe
            foreach (var member in universe.Members.Values)
            {
                // if we've selected this subscription again, keep it
                if (selections.Contains(member.Symbol))
                {
                    continue;
                }

                // don't remove if the universe wants to keep him in
                if (!universe.CanRemoveMember(dateTimeUtc, member))
                {
                    continue;
                }

                // remove the member - this marks this member as not being
                // selected by the universe, but it may remain in the universe
                // until open orders are closed and the security is liquidated
                removals.Add(member);

                RemoveSecurityFromUniverse(_pendingRemovalsManager.TryRemoveMember(member, universe),
                                           removals,
                                           dateTimeUtc,
                                           algorithmEndDateUtc);
            }

            var keys = _pendingSecurityAdditions.Keys;

            if (keys.Any() && keys.Single() != dateTimeUtc)
            {
                // if the frontier moved forward then we've added these securities to the algorithm
                _pendingSecurityAdditions.Clear();
            }

            Dictionary <Symbol, Security> pendingAdditions;

            if (!_pendingSecurityAdditions.TryGetValue(dateTimeUtc, out pendingAdditions))
            {
                // keep track of created securities so we don't create the same security twice, leads to bad things :)
                pendingAdditions = new Dictionary <Symbol, Security>();
                _pendingSecurityAdditions[dateTimeUtc] = pendingAdditions;
            }

            // find new selections and add them to the algorithm
            foreach (var symbol in selections)
            {
                if (universe.Securities.ContainsKey(symbol))
                {
                    // if its already part of the universe no need to re add it
                    continue;
                }

                // create the new security, the algorithm thread will add this at the appropriate time
                Security security;
                if (!pendingAdditions.TryGetValue(symbol, out security) && !_algorithm.Securities.TryGetValue(symbol, out security))
                {
                    // For now this is required for retro compatibility with usages of security.Subscriptions
                    var configs = _algorithm.SubscriptionManager.SubscriptionDataConfigService.Add(symbol,
                                                                                                   universe.UniverseSettings.Resolution,
                                                                                                   universe.UniverseSettings.FillForward,
                                                                                                   universe.UniverseSettings.ExtendedMarketHours,
                                                                                                   dataNormalizationMode: universe.UniverseSettings.DataNormalizationMode);

                    security = _securityService.CreateSecurity(symbol, configs, universe.UniverseSettings.Leverage, symbol.ID.SecurityType == SecurityType.Option);

                    pendingAdditions.Add(symbol, security);

                    SetUnderlyingSecurity(universe, security);
                }

                var addedSubscription = false;

                foreach (var request in universe.GetSubscriptionRequests(security, dateTimeUtc, algorithmEndDateUtc,
                                                                         _algorithm.SubscriptionManager.SubscriptionDataConfigService))
                {
                    if (security.Symbol == request.Configuration.Symbol && // Just in case check its the same symbol, else AddData will throw.
                        !security.Subscriptions.Contains(request.Configuration))
                    {
                        // For now this is required for retro compatibility with usages of security.Subscriptions
                        security.AddData(request.Configuration);
                    }

                    var toRemove = _currencySubscriptionDataConfigManager.GetSubscriptionDataConfigToRemove(request.Configuration.Symbol);
                    if (toRemove != null)
                    {
                        Log.Trace($"UniverseSelection.ApplyUniverseSelection(): Removing internal currency data feed {toRemove}");
                        _dataManager.RemoveSubscription(toRemove);
                    }

                    _dataManager.AddSubscription(request);

                    // only update our security changes if we actually added data
                    if (!request.IsUniverseSubscription)
                    {
                        addedSubscription = true;

                        _internalSubscriptionManager.AddedSubscriptionRequest(request);
                    }
                }

                if (addedSubscription)
                {
                    var addedMember = universe.AddMember(dateTimeUtc, security);

                    if (addedMember)
                    {
                        additions.Add(security);
                    }
                }
            }

            // return None if there's no changes, otherwise return what we've modified
            var securityChanges = additions.Count + removals.Count != 0
                ? new SecurityChanges(additions, removals)
                : SecurityChanges.None;

            // Add currency data feeds that weren't explicitly added in Initialize
            if (additions.Count > 0)
            {
                EnsureCurrencyDataFeeds(securityChanges);
            }

            if (securityChanges != SecurityChanges.None && Log.DebuggingEnabled)
            {
                // for performance lets not create the message string if debugging is not enabled
                // this can be executed many times and its in the algorithm thread
                Log.Debug("UniverseSelection.ApplyUniverseSelection(): " + dateTimeUtc + ": " + securityChanges);
            }

            return(securityChanges);
        }
Beispiel #36
0
    static int Main2(string [] args)
    {
        bool          show_help = false;
        bool          zero_copy = false;
        string        basedir = null;
        string        tmpdir = null;
        string        ns = null;
        string        outfile = null;
        bool          delete_temp = true, debug = false;
        bool          verbose          = false;
        bool          unsafef          = true;
        bool          external         = false;
        bool          public_mode      = true;
        bool          nostdlib         = false;
        bool?         inline_selectors = null;
        List <string> sources;
        var           resources          = new List <string> ();
        var           linkwith           = new List <string> ();
        var           references         = new List <string> ();
        var           api_sources        = new List <string> ();
        var           core_sources       = new List <string> ();
        var           extra_sources      = new List <string> ();
        var           defines            = new List <string> ();
        string        generate_file_list = null;
        bool          process_enums      = false;

        var os = new OptionSet()
        {
            { "h|?|help", "Displays the help", v => show_help = true },
            { "a", "Include alpha bindings (Obsolete).", v => {}, true },
            { "outdir=", "Sets the output directory for the temporary binding files", v => { basedir = v; } },
            { "o|out=", "Sets the name of the output library", v => outfile = v },
            { "tmpdir=", "Sets the working directory for temp files", v => { tmpdir = v; delete_temp = false; } },
            { "debug", "Generates a debugging build of the binding", v => debug = true },
            { "sourceonly=", "Only generates the source", v => generate_file_list = v },
            { "ns=", "Sets the namespace for storing helper classes", v => ns = v },
            { "unsafe", "Sets the unsafe flag for the build", v => unsafef = true },
            { "core", "Use this to build product assemblies", v => Generator.BindThirdPartyLibrary = false },
            { "r=", "Adds a reference", v => references.Add(v) },
            { "lib=", "Adds the directory to the search path for the compiler", v => libs.Add(StringUtils.Quote(v)) },
            { "compiler=", "Sets the compiler to use", v => compiler = v },
            { "sdk=", "Sets the .NET SDK to use", v => net_sdk = v },
            { "new-style", "Build for Unified (Obsolete).", v => { Console.WriteLine("The --new-style option is obsolete and ignored."); }, true },
            { "d=", "Defines a symbol", v => defines.Add(v) },
            { "api=", "Adds a API definition source file", v => api_sources.Add(StringUtils.Quote(v)) },
            { "s=", "Adds a source file required to build the API", v => core_sources.Add(StringUtils.Quote(v)) },
            { "v", "Sets verbose mode", v => verbose = true },
            { "x=", "Adds the specified file to the build, used after the core files are compiled", v => extra_sources.Add(StringUtils.Quote(v)) },
            { "e", "Generates smaller classes that can not be subclassed (previously called 'external mode')", v => external = true },
            { "p", "Sets private mode", v => public_mode = false },
            { "baselib=", "Sets the base library", v => baselibdll = v },
            { "attributelib=", "Sets the attribute library", v => attributedll = v },
            { "use-zero-copy", v => zero_copy = true },
            { "nostdlib", "Does not reference mscorlib.dll library", l => nostdlib = true },
            { "no-mono-path", "Launches compiler with empty MONO_PATH", l => { } },
            { "native-exception-marshalling", "Enable the marshalling support for Objective-C exceptions", (v) => { /* no-op */ } },
            { "inline-selectors:", "If Selector.GetHandle is inlined and does not need to be cached (enabled by default in Xamarin.iOS, disabled in Xamarin.Mac)",
              v => inline_selectors = string.Equals("true", v, StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(v) },
            { "process-enums", "Process enums as bindings, not external, types.", v => process_enums = true },
            { "link-with=,", "Link with a native library {0:FILE} to the binding, embedded as a resource named {1:ID}",
              (path, id) => {
                  if (path == null || path.Length == 0)
                  {
                      throw new Exception("-link-with=FILE,ID requires a filename.");
                  }

                  if (id == null || id.Length == 0)
                  {
                      id = Path.GetFileName(path);
                  }

                  if (linkwith.Contains(id))
                  {
                      throw new Exception("-link-with=FILE,ID cannot assign the same resource id to multiple libraries.");
                  }

                  resources.Add(string.Format("-res:{0},{1}", path, id));
                  linkwith.Add(id);
              } },
            { "unified-full-profile", "Launches compiler pointing to XM Full Profile", l => { /* no-op*/ }, true },
            { "unified-mobile-profile", "Launches compiler pointing to XM Mobile Profile", l => { /* no-op*/ }, true },
            { "target-framework=", "Specify target framework to use. Always required, and the currently supported values are: 'MonoTouch,v1.0', 'Xamarin.iOS,v1.0', 'Xamarin.TVOS,v1.0', 'Xamarin.WatchOS,v1.0', 'XamMac,v1.0', 'Xamarin.Mac,Version=v2.0,Profile=Mobile', 'Xamarin.Mac,Version=v4.5,Profile=Full' and 'Xamarin.Mac,Version=v4.5,Profile=System')", v => SetTargetFramework(v) },
            { "warnaserror:", "An optional comma-separated list of warning codes that should be reported as errors (if no warnings are specified all warnings are reported as errors).", v => {
                  try {
                      if (!string.IsNullOrEmpty(v))
                      {
                          foreach (var code in v.Split(new char [] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                          {
                              ErrorHelper.SetWarningLevel(ErrorHelper.WarningLevel.Error, int.Parse(code));
                          }
                      }
                      else
                      {
                          ErrorHelper.SetWarningLevel(ErrorHelper.WarningLevel.Error);
                      }
                  } catch (Exception ex) {
                      throw ErrorHelper.CreateError(26, $"Could not parse the command line argument '--warnaserror': {ex.Message}");
                  }
              } },
            { "nowarn:", "An optional comma-separated list of warning codes to ignore (if no warnings are specified all warnings are ignored).", v => {
                  try {
                      if (!string.IsNullOrEmpty(v))
                      {
                          foreach (var code in v.Split(new char [] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                          {
                              ErrorHelper.SetWarningLevel(ErrorHelper.WarningLevel.Disable, int.Parse(code));
                          }
                      }
                      else
                      {
                          ErrorHelper.SetWarningLevel(ErrorHelper.WarningLevel.Disable);
                      }
                  } catch (Exception ex) {
                      throw ErrorHelper.CreateError(26, $"Could not parse the command line argument '--nowarn': {ex.Message}");
                  }
              } },
            new Mono.Options.ResponseFileSource(),
        };

        try {
            sources = os.Parse(args);
        } catch (Exception e) {
            Console.Error.WriteLine("{0}: {1}", ToolName, e.Message);
            Console.Error.WriteLine("see {0} --help for more information", ToolName);
            return(1);
        }

        if (show_help)
        {
            ShowHelp(os);
            return(0);
        }

        if (!target_framework.HasValue)
        {
            throw ErrorHelper.CreateError(86, "A target framework (--target-framework) must be specified.");
        }

        switch (target_framework.Value.Identifier.ToLowerInvariant())
        {
        case "monotouch":
            CurrentPlatform = PlatformName.iOS;
            Unified         = false;
            if (string.IsNullOrEmpty(baselibdll))
            {
                baselibdll = Path.Combine(GetSDKRoot(), "lib/mono/2.1/monotouch.dll");
            }
            Path.Combine(GetSDKRoot(), "bin/smcs");
            break;

        case "xamarin.ios":
            CurrentPlatform = PlatformName.iOS;
            Unified         = true;
            if (string.IsNullOrEmpty(baselibdll))
            {
                baselibdll = Path.Combine(GetSDKRoot(), "lib/mono/Xamarin.iOS/Xamarin.iOS.dll");
            }
            break;

        case "xamarin.tvos":
            CurrentPlatform = PlatformName.TvOS;
            Unified         = true;
            if (string.IsNullOrEmpty(baselibdll))
            {
                baselibdll = Path.Combine(GetSDKRoot(), "lib/mono/Xamarin.TVOS/Xamarin.TVOS.dll");
            }
            break;

        case "xamarin.watchos":
            CurrentPlatform = PlatformName.WatchOS;
            Unified         = true;
            if (string.IsNullOrEmpty(baselibdll))
            {
                baselibdll = Path.Combine(GetSDKRoot(), "lib/mono/Xamarin.WatchOS/Xamarin.WatchOS.dll");
            }
            break;

        case "xammac":
            CurrentPlatform = PlatformName.MacOSX;
            Unified         = false;
            if (string.IsNullOrEmpty(baselibdll))
            {
                baselibdll = Path.Combine(GetSDKRoot(), "lib", "mono", "XamMac.dll");
            }
            net_sdk = "4";
            break;

        case "xamarin.mac":
            CurrentPlatform   = PlatformName.MacOSX;
            Unified           = true;
            skipSystemDrawing = target_framework == TargetFramework.Xamarin_Mac_4_5_Full;
            if (string.IsNullOrEmpty(baselibdll))
            {
                if (target_framework == TargetFramework.Xamarin_Mac_2_0_Mobile)
                {
                    baselibdll = Path.Combine(GetSDKRoot(), "lib", "reference", "mobile", "Xamarin.Mac.dll");
                }
                else
                {
                    baselibdll = Path.Combine(GetSDKRoot(), "lib", "reference", "full", "Xamarin.Mac.dll");
                }
            }
            net_sdk = "4";
            break;

        default:
            throw ErrorHelper.CreateError(1043, "Internal error: unknown target framework '{0}'.", target_framework);
        }

        if (string.IsNullOrEmpty(compiler))
        {
            compiler = "/Library/Frameworks/Mono.framework/Commands/mcs";
        }

        if (target_framework == TargetFramework.XamMac_1_0 && !references.Any((v) => Path.GetFileNameWithoutExtension(v) == "System.Drawing"))
        {
            // If we're targeting XM/Classic ensure we have a reference to System.Drawing.dll.
            references.Add("/Library/Frameworks/Mono.framework/Versions/Current/lib/mono/4.5/System.Drawing.dll");
        }

        if (sources.Count > 0)
        {
            api_sources.Insert(0, StringUtils.Quote(sources [0]));
            for (int i = 1; i < sources.Count; i++)
            {
                core_sources.Insert(i - 1, StringUtils.Quote(sources [i]));
            }
        }

        if (api_sources.Count == 0)
        {
            Console.WriteLine("Error: no api file provided");
            ShowHelp(os);
            return(1);
        }

        if (tmpdir == null)
        {
            tmpdir = GetWorkDir();
        }

        string firstApiDefinitionName = Path.GetFileNameWithoutExtension(StringUtils.Unquote(api_sources [0]));

        firstApiDefinitionName = firstApiDefinitionName.Replace('-', '_');          // This is not exhaustive, but common.
        if (outfile == null)
        {
            outfile = firstApiDefinitionName + ".dll";
        }

        string refs = string.Empty;

        foreach (var r in references)
        {
            if (refs != string.Empty)
            {
                refs += " ";
            }
            refs += "-r:" + StringUtils.Quote(r);
        }
        string paths = (libs.Count > 0 ? "-lib:" + String.Join(" -lib:", libs.ToArray()) : "");

        try {
            var tmpass = Path.Combine(tmpdir, "temp.dll");

            // -nowarn:436 is to avoid conflicts in definitions between core.dll and the sources
            // Keep source files at the end of the command line - csc will create TWO assemblies if any sources preceed the -out parameter
            var cargs = new StringBuilder();

            if (CurrentPlatform == PlatformName.MacOSX)
            {
                // HACK
                bool isCSC = compiler.Contains("/Library/Frameworks/Mono.framework/Versions/Current/bin/csc");
                if (!isCSC && !string.IsNullOrEmpty(net_sdk) && net_sdk != "mobile")
                {
                    cargs.Append("-sdk:").Append(net_sdk).Append(' ');
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(net_sdk))
                {
                    cargs.Append("-sdk:").Append(net_sdk).Append(' ');
                }
            }
            cargs.Append("-debug -unsafe -target:library -nowarn:436").Append(' ');
            cargs.Append("-out:").Append(StringUtils.Quote(tmpass)).Append(' ');
            cargs.Append("-r:").Append(StringUtils.Quote(GetAttributeLibraryPath())).Append(' ');
            cargs.Append(refs).Append(' ');
            if (unsafef)
            {
                cargs.Append("-unsafe ");
            }
            cargs.Append("-r:").Append(StringUtils.Quote(baselibdll)).Append(' ');
            foreach (var def in defines)
            {
                cargs.Append("-define:").Append(def).Append(' ');
            }
            cargs.Append(paths).Append(' ');
            if (nostdlib)
            {
                cargs.Append("-nostdlib ");
            }
            foreach (var qs in api_sources)
            {
                cargs.Append(qs).Append(' ');
            }
            foreach (var cs in core_sources)
            {
                cargs.Append(cs).Append(' ');
            }
            if (!string.IsNullOrEmpty(Path.GetDirectoryName(baselibdll)))
            {
                cargs.Append("-lib:").Append(Path.GetDirectoryName(baselibdll)).Append(' ');
            }


            var si = new ProcessStartInfo(compiler, cargs.ToString())
            {
                UseShellExecute = false,
            };

            // HACK: We are calling btouch with forced 2.1 path but we need working mono for compiler
            si.EnvironmentVariables.Remove("MONO_PATH");

            if (verbose)
            {
                Console.WriteLine("{0} {1}", si.FileName, si.Arguments);
            }

            var p = Process.Start(si);
            p.WaitForExit();
            if (p.ExitCode != 0)
            {
                Console.WriteLine("{0}: API binding contains errors.", ToolName);
                return(1);
            }

            universe = new Universe(UniverseOptions.EnableFunctionPointers | UniverseOptions.ResolveMissingMembers | UniverseOptions.MetadataOnly);

            Assembly api;
            try {
                api = universe.LoadFile(tmpass);
            } catch (Exception e) {
                if (verbose)
                {
                    Console.WriteLine(e);
                }

                Console.Error.WriteLine("Error loading API definition from {0}", tmpass);
                return(1);
            }

            Assembly baselib;
            try {
                baselib = universe.LoadFile(baselibdll);
            } catch (Exception e) {
                if (verbose)
                {
                    Console.WriteLine(e);
                }

                Console.Error.WriteLine("Error loading base library {0}", baselibdll);
                return(1);
            }

            Assembly corlib_assembly   = universe.LoadFile(LocateAssembly("mscorlib"));
            Assembly platform_assembly = baselib;
            Assembly system_assembly   = universe.LoadFile(LocateAssembly("System"));
            Assembly binding_assembly  = universe.LoadFile(GetAttributeLibraryPath());
            TypeManager.Initialize(api, corlib_assembly, platform_assembly, system_assembly, binding_assembly);

            foreach (var linkWith in AttributeManager.GetCustomAttributes <LinkWithAttribute> (api))
            {
                if (!linkwith.Contains(linkWith.LibraryName))
                {
                    Console.Error.WriteLine("Missing native library {0}, please use `--link-with' to specify the path to this library.", linkWith.LibraryName);
                    return(1);
                }
            }

            foreach (var r in references)
            {
                if (File.Exists(r))
                {
                    try {
                        universe.LoadFile(r);
                    } catch (Exception ex) {
                        ErrorHelper.Show(new BindingException(1104, false, "Could not load the referenced library '{0}': {1}.", r, ex.Message));
                    }
                }
            }

            var types = new List <Type> ();
            var strong_dictionaries = new List <Type> ();
            foreach (var t in api.GetTypes())
            {
                if ((process_enums && t.IsEnum) ||
                    AttributeManager.HasAttribute <BaseTypeAttribute> (t) ||
                    AttributeManager.HasAttribute <ProtocolAttribute> (t) ||
                    AttributeManager.HasAttribute <StaticAttribute> (t) ||
                    AttributeManager.HasAttribute <PartialAttribute> (t))
                {
                    types.Add(t);
                }
                if (AttributeManager.HasAttribute <StrongDictionaryAttribute> (t))
                {
                    strong_dictionaries.Add(t);
                }
            }

            var nsManager = new NamespaceManager(
                NamespacePlatformPrefix,
                ns == null ? firstApiDefinitionName : ns,
                skipSystemDrawing
                );

            var g = new Generator(nsManager, public_mode, external, debug, types.ToArray(), strong_dictionaries.ToArray())
            {
                BaseDir         = basedir != null ? basedir : tmpdir,
                ZeroCopyStrings = zero_copy,
                InlineSelectors = inline_selectors ?? (Unified && CurrentPlatform != PlatformName.MacOSX),
            };

            if (!Unified && !Generator.BindThirdPartyLibrary)
            {
                foreach (var mi in baselib.GetType(nsManager.CoreObjCRuntime + ".Messaging").GetMethods())
                {
                    if (mi.Name.IndexOf("_objc_msgSend", StringComparison.Ordinal) != -1)
                    {
                        g.RegisterMethodName(mi.Name);
                    }
                }
            }

            g.Go();

            if (generate_file_list != null)
            {
                using (var f = File.CreateText(generate_file_list)){
                    foreach (var x in g.GeneratedFiles.OrderBy((v) => v))
                    {
                        f.WriteLine(x);
                    }
                }
                return(0);
            }

            cargs.Clear();
            if (unsafef)
            {
                cargs.Append("-unsafe ");
            }
            cargs.Append("-target:library ");
            cargs.Append("-out:").Append(StringUtils.Quote(outfile)).Append(' ');
            foreach (var def in defines)
            {
                cargs.Append("-define:").Append(def).Append(' ');
            }
            foreach (var gf in g.GeneratedFiles)
            {
                cargs.Append(gf).Append(' ');
            }
            foreach (var cs in core_sources)
            {
                cargs.Append(cs).Append(' ');
            }
            foreach (var es in extra_sources)
            {
                cargs.Append(es).Append(' ');
            }
            cargs.Append(refs).Append(' ');
            cargs.Append("-r:").Append(StringUtils.Quote(baselibdll)).Append(' ');
            foreach (var res in resources)
            {
                cargs.Append(res).Append(' ');
            }
            if (nostdlib)
            {
                cargs.Append("-nostdlib ");
            }
            if (!string.IsNullOrEmpty(Path.GetDirectoryName(baselibdll)))
            {
                cargs.Append("-lib:").Append(Path.GetDirectoryName(baselibdll)).Append(' ');
            }

            si = new ProcessStartInfo(compiler, cargs.ToString())
            {
                UseShellExecute = false,
            };

            // HACK: We are calling btouch with forced 2.1 path but we need working mono for compiler
            si.EnvironmentVariables.Remove("MONO_PATH");

            if (verbose)
            {
                Console.WriteLine("{0} {1}", si.FileName, si.Arguments);
            }

            p = Process.Start(si);
            p.WaitForExit();
            if (p.ExitCode != 0)
            {
                Console.WriteLine("{0}: API binding contains errors.", ToolName);
                return(1);
            }
        } finally {
            if (delete_temp)
            {
                Directory.Delete(tmpdir, true);
            }
        }
        return(0);
    }
Beispiel #37
0
 public MessageBoxSteps(Universe universe)
 {
     _universe = universe;
 }
Beispiel #38
0
        public override void SetUp()
        {
            universe = new Universe();

            base.SetUp();
        }
Beispiel #39
0
 /// <summary>
 /// Converts a string consisting of characters of the Universe's alphabet to an equivalent number (base conversion).
 /// </summary>
 public static BigInteger TextToNumber(string text, string alphabet)
 {
     return(Universe.ArbitraryToDecimalSystem(text, alphabet));
 }
Beispiel #40
0
        /// <summary>
        /// Applies universe selection the the data feed and algorithm
        /// </summary>
        /// <param name="universe">The universe to perform selection on</param>
        /// <param name="dateTimeUtc">The current date time in utc</param>
        /// <param name="universeData">The data provided to perform selection with</param>
        public SecurityChanges ApplyUniverseSelection(Universe universe, DateTime dateTimeUtc, BaseDataCollection universeData)
        {
            IEnumerable <Symbol> selectSymbolsResult;

            // check if this universe must be filtered with fine fundamental data
            var fineFiltered = universe as FineFundamentalFilteredUniverse;

            if (fineFiltered != null)
            {
                // perform initial filtering and limit the result
                selectSymbolsResult = universe.SelectSymbols(dateTimeUtc, universeData);

                // prepare a BaseDataCollection of FineFundamental instances
                var fineCollection   = new BaseDataCollection();
                var dataFileProvider = new DefaultDataFileProvider();

                foreach (var symbol in selectSymbolsResult)
                {
                    var factory = new FineFundamentalSubscriptionEnumeratorFactory(_algorithm.LiveMode, x => new[] { dateTimeUtc });
                    var config  = FineFundamentalUniverse.CreateConfiguration(symbol);

                    Security security;
                    if (!_algorithm.Securities.TryGetValue(symbol, out security))
                    {
                        security = universe.CreateSecurity(symbol, _algorithm, _marketHoursDatabase, _symbolPropertiesDatabase);
                        _algorithm.Securities.Add(security);
                    }

                    var request    = new SubscriptionRequest(true, universe, security, config, dateTimeUtc, dateTimeUtc);
                    var enumerator = factory.CreateEnumerator(request, dataFileProvider);
                    if (enumerator.MoveNext())
                    {
                        fineCollection.Data.Add(enumerator.Current);
                    }
                }

                // perform the fine fundamental universe selection
                selectSymbolsResult = fineFiltered.FineFundamentalUniverse.PerformSelection(dateTimeUtc, fineCollection);
            }
            else
            {
                // perform initial filtering and limit the result
                selectSymbolsResult = universe.PerformSelection(dateTimeUtc, universeData);
            }

            // check for no changes first
            if (ReferenceEquals(selectSymbolsResult, Universe.Unchanged))
            {
                return(SecurityChanges.None);
            }

            // materialize the enumerable into a set for processing
            var selections = selectSymbolsResult.ToHashSet();

            var additions           = new List <Security>();
            var removals            = new List <Security>();
            var algorithmEndDateUtc = _algorithm.EndDate.ConvertToUtc(_algorithm.TimeZone);

            // remove previously deselected members which were kept in the universe because of holdings or open orders
            foreach (var member in _pendingRemovals.ToList())
            {
                var openOrders = _algorithm.Transactions.GetOrders(x => x.Status.IsOpen() && x.Symbol == member.Symbol);
                if (!member.HoldStock && !openOrders.Any())
                {
                    RemoveSecurityFromUniverse(universe, member, removals, dateTimeUtc, algorithmEndDateUtc);

                    _pendingRemovals.Remove(member);
                }
            }

            // determine which data subscriptions need to be removed from this universe
            foreach (var member in universe.Members.Values)
            {
                // if we've selected this subscription again, keep it
                if (selections.Contains(member.Symbol))
                {
                    continue;
                }

                // don't remove if the universe wants to keep him in
                if (!universe.CanRemoveMember(dateTimeUtc, member))
                {
                    continue;
                }

                // remove the member - this marks this member as not being
                // selected by the universe, but it may remain in the universe
                // until open orders are closed and the security is liquidated
                removals.Add(member);

                // but don't physically remove it from the algorithm if we hold stock or have open orders against it
                var openOrders = _algorithm.Transactions.GetOrders(x => x.Status.IsOpen() && x.Symbol == member.Symbol);
                if (!member.HoldStock && !openOrders.Any())
                {
                    RemoveSecurityFromUniverse(universe, member, removals, dateTimeUtc, algorithmEndDateUtc);
                }
                else
                {
                    _pendingRemovals.Add(member);
                }
            }

            // find new selections and add them to the algorithm
            foreach (var symbol in selections)
            {
                // create the new security, the algorithm thread will add this at the appropriate time
                Security security;
                if (!_algorithm.Securities.TryGetValue(symbol, out security))
                {
                    security = universe.CreateSecurity(symbol, _algorithm, _marketHoursDatabase, _symbolPropertiesDatabase);
                }

                var addedSubscription = false;

                foreach (var request in universe.GetSubscriptionRequests(security, dateTimeUtc, algorithmEndDateUtc))
                {
                    // ask the limiter if we can add another subscription at that resolution
                    string reason;
                    if (!_limiter.CanAddSubscription(request.Configuration.Resolution, out reason))
                    {
                        // should we be counting universe subscriptions against user subscriptions limits?

                        _algorithm.Error(reason);
                        Log.Trace("UniverseSelection.ApplyUniverseSelection(): Skipping adding subscription: " + request.Configuration.Symbol.ToString() + ": " + reason);
                        continue;
                    }
                    // add the new subscriptions to the data feed
                    _dataFeed.AddSubscription(request);

                    // only update our security changes if we actually added data
                    if (!request.IsUniverseSubscription)
                    {
                        addedSubscription = true;
                    }
                }

                if (addedSubscription)
                {
                    var addedMember = universe.AddMember(dateTimeUtc, security);

                    if (addedMember)
                    {
                        additions.Add(security);
                    }
                }
            }

            // Add currency data feeds that weren't explicitly added in Initialize
            if (additions.Count > 0)
            {
                var addedSecurities = _algorithm.Portfolio.CashBook.EnsureCurrencyDataFeeds(_algorithm.Securities, _algorithm.SubscriptionManager, _marketHoursDatabase, _symbolPropertiesDatabase, _algorithm.BrokerageModel.DefaultMarkets);
                foreach (var security in addedSecurities)
                {
                    // assume currency feeds are always one subscription per, these are typically quote subscriptions
                    _dataFeed.AddSubscription(new SubscriptionRequest(false, universe, security, security.Subscriptions.First(), dateTimeUtc, algorithmEndDateUtc));
                }
            }

            // return None if there's no changes, otherwise return what we've modified
            var securityChanges = additions.Count + removals.Count != 0
                ? new SecurityChanges(additions, removals)
                : SecurityChanges.None;

            if (securityChanges != SecurityChanges.None)
            {
                Log.Debug("UniverseSelection.ApplyUniverseSelection(): " + dateTimeUtc + ": " + securityChanges);
            }

            return(securityChanges);
        }
    private static bool MakeSweetestMoves(Universe uni, IEnumerable<AttackPlan> attackPlan)
    {
        bool attackPerformed = false;
        Planet Defender = null;
        Planet agressor = null;
        foreach (var attack in attackPlan)
        {
            agressor = attack.Source;
            if (agressor.PlanetID == 2)
            {
            }
            if (agressor.AttackMovesAllowed)
            {
                if ((agressor.AttackForce >= attack.ShipCount && agressor.CanSurviveIncommingAttack) || agressor.IsLost)
                {
                    Defender = attack.Target;
                    bool domination = Universe.IsDominating || attack.DominationMove;
                    if (Defender.IsAttackable || domination)
                    {
                        //create bias towards planets for which we initiate battle
                        Universe.AddToWishList(Defender);

                        uni.MakeMove(agressor, Defender, attack.ShipCount);
                        attackPerformed = true;
                    }
                }
            }
        }
        return attackPerformed;
    }
Beispiel #42
0
 public void Setup()
 {
     _universe = new Universe();
 }
 public UniverseState(Universe universe, TransitionState transitionState)
 {
     this.universe        = universe;
     this.transitionState = transitionState;
 }
 /// <summary>
 /// Creates a new SteamId with the specified account Id, universe, account type, and instance Id
 /// </summary>
 /// <param name="accountId"></param>
 /// <param name="universe"></param>
 /// <param name="type"></param>
 /// <param name="instance"></param>
 public SteamId(long accountId, Universe universe = Universe.Public, AccountType type = AccountType.Individual, long instance = 1)
     : this(accountId > uint.MaxValue || accountId < uint.MinValue ? throw new ArgumentOutOfRangeException(nameof(accountId)) : (uint)accountId, universe, type, instance <uint.MinValue || instance> uint.MaxValue ? throw new ArgumentOutOfRangeException(nameof(instance)) : (uint)instance)
Beispiel #45
0
 ///Constructor.
 public ExposedSheath(Universe universe)
     : base(universe)
 {
     TTSinceSen = 0.0;
 }
Beispiel #46
0
 public TestPlugin(Client client)
 {
     _protocol = new ClientProtocol(client);
     universe  = new Universe();
 }
Beispiel #47
0
        public static void Main()
        {
            try
            {
                ServerContext.StartTime = DateTime.UtcNow.Ticks;

                //Start the server clock
                ServerContext.ServerClock.Start();

                //Set the last player activity time to server start
                ServerContext.LastPlayerActivity = ServerContext.ServerClock.ElapsedMilliseconds;

                //Register the ctrl+c event
                Console.CancelKeyPress      += CatchExit;
                ServerContext.ServerStarting = true;

                LunaLog.Debug("Loading settings...");
                if (GeneralSettings.SettingsStore.GameDifficulty == GameDifficulty.CUSTOM)
                {
                    GameplaySettings.Reset();
                    GameplaySettings.Load();
                }

                //Set day for log change
                ServerContext.Day = DateTime.Now.Day;

                //Load plugins
                LmpPluginHandler.LoadPlugins();

                Console.Title = "LMPServer v" + VersionInfo.VersionNumber;

                while (ServerContext.ServerStarting || ServerContext.ServerRestarting)
                {
                    if (ServerContext.ServerRestarting)
                    {
                        LunaLog.Debug("Reloading settings...");
                        GeneralSettings.Reset();
                        GeneralSettings.Load();
                        if (GeneralSettings.SettingsStore.GameDifficulty == GameDifficulty.CUSTOM)
                        {
                            LunaLog.Debug("Reloading gameplay settings...");
                            GameplaySettings.Reset();
                            GameplaySettings.Load();
                        }
                    }

                    ServerContext.ServerRestarting = false;
                    LunaLog.Normal("Starting Luna Server v" + VersionInfo.FullVersionNumber);

                    if (GeneralSettings.SettingsStore.GameDifficulty == GameDifficulty.CUSTOM)
                    {
                        //Generate the config file by accessing the object.
                        LunaLog.Debug("Loading gameplay settings...");
                        GameplaySettings.Load();
                    }

                    //Load universe
                    LunaLog.Normal("Loading universe... ");
                    Universe.CheckUniverse();

                    LunaLog.Normal("Starting " + GeneralSettings.SettingsStore.WarpMode + " server on Port " +
                                   GeneralSettings.SettingsStore.Port + "... ");

                    ServerContext.ServerRunning = true;

                    var commandThread = Task.Run(() => new CommandHandler().ThreadMain());
                    var clientThread  = Task.Run(() => new ClientMainThread().ThreadMain());

                    ServerContext.LidgrenServer.SetupLidgrenServer();
                    Task.Run(() => ServerContext.LidgrenServer.StartReceiveingMessages());
                    Task.Run(() => ServerContext.LidgrenServer.RegisterWithMasterServer());

                    var vesselRelayThread = Task.Run(() => VesselRelaySystem.RelayOldVesselMessages());

                    var vesselRelayFarThread    = Task.Run(() => VesselUpdateRelaySystem.RelayToFarPlayers());
                    var vesselRelayMediumThread = Task.Run(() => VesselUpdateRelaySystem.RelayToMediumDistancePlayers());
                    var vesselRelayCloseThread  = Task.Run(() => VesselUpdateRelaySystem.RelayToClosePlayers());

                    while (ServerContext.ServerStarting)
                    {
                        Thread.Sleep(500);
                    }

                    LunaLog.Normal("Ready!");
                    LmpPluginHandler.FireOnServerStart();
                    while (ServerContext.ServerRunning)
                    {
                        //Run the log expire function every 10 minutes
                        if (ServerContext.ServerClock.ElapsedMilliseconds - _lastLogExpiredCheck > 600000)
                        {
                            _lastLogExpiredCheck = ServerContext.ServerClock.ElapsedMilliseconds;
                            LogExpire.ExpireLogs();
                        }

                        // Check if the day has changed, every minute
                        if (ServerContext.ServerClock.ElapsedMilliseconds - _lastDayCheck > 60000)
                        {
                            _lastDayCheck = ServerContext.ServerClock.ElapsedMilliseconds;
                            if (ServerContext.Day != DateTime.Now.Day)
                            {
                                LunaLog.LogFilename = Path.Combine(LunaLog.LogFolder, $"lmpserver {DateTime.Now:yyyy-MM-dd HH-mm-ss}.log");
                                LunaLog.WriteToLog($"Continued from logfile {DateTime.Now:yyyy-MM-dd HH-mm-ss}.log");
                                ServerContext.Day = DateTime.Now.Day;
                            }
                        }

                        Thread.Sleep(500);
                    }

                    LmpPluginHandler.FireOnServerStop();
                    commandThread.Wait();
                    clientThread.Wait();
                    vesselRelayThread.Wait();

                    vesselRelayFarThread.Wait();
                    vesselRelayMediumThread.Wait();
                    vesselRelayCloseThread.Wait();
                }
                LunaLog.Normal("Goodbye and thanks for all the fish!");
                Environment.Exit(0);
            }
            catch (Exception e)
            {
                LunaLog.Fatal("Error in main server thread, Exception: " + e);
                throw;
            }
        }
Beispiel #48
0
 internal PlayerPartedEvent(Player player) : base(player)
 {
     Universe = player.Universe;
     Team     = player.Team;
 }
Beispiel #49
0
 ///<summary>Copy constructor</summary>
 ///<param name="universe">The universe of this ear peduncle.</param>
 ///<param name="toCopy">The ear peduncle to copy.</param>
 public EarPeduncle(Universe universe, EarPeduncle toCopy)
     : base(universe, toCopy)
 {
     InterNode_ = new InterNode(universe, toCopy.InterNode_);
 }
Beispiel #50
0
            private void WriteFieldOrPropType(Type type)
            {
                Universe u = type.Module.universe;

                if (type == u.System_Type)
                {
                    WriteByte(0x50);
                }
                else if (type == u.System_Object)
                {
                    WriteByte(0x51);
                }
                else if (type == u.System_Boolean)
                {
                    WriteByte(0x02);
                }
                else if (type == u.System_Char)
                {
                    WriteByte(0x03);
                }
                else if (type == u.System_SByte)
                {
                    WriteByte(0x04);
                }
                else if (type == u.System_Byte)
                {
                    WriteByte(0x05);
                }
                else if (type == u.System_Int16)
                {
                    WriteByte(0x06);
                }
                else if (type == u.System_UInt16)
                {
                    WriteByte(0x07);
                }
                else if (type == u.System_Int32)
                {
                    WriteByte(0x08);
                }
                else if (type == u.System_UInt32)
                {
                    WriteByte(0x09);
                }
                else if (type == u.System_Int64)
                {
                    WriteByte(0x0A);
                }
                else if (type == u.System_UInt64)
                {
                    WriteByte(0x0B);
                }
                else if (type == u.System_Single)
                {
                    WriteByte(0x0C);
                }
                else if (type == u.System_Double)
                {
                    WriteByte(0x0D);
                }
                else if (type == u.System_String)
                {
                    WriteByte(0x0E);
                }
                else if (type.IsArray)
                {
                    WriteByte(0x1D);
                    WriteFieldOrPropType(type.GetElementType());
                }
                else if (type.IsEnum)
                {
                    WriteByte(0x55);
                    WriteTypeName(type);
                }
                else
                {
                    throw new ArgumentException();
                }
            }
Beispiel #51
0
 private void neuladenToolStripMenuItem_Click(object sender, EventArgs e)
 {
     universe = Universe.getInstance(AppDomain.CurrentDomain.BaseDirectory);
 }
Beispiel #52
0
            private void WriteFixedArg(Type type, object value)
            {
                Universe u = assembly.universe;

                if (type == u.System_String)
                {
                    WriteString((string)value);
                }
                else if (type == u.System_Boolean)
                {
                    WriteByte((bool)value ? (byte)1 : (byte)0);
                }
                else if (type == u.System_Char)
                {
                    WriteUInt16((char)value);
                }
                else if (type == u.System_SByte)
                {
                    WriteByte((byte)(sbyte)value);
                }
                else if (type == u.System_Byte)
                {
                    WriteByte((byte)value);
                }
                else if (type == u.System_Int16)
                {
                    WriteUInt16((ushort)(short)value);
                }
                else if (type == u.System_UInt16)
                {
                    WriteUInt16((ushort)value);
                }
                else if (type == u.System_Int32)
                {
                    WriteInt32((int)value);
                }
                else if (type == u.System_UInt32)
                {
                    WriteInt32((int)(uint)value);
                }
                else if (type == u.System_Int64)
                {
                    WriteInt64((long)value);
                }
                else if (type == u.System_UInt64)
                {
                    WriteInt64((long)(ulong)value);
                }
                else if (type == u.System_Single)
                {
                    WriteSingle((float)value);
                }
                else if (type == u.System_Double)
                {
                    WriteDouble((double)value);
                }
                else if (type == u.System_Type)
                {
                    WriteTypeName((Type)value);
                }
                else if (type == u.System_Object)
                {
                    if (value == null)
                    {
                        type = u.System_String;
                    }
                    else if (value is Type)
                    {
                        // value.GetType() would return a subclass of Type, but we don't want to deal with that
                        type = u.System_Type;
                    }
                    else if (value is CustomAttributeTypedArgument)
                    {
                        CustomAttributeTypedArgument cta = (CustomAttributeTypedArgument)value;
                        value = cta.Value;
                        type  = cta.ArgumentType;
                    }
                    else
                    {
                        type = u.Import(value.GetType());
                    }
                    WriteFieldOrPropType(type);
                    WriteFixedArg(type, value);
                }
                else if (type.IsArray)
                {
                    if (value == null)
                    {
                        WriteInt32(-1);
                    }
                    else
                    {
                        Array array    = (Array)value;
                        Type  elemType = type.GetElementType();
                        WriteInt32(array.Length);
                        foreach (object val in array)
                        {
                            WriteFixedArg(elemType, val);
                        }
                    }
                }
                else if (type.IsEnum)
                {
                    WriteFixedArg(type.GetEnumUnderlyingTypeImpl(), value);
                }
                else
                {
                    throw new ArgumentException();
                }
            }
Beispiel #53
0
        /// <summary>
        /// Applies universe selection the the data feed and algorithm
        /// </summary>
        /// <param name="universe">The universe to perform selection on</param>
        /// <param name="dateTimeUtc">The current date time in utc</param>
        /// <param name="universeData">The data provided to perform selection with</param>
        public SecurityChanges ApplyUniverseSelection(Universe universe, DateTime dateTimeUtc, BaseDataCollection universeData)
        {
            var settings = universe.UniverseSettings;

            // perform initial filtering and limit the result
            var selectSymbolsResult = universe.PerformSelection(dateTimeUtc, universeData);

            // check for no changes first
            if (ReferenceEquals(selectSymbolsResult, Universe.Unchanged))
            {
                return(SecurityChanges.None);
            }

            // materialize the enumerable into a set for processing
            var selections = selectSymbolsResult.ToHashSet();

            // create a hash set of our existing subscriptions by sid
            var existingSubscriptions = _dataFeed.Subscriptions.ToHashSet(x => x.Security.Symbol);

            var additions = new List <Security>();
            var removals  = new List <Security>();

            // determine which data subscriptions need to be removed from this universe
            foreach (var member in universe.Members.Values)
            {
                var config = member.SubscriptionDataConfig;

                // if we've selected this subscription again, keep it
                if (selections.Contains(config.Symbol))
                {
                    continue;
                }

                // don't remove if the universe wants to keep him in
                if (!universe.CanRemoveMember(dateTimeUtc, member))
                {
                    continue;
                }

                // remove the member - this marks this member as not being
                // selected by the universe, but it may remain in the universe
                // until open orders are closed and the security is liquidated
                removals.Add(member);

                // but don't physically remove it from the algorithm if we hold stock or have open orders against it
                var openOrders = _algorithm.Transactions.GetOrders(x => x.Status.IsOpen() && x.Symbol == config.Symbol);
                if (!member.HoldStock && !openOrders.Any())
                {
                    // safe to remove the member from the universe
                    universe.RemoveMember(dateTimeUtc, member);

                    // we need to mark this security as untradeable while it has no data subscription
                    // it is expected that this function is called while in sync with the algo thread,
                    // so we can make direct edits to the security here
                    member.Cache.Reset();
                    _dataFeed.RemoveSubscription(member.Symbol);
                }
            }

            // find new selections and add them to the algorithm
            foreach (var symbol in selections)
            {
                // we already have a subscription for this symbol so don't re-add it
                if (existingSubscriptions.Contains(symbol))
                {
                    continue;
                }

                // create the new security, the algorithm thread will add this at the appropriate time
                Security security;
                if (!_algorithm.Securities.TryGetValue(symbol, out security))
                {
                    security = universe.CreateSecurity(symbol, _algorithm, _marketHoursDatabase, _symbolPropertiesDatabase);
                }

                additions.Add(security);

                var addedSubscription = false;
                foreach (var config in universe.GetSubscriptions(security))
                {
                    // ask the limiter if we can add another subscription at that resolution
                    string reason;
                    if (!_limiter.CanAddSubscription(config.Resolution, out reason))
                    {
                        _algorithm.Error(reason);
                        Log.Trace("UniverseSelection.ApplyUniverseSelection(): Skipping adding subscription: " + config.Symbol.ToString() + ": " + reason);
                        continue;
                    }

                    // add the new subscriptions to the data feed
                    if (_dataFeed.AddSubscription(universe, security, config, dateTimeUtc, _algorithm.EndDate.ConvertToUtc(_algorithm.TimeZone)))
                    {
                        addedSubscription = true;
                    }
                }

                if (addedSubscription)
                {
                    universe.AddMember(dateTimeUtc, security);
                }
            }

            // Add currency data feeds that weren't explicitly added in Initialize
            if (additions.Count > 0)
            {
                var addedSecurities = _algorithm.Portfolio.CashBook.EnsureCurrencyDataFeeds(_algorithm.Securities, _algorithm.SubscriptionManager, _marketHoursDatabase, _symbolPropertiesDatabase, _algorithm.BrokerageModel.DefaultMarkets);
                foreach (var security in addedSecurities)
                {
                    // assume currency feeds are always one subscription per, these are typically quote subscriptions
                    _dataFeed.AddSubscription(universe, security, security.SubscriptionDataConfig, dateTimeUtc, _algorithm.EndDate.ConvertToUtc(_algorithm.TimeZone));
                }
            }

            // return None if there's no changes, otherwise return what we've modified
            var securityChanges = additions.Count + removals.Count != 0
                ? new SecurityChanges(additions, removals)
                : SecurityChanges.None;

            if (securityChanges != SecurityChanges.None)
            {
                Log.Debug("UniverseSelection.ApplyUniverseSelection(): " + dateTimeUtc + ": " + securityChanges);
            }

            return(securityChanges);
        }
Beispiel #54
0
        public static void Main()
        {
            try
            {
                Console.Title = $"LMPServer {LmpVersioning.CurrentVersion}";
#if DEBUG
                Console.Title += " DEBUG";
#endif
                Console.OutputEncoding  = Encoding.Unicode;
                ServerContext.StartTime = LunaTime.UtcNow.Ticks;

                //We cannot run more than 6 instances ofd servers + clients as otherwise the sync time will fail (30 seconds / 5 seconds = 6) but we use 3 for safety
                if (GetRunningInstances() > 3)
                {
                    throw new HandledException("Cannot run more than 3 servers at a time!");
                }

                //Start the server clock
                ServerContext.ServerClock.Start();

                //Set the last player activity time to server start
                ServerContext.LastPlayerActivity = ServerContext.ServerClock.ElapsedMilliseconds;

                //Register the ctrl+c event
                Console.CancelKeyPress      += CatchExit;
                ServerContext.ServerStarting = true;

                //Set day for log change
                ServerContext.Day = LunaTime.Now.Day;

                LunaLog.Normal($"Starting Luna Server version: {LmpVersioning.CurrentVersion}");

                Universe.CheckUniverse();
                LoadSettingsAndGroups();
                LmpPluginHandler.LoadPlugins();
                WarpSystem.Reset();
                ChatSystem.Reset();

                LunaLog.Normal($"Starting {GeneralSettings.SettingsStore.WarpMode} server on Port {GeneralSettings.SettingsStore.Port}... ");

                ServerContext.ServerRunning = true;
                ServerContext.LidgrenServer.SetupLidgrenServer();

                Task.Run(() => new CommandHandler().ThreadMain());
                Task.Run(() => new ClientMainThread().ThreadMain());

                Task.Run(() => ServerContext.LidgrenServer.StartReceiveingMessages());
                Task.Run(() => ServerContext.LidgrenServer.RefreshMasterServersList());
                Task.Run(() => ServerContext.LidgrenServer.RegisterWithMasterServer());
                Task.Run(() => LogThread.RunLogThread());

                Task.Run(() => VesselRelaySystem.RelayOldVesselMessages());
                Task.Run(() => VesselUpdateRelaySystem.RelayToFarPlayers());
                Task.Run(() => VesselUpdateRelaySystem.RelayToMediumDistancePlayers());
                Task.Run(() => VesselUpdateRelaySystem.RelayToClosePlayers());
                Task.Run(() => VersionChecker.CheckForNewVersions());

                while (ServerContext.ServerStarting)
                {
                    Thread.Sleep(500);
                }

                LunaLog.Normal("All systems up and running. Поехали!");
                LmpPluginHandler.FireOnServerStart();

                QuitEvent.WaitOne();

                WarpSystem.SaveSubspacesToFile();
                LmpPluginHandler.FireOnServerStop();

                LunaLog.Normal("Goodbye and thanks for all the fish!");
            }
            catch (Exception e)
            {
                if (e is HandledException)
                {
                    LunaLog.Fatal(e.Message);
                }
                else
                {
                    LunaLog.Fatal($"Error in main server thread, Exception: {e}");
                }
                Console.ReadLine(); //Avoid closing automatically
            }
        }
Beispiel #55
0
        /// <summary>
        /// Generates the stub .exe file for starting the app
        /// </summary>
        /// <param name="config"></param>
        static void GenerateExe(Config config)
        {
            var u     = new Universe();
            var aName = new AssemblyName(Path.GetFileNameWithoutExtension(new FileInfo(config.Output).Name));
            var ab    = u.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Save, Path.GetDirectoryName(config.Output));
            var mb    = ab.DefineDynamicModule(config.Output, aName.Name + (aName.Name.EndsWith(".exe") ? string.Empty : ".exe"));
            var tb    = mb.DefineType("PythonMain", IKVM.Reflection.TypeAttributes.Public);

            if (!string.IsNullOrEmpty(config.Win32Icon))
            {
                ab.__DefineIconResource(File.ReadAllBytes(config.Win32Icon));
            }

            MethodBuilder assemblyResolveMethod = null;
            ILGenerator   gen = null;

            if (config.Standalone)
            {
                ConsoleOps.Info("Generating stand alone executable");
                config.Embed = true;

                foreach (var a in System.AppDomain.CurrentDomain.GetAssemblies())
                {
                    var n = new AssemblyName(a.FullName);
#if CLR2
                    if (a.EntryPoint == null && (n.Name.StartsWith("IronPython") || n.Name == "Microsoft.Dynamic" || n.Name == "Microsoft.Scripting"))
                    {
#else
                    if (!a.IsDynamic && a.EntryPoint == null && (n.Name.StartsWith("IronPython") || n.Name == "Microsoft.Dynamic" || n.Name == "Microsoft.Scripting"))
                    {
#endif
                        ConsoleOps.Info("\tEmbedded {0} {1}", n.Name, n.Version);
                        var f = new FileStream(a.Location, FileMode.Open, FileAccess.Read);
                        mb.DefineManifestResource("Dll." + n.Name, f, IKVM.Reflection.ResourceAttributes.Public);
                    }
                }

                // we currently do no error checking on what is passed in to the assemblyresolve event handler
                assemblyResolveMethod = tb.DefineMethod("AssemblyResolve", MethodAttributes.Public | MethodAttributes.Static, u.Import(typeof(System.Reflection.Assembly)), new IKVM.Reflection.Type[] { u.Import(typeof(System.Object)), u.Import(typeof(System.ResolveEventArgs)) });
                gen = assemblyResolveMethod.GetILGenerator();
                var s = gen.DeclareLocal(u.Import(typeof(System.IO.Stream))); // resource stream

                gen.Emit(OpCodes.Ldnull);
                gen.Emit(OpCodes.Stloc, s);
                var d = gen.DeclareLocal(u.Import(typeof(byte[]))); // data buffer;
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Reflection.Assembly)).GetMethod("GetEntryAssembly"), Type.EmptyTypes);
                gen.Emit(OpCodes.Ldstr, "Dll.");
                gen.Emit(OpCodes.Ldarg_1);    // The event args
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.ResolveEventArgs)).GetMethod("get_Name"), Type.EmptyTypes);
                gen.Emit(OpCodes.Newobj, u.Import(typeof(System.Reflection.AssemblyName)).GetConstructor(new IKVM.Reflection.Type[] { u.Import(typeof(string)) }));
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Reflection.AssemblyName)).GetMethod("get_Name"), Type.EmptyTypes);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(string)).GetMethod("Concat", new IKVM.Reflection.Type[] { u.Import(typeof(string)), u.Import(typeof(string)) }), Type.EmptyTypes);
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.Reflection.Assembly)).GetMethod("GetManifestResourceStream", new IKVM.Reflection.Type[] { u.Import(typeof(string)) }), Type.EmptyTypes);
                gen.Emit(OpCodes.Stloc, s);
                gen.Emit(OpCodes.Ldloc, s);
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.IO.Stream)).GetMethod("get_Length"), Type.EmptyTypes);
                gen.Emit(OpCodes.Newarr, u.Import(typeof(System.Byte)));
                gen.Emit(OpCodes.Stloc, d);
                gen.Emit(OpCodes.Ldloc, s);
                gen.Emit(OpCodes.Ldloc, d);
                gen.Emit(OpCodes.Ldc_I4_0);
                gen.Emit(OpCodes.Ldloc, s);
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.IO.Stream)).GetMethod("get_Length"), Type.EmptyTypes);
                gen.Emit(OpCodes.Conv_I4);
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.IO.Stream)).GetMethod("Read", new IKVM.Reflection.Type[] { u.Import(typeof(byte[])), u.Import(typeof(int)), u.Import(typeof(int)) }), Type.EmptyTypes);
                gen.Emit(OpCodes.Pop);
                gen.Emit(OpCodes.Ldloc, d);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Reflection.Assembly)).GetMethod("Load", new IKVM.Reflection.Type[] { u.Import(typeof(byte[])) }), Type.EmptyTypes);
                gen.Emit(OpCodes.Ret);

                // generate a static constructor to assign the AssemblyResolve handler (otherwise it tries to use IronPython before it adds the handler)
                // the other way of handling this would be to move the call to InitializeModule into a separate method.
                var staticConstructor = tb.DefineConstructor(MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, Type.EmptyTypes);
                gen = staticConstructor.GetILGenerator();
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.AppDomain)).GetMethod("get_CurrentDomain"), Type.EmptyTypes);
                gen.Emit(OpCodes.Ldnull);
                gen.Emit(OpCodes.Ldftn, assemblyResolveMethod);
                gen.Emit(OpCodes.Newobj, u.Import(typeof(System.ResolveEventHandler)).GetConstructor(new IKVM.Reflection.Type[] { u.Import(typeof(object)), u.Import(typeof(System.IntPtr)) }));
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.AppDomain)).GetMethod("add_AssemblyResolve"), Type.EmptyTypes);
                gen.Emit(OpCodes.Ret);
            }

            var mainMethod = tb.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, u.Import(typeof(int)), Type.EmptyTypes);
            if (config.Target == PEFileKinds.WindowApplication && config.UseMta)
            {
                mainMethod.SetCustomAttribute(u.Import(typeof(System.MTAThreadAttribute)).GetConstructor(Type.EmptyTypes), new byte[0]);
            }
            else if (config.Target == PEFileKinds.WindowApplication)
            {
                mainMethod.SetCustomAttribute(u.Import(typeof(System.STAThreadAttribute)).GetConstructor(Type.EmptyTypes), new byte[0]);
            }

            gen = mainMethod.GetILGenerator();

            // variables for saving original working directory and return code of script
            var          strVar  = gen.DeclareLocal(u.Import(typeof(string)));
            var          intVar  = gen.DeclareLocal(u.Import(typeof(int)));
            LocalBuilder dictVar = null;

            if (config.PythonOptions.Count > 0)
            {
                var True  = u.Import(typeof(ScriptingRuntimeHelpers)).GetField("True");
                var False = u.Import(typeof(ScriptingRuntimeHelpers)).GetField("False");

                dictVar = gen.DeclareLocal(u.Import(typeof(Dictionary <string, object>)));
                gen.Emit(OpCodes.Newobj, u.Import(typeof(Dictionary <string, object>)).GetConstructor(Type.EmptyTypes));
                gen.Emit(OpCodes.Stloc, dictVar);

                foreach (var option in config.PythonOptions)
                {
                    gen.Emit(OpCodes.Ldloc, dictVar);
                    gen.Emit(OpCodes.Ldstr, option.Key);
                    if (option.Value is int)
                    {
                        int val = (int)option.Value;
                        if (val >= -128 && val <= 127)
                        {
                            gen.Emit(OpCodes.Ldc_I4_S, val); // this is more optimized
                        }
                        else
                        {
                            gen.Emit(OpCodes.Ldc_I4, val);
                        }
                        gen.Emit(OpCodes.Box, u.Import(typeof(System.Int32)));
                    }
                    else if (option.Value.Equals(ScriptingRuntimeHelpers.True))
                    {
                        gen.Emit(OpCodes.Ldsfld, True);
                    }
                    else if (option.Value.Equals(ScriptingRuntimeHelpers.False))
                    {
                        gen.Emit(OpCodes.Ldsfld, False);
                    }
                    gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(Dictionary <string, object>)).GetMethod("Add", new IKVM.Reflection.Type[] { u.Import(typeof(string)), u.Import(typeof(object)) }), Type.EmptyTypes);
                }
            }

            Label tryStart = gen.BeginExceptionBlock();

            // get the ScriptCode assembly...
            if (config.Embed)
            {
                // put the generated DLL into the resources for the stub exe
                var mem = new MemoryStream();
                var rw  = new ResourceWriter(mem);
                rw.AddResource("IPDll." + Path.GetFileNameWithoutExtension(config.Output) + ".dll", File.ReadAllBytes(config.Output + ".dll"));
                rw.Generate();
                mem.Position = 0;
                mb.DefineManifestResource("IPDll.resources", mem, ResourceAttributes.Public);
                File.Delete(config.Output + ".dll");

                // generate code to load the resource
                gen.Emit(OpCodes.Ldstr, "IPDll");
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Reflection.Assembly)).GetMethod("GetEntryAssembly"), Type.EmptyTypes);
                gen.Emit(OpCodes.Newobj, u.Import(typeof(System.Resources.ResourceManager)).GetConstructor(new IKVM.Reflection.Type[] { u.Import(typeof(string)), u.Import(typeof(System.Reflection.Assembly)) }));
                gen.Emit(OpCodes.Ldstr, "IPDll." + Path.GetFileNameWithoutExtension(config.Output) + ".dll");
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Resources.ResourceManager)).GetMethod("GetObject", new IKVM.Reflection.Type[] { u.Import(typeof(string)) }), Type.EmptyTypes);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Reflection.Assembly)).GetMethod("Load", new IKVM.Reflection.Type[] { u.Import(typeof(byte[])) }), Type.EmptyTypes);
            }
            else
            {
                // save current working directory
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Environment)).GetMethod("get_CurrentDirectory"), Type.EmptyTypes);
                gen.Emit(OpCodes.Stloc, strVar);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Reflection.Assembly)).GetMethod("GetEntryAssembly"), Type.EmptyTypes);
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.Reflection.Assembly)).GetMethod("get_Location"), Type.EmptyTypes);
                gen.Emit(OpCodes.Newobj, u.Import(typeof(System.IO.FileInfo)).GetConstructor(new IKVM.Reflection.Type[] { u.Import(typeof(string)) }));
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.IO.FileInfo)).GetMethod("get_Directory"), Type.EmptyTypes);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.IO.DirectoryInfo)).GetMethod("get_FullName"), Type.EmptyTypes);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Environment)).GetMethod("set_CurrentDirectory"), Type.EmptyTypes);
                gen.Emit(OpCodes.Ldstr, config.Output + ".dll");
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.IO.Path)).GetMethod("GetFullPath", new IKVM.Reflection.Type[] { u.Import(typeof(string)) }), Type.EmptyTypes);
                // result of GetFullPath stays on the stack during the restore of the
                // original working directory

                // restore original working directory
                gen.Emit(OpCodes.Ldloc, strVar);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Environment)).GetMethod("set_CurrentDirectory"), Type.EmptyTypes);

                // for the LoadFile() call, the full path of the assembly is still is on the stack
                // as the result from the call to GetFullPath()
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Reflection.Assembly)).GetMethod("LoadFile", new IKVM.Reflection.Type[] { u.Import(typeof(string)) }), Type.EmptyTypes);
            }

            // emit module name
            gen.Emit(OpCodes.Ldstr, "__main__");  // main module name
            gen.Emit(OpCodes.Ldnull);             // no references
            gen.Emit(OpCodes.Ldc_I4_0);           // don't ignore environment variables for engine startup
            if (config.PythonOptions.Count > 0)
            {
                gen.Emit(OpCodes.Ldloc, dictVar);
            }
            else
            {
                gen.Emit(OpCodes.Ldnull);
            }

            // call InitializeModuleEx
            // (this will also run the script)
            // and put the return code on the stack
            gen.EmitCall(OpCodes.Call, u.Import(typeof(PythonOps)).GetMethod("InitializeModuleEx",
                                                                             new IKVM.Reflection.Type[] { u.Import(typeof(System.Reflection.Assembly)), u.Import(typeof(string)), u.Import(typeof(string[])), u.Import(typeof(bool)), u.Import(typeof(Dictionary <string, object>)) }),
                         Type.EmptyTypes);
            gen.Emit(OpCodes.Stloc, intVar);
            gen.BeginCatchBlock(u.Import(typeof(Exception)));

            if (config.Target == PEFileKinds.ConsoleApplication)
            {
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.Exception)).GetMethod("get_Message", Type.EmptyTypes), Type.EmptyTypes);
                gen.Emit(OpCodes.Stloc, strVar);
                gen.Emit(OpCodes.Ldstr, config.ErrorMessageFormat);
                gen.Emit(OpCodes.Ldloc, strVar);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Console)).GetMethod("WriteLine", new IKVM.Reflection.Type[] { u.Import(typeof(string)), u.Import(typeof(string)) }), Type.EmptyTypes);
            }
            else
            {
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.Exception)).GetMethod("get_Message", Type.EmptyTypes), Type.EmptyTypes);
                gen.Emit(OpCodes.Stloc, strVar);
                gen.Emit(OpCodes.Ldstr, config.ErrorMessageFormat);
                gen.Emit(OpCodes.Ldloc, strVar);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(string)).GetMethod("Format", new IKVM.Reflection.Type[] { u.Import(typeof(string)), u.Import(typeof(string)) }), Type.EmptyTypes);
                gen.Emit(OpCodes.Ldstr, "Error");
                gen.Emit(OpCodes.Ldc_I4, (int)System.Windows.Forms.MessageBoxButtons.OK);
                gen.Emit(OpCodes.Ldc_I4, (int)System.Windows.Forms.MessageBoxIcon.Error);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Windows.Forms.MessageBox)).GetMethod("Show", new IKVM.Reflection.Type[] { u.Import(typeof(string)), u.Import(typeof(string)), u.Import(typeof(System.Windows.Forms.MessageBoxButtons)), u.Import(typeof(System.Windows.Forms.MessageBoxIcon)) }), Type.EmptyTypes);
                gen.Emit(OpCodes.Pop);
            }

            gen.Emit(OpCodes.Ldc_I4, -1); // return code is -1 to show failure
            gen.Emit(OpCodes.Stloc, intVar);

            gen.EndExceptionBlock();

            gen.Emit(OpCodes.Ldloc, intVar);
            gen.Emit(OpCodes.Ret);

            tb.CreateType();
            ab.SetEntryPoint(mainMethod, config.Target);
            string fileName = aName.Name.EndsWith(".exe") ? aName.Name : aName.Name + ".exe";
            ab.Save(fileName, config.Platform, config.Machine);
        }
        private void Render(object sender, TicEventArgs e)
        {
            var toRender = new List <Printable>();

            // background
            var background = e.Universe.PrintableBackground;

            toRender.Add(background);

            // pipes
            var pipes = e.PrintablePipes;

            if (MyBird.IsDead || MyBird.CurrentGraceInterval > 0)
            {
                pipes = pipes.Select(p => new Printable(p.X, p.Y, p.Image, Convert.ToInt32(p.R), 0.4, p.GuidKey)).ToList();
            }
            toRender.AddRange(pipes);


            // the base
            var theBase = e.Universe.TheBase;

            toRender.Add(theBase);

            // score
            toRender.AddRange(GetPrintableScore(MyBird.score));

            // other players
            foreach (var bird in e.Players)
            {
                if (bird != MyBird)
                {
                    var otherBirdIndex = bird.IsDead?0:bird.playerIndex;
                    var otherBird      = new Printable(bird.playerx, bird.playery, bird.player_images[otherBirdIndex], -bird.visibleRot, opacity: 0.5, guidKey: bird.GuidKey);
                    toRender.Add(otherBird);
                }
            }

            // myBird
            var myBirdIndex = MyBird.IsDead?0:MyBird.playerIndex;
            var ocell       = new Printable(MyBird.playerx, MyBird.playery, MyBird.player_images[myBirdIndex], -MyBird.visibleRot, null, MyBird.GuidKey);

            toRender.Add(ocell);

            // play again
            if (MyBird.IsDead && MyBird.CurrentPenaltyTime == 0)
            {
                var playAgain = e.Universe.PlayAgain;
                toRender.Add(playAgain);
                if (!PleaseStopSent)
                {
                    PleaseStopSent = true;
                    Universe.PleaseStop();
                }
            }
            else if (MyBird.IsDead && MyBird.CurrentPenaltyTime > 0)
            {
                var gameOver = e.Universe.GameOver;
                toRender.Add(gameOver);
            }

            Statistics.totalPlayers  = e.Players.Count();
            Statistics.fps           = Universe.CurrentFps;
            Statistics.totalSessions = Universe.TotalSessions.ToString();
            Statistics.startedAt     = Universe.StartedAt;
            Statistics.maxScore      = Universe.MaxScore;
            lock (ToRender)
            {
                ToRender.Clear();
                ToRender.AddRange(toRender);
            }

            InvokeAsync(StateHasChanged);
        }
 //public frmStudioCollectionMaker()
 //{
 //    InitializeComponent();
 //}
 public frmStudioGroupMaker(Universe univ)
 {
     InitializeComponent();
     u = univ; // Initialize Universe
 }
Beispiel #58
0
 ///Constructor.
 public ExposedSheath(Universe universe, ExposedSheath toCopy)
     : base(universe, toCopy)
 {
     TTSinceSen = toCopy.TTSinceSen;
 }
Beispiel #59
0
        public void BlinkerTest()
        {
            Universe testUniverse = new Universe(5, 5);

            testUniverse.SetCell(1, 2, true);
            testUniverse.SetCell(2, 2, true);
            testUniverse.SetCell(3, 2, true);

            Assert.IsFalse(testUniverse.GetCell(0, 0).Alive);
            Assert.IsFalse(testUniverse.GetCell(1, 0).Alive);
            Assert.IsFalse(testUniverse.GetCell(2, 0).Alive);
            Assert.IsFalse(testUniverse.GetCell(3, 0).Alive);
            Assert.IsFalse(testUniverse.GetCell(4, 0).Alive);

            Assert.IsFalse(testUniverse.GetCell(0, 1).Alive);
            Assert.IsFalse(testUniverse.GetCell(1, 1).Alive);
            Assert.IsFalse(testUniverse.GetCell(2, 1).Alive);
            Assert.IsFalse(testUniverse.GetCell(3, 1).Alive);
            Assert.IsFalse(testUniverse.GetCell(4, 1).Alive);

            Assert.IsFalse(testUniverse.GetCell(0, 2).Alive);
            Assert.IsTrue(testUniverse.GetCell(1, 2).Alive);
            Assert.IsTrue(testUniverse.GetCell(2, 2).Alive);
            Assert.IsTrue(testUniverse.GetCell(3, 2).Alive);
            Assert.IsFalse(testUniverse.GetCell(4, 2).Alive);

            Assert.IsFalse(testUniverse.GetCell(0, 3).Alive);
            Assert.IsFalse(testUniverse.GetCell(1, 3).Alive);
            Assert.IsFalse(testUniverse.GetCell(2, 3).Alive);
            Assert.IsFalse(testUniverse.GetCell(3, 3).Alive);
            Assert.IsFalse(testUniverse.GetCell(4, 3).Alive);

            Assert.IsFalse(testUniverse.GetCell(0, 4).Alive);
            Assert.IsFalse(testUniverse.GetCell(1, 4).Alive);
            Assert.IsFalse(testUniverse.GetCell(2, 4).Alive);
            Assert.IsFalse(testUniverse.GetCell(3, 4).Alive);
            Assert.IsFalse(testUniverse.GetCell(4, 4).Alive);

            testUniverse.Print();

            testUniverse.Evolve();

            testUniverse.Print();

            Assert.IsFalse(testUniverse.GetCell(0, 0).Alive);
            Assert.IsFalse(testUniverse.GetCell(1, 0).Alive);
            Assert.IsFalse(testUniverse.GetCell(2, 0).Alive);
            Assert.IsFalse(testUniverse.GetCell(3, 0).Alive);
            Assert.IsFalse(testUniverse.GetCell(4, 0).Alive);

            Assert.IsFalse(testUniverse.GetCell(0, 1).Alive);
            Assert.IsFalse(testUniverse.GetCell(1, 1).Alive);
            Assert.IsTrue(testUniverse.GetCell(2, 1).Alive);
            Assert.IsFalse(testUniverse.GetCell(3, 1).Alive);
            Assert.IsFalse(testUniverse.GetCell(4, 1).Alive);

            Assert.IsFalse(testUniverse.GetCell(0, 2).Alive);
            Assert.IsFalse(testUniverse.GetCell(1, 2).Alive);
            Assert.IsTrue(testUniverse.GetCell(2, 2).Alive);
            Assert.IsFalse(testUniverse.GetCell(3, 2).Alive);
            Assert.IsFalse(testUniverse.GetCell(4, 2).Alive);

            Assert.IsFalse(testUniverse.GetCell(0, 3).Alive);
            Assert.IsFalse(testUniverse.GetCell(1, 3).Alive);
            Assert.IsTrue(testUniverse.GetCell(2, 3).Alive);
            Assert.IsFalse(testUniverse.GetCell(3, 3).Alive);
            Assert.IsFalse(testUniverse.GetCell(4, 3).Alive);

            Assert.IsFalse(testUniverse.GetCell(0, 4).Alive);
            Assert.IsFalse(testUniverse.GetCell(1, 4).Alive);
            Assert.IsFalse(testUniverse.GetCell(2, 4).Alive);
            Assert.IsFalse(testUniverse.GetCell(3, 4).Alive);
            Assert.IsFalse(testUniverse.GetCell(4, 4).Alive);
        }
Beispiel #60
0
 /// <summary>
 /// Converts a number to an equivalent string consisting of cahracters of the Universe's alphabet (base conversion).
 /// </summary>
 public static string NumberToText(BigInteger number, string alphabet)
 {
     return(Universe.DecimalToArbitrarySystem(number, alphabet));
 }