コード例 #1
0
        private static Tuple <string, ShipDNA>[] ScanFolder(string foldername, CancellationToken cancel)
        {
            //NOTE: This method is running in an arbitrary thread

            try
            {
                List <Tuple <string, ShipDNA> > retVal = new List <Tuple <string, ShipDNA> >();

                foreach (string filename in Directory.EnumerateFiles(foldername, "*.xml"))
                {
                    if (cancel.IsCancellationRequested)
                    {
                        return(null);
                    }

                    try
                    {
                        // Try to deserialize this file as shipdna
                        ShipDNA dna = UtilityCore.DeserializeFromFile <ShipDNA>(filename);

                        // Success, add it
                        retVal.Add(Tuple.Create(filename, dna));
                    }
                    catch (Exception) { }
                }

                return(retVal.ToArray());
            }
            catch (Exception)
            {
                return(null);
            }
        }
コード例 #2
0
        private void SaveShip()
        {
            // Get ship from the editor
            string        name;         // the editor returns this trimmed
            List <string> layerNames;
            SortedList <int, List <DesignPart> > partsByLayer;

            editor1.GetDesign(out name, out layerNames, out partsByLayer);

            if (name == "")
            {
                MessageBox.Show("Please give the ship a name first", this.Title, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // Get the definition of the ship
            ShipDNA ship = new ShipDNA();

            ship.ShipName = name;
            //TODO: Validate the ship
            //ship.IsValid =
            ship.LayerNames   = layerNames;
            ship.PartsByLayer = new SortedList <int, List <ShipPartDNA> >();
            foreach (int layerIndex in partsByLayer.Keys)
            {
                ship.PartsByLayer.Add(layerIndex, partsByLayer[layerIndex].Select(o => o.Part3D.GetDNA()).ToList());
            }

            SaveShip(ship);
        }
コード例 #3
0
        private static ShipDNA RotateDNA_FromExternal(ShipDNA dna)
        {
            Quaternion quat = new Quaternion(new Vector3D(1, 0, 0), -90);

            RotateTransform3D rotation = new RotateTransform3D(new QuaternionRotation3D(quat));


            //double sqrt2div2 = Math.Sqrt(2d) / 2d;
            //Quaternion orig = new Quaternion(0, -sqrt2div2, 0, sqrt2div2);
            //Quaternion rotated = orig.RotateBy(quat);
            //Quaternion rotated3 = quat.RotateBy(orig);


            //Vector3D z = new Vector3D(0, 0, 1);
            //Vector3D zOrig = orig.GetRotatedVector(z);
            //Vector3D zRot = rotated.GetRotatedVector(z);
            //Vector3D zRot3 = rotated3.GetRotatedVector(z);


            //Transform3DGroup group = new Transform3DGroup();
            //group.Children.Add(new RotateTransform3D(new QuaternionRotation3D(orig)));
            //group.Children.Add(new RotateTransform3D(new QuaternionRotation3D(quat)));

            //Vector3D zRot2 = group.Transform(z);


            //Thruster testThrust = new Thruster();


            return(RotateDNA_DoIt(dna, quat, rotation));
        }
コード例 #4
0
        private void AddEgg_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_bots.Count == 0)
                {
                    MessageBox.Show("Add a bot first", this.Title, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                Swimbot bot = _bots[StaticRandom.Next(_bots.Count)];

                Point3D position = bot.PositionWorld + Math3D.GetRandomVector_Spherical_Shell(bot.Radius * 1.5d);

                // The radius should be 20% the size of the adult ship
                ShipDNA dna    = bot.GetNewDNA();
                double  radius = dna.PartsByLayer.SelectMany(o => o.Value).
                                 Max(o => o.Position.ToVector().Length + Math1D.Max(o.Scale.X, o.Scale.Y, o.Scale.Z))
                                 * .2d;

                Egg <ShipDNA> egg = new Egg <ShipDNA>(position, radius, _world, _material_Egg, _itemOptions, dna);

                egg.PhysicsBody.AngularVelocity = bot.PhysicsBody.AngularVelocity;
                egg.PhysicsBody.Velocity        = bot.PhysicsBody.Velocity;

                egg.PhysicsBody.ApplyForceAndTorque += new EventHandler <BodyApplyForceAndTorqueArgs>(Egg_ApplyForceAndTorque);

                _map.AddItem(egg);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
コード例 #5
0
        /// <summary>
        /// This creates a new ship and puts syncronizes part
        /// </summary>
        public bool ShipEdited()
        {
            ShipDNA newDNA = GetDNAFromEditor(_editor);

            ShipPlayer newShip = null;

            try
            {
                // Create the new ship
                newShip = ShipPlayer.GetNewShip(newDNA, _world, _material_Ship, _map, _shipExtra);
            }
            catch (Exception ex)
            {
                return(false);
            }

            TransferContainers(_player.Ship, newShip);

            List <ShipPartDNA> unaccountedParts = newDNA.PartsByLayer.
                                                  SelectMany(o => o.Value).
                                                  ToList();

            Cargo[] remainder = TransferCargo(_player.Ship, newShip, unaccountedParts);

            RedistributeParts(remainder, unaccountedParts);

            newShip.RecalculateMass();

            SwapShip(_player, newShip);

            return(true);
        }
コード例 #6
0
        /// <summary>
        /// This returns a candidate that still needs to be spawned and scored
        /// </summary>
        public Tuple <long, ShipDNA> GetCandidate(string shipName)
        {
            // Find the finalists that still need more spawned
            TrackingCandidate[] finalists = _finalists.Where(o => o.DNA.ShipName == shipName && o.NumStarted < this.FinalistCount).ToArray();

            TrackingCandidate finalist = null;

            if (finalists.Length > 0)
            {
                // Pick a random one
                finalist = finalists[StaticRandom.Next(finalists.Length)];
            }
            else
            {
                // See if there are any candidates waiting to go in the finalist list
                ShipDNA dna = this.Candidates.Pop(shipName);
                if (dna == null)
                {
                    return(null);
                }

                finalist = new TrackingCandidate(dna);
                _finalists.Add(finalist);
            }

            // Exit Function
            return(Tuple.Create(finalist.Token, finalist.DNA));
        }
コード例 #7
0
        public static void SaveShip(ShipDNA ship)
        {
            // Make sure the folder exists
            string foldername = System.IO.Path.Combine(UtilityCore.GetOptionsFolder(), SHIPFOLDER);

            if (!Directory.Exists(foldername))
            {
                Directory.CreateDirectory(foldername);
            }

            int infiniteLoopDetector = 0;

            while (true)
            {
                char[] illegalChars = System.IO.Path.GetInvalidFileNameChars();
                string filename     = new string(ship.ShipName.Select(o => illegalChars.Contains(o) ? '_' : o).ToArray());
                filename = DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss.fff") + " - " + filename + ".xml";
                filename = System.IO.Path.Combine(foldername, filename);

                try
                {
                    UtilityCore.SerializeToFile(filename, ship);
                    break;
                }
                catch (IOException ex)
                {
                    infiniteLoopDetector++;
                    if (infiniteLoopDetector > 100)
                    {
                        throw new ApplicationException("Couldn't create the file\r\n" + filename, ex);
                    }
                }
            }
        }
コード例 #8
0
        /// <summary>
        /// This gathers parts and sets up the editor
        /// </summary>
        public void EditShip(string title, UIElement managementControl)
        {
            PartDesignBase[] combinedParts = GatherParts(false);

            // Fix the orientations (or they will be random when dragged to the surface, which is really annoying to manually fix)
            foreach (PartDesignBase part in combinedParts)
            {
                part.Orientation = Quaternion.Identity;
            }

            _editor.SetupEditor(title, combinedParts, managementControl);

            #region Show ship

            ShipDNA dna = _player.Ship.GetNewDNA();

            SortedList <int, List <DesignPart> > partsByLayer = new SortedList <int, List <DesignPart> >();
            foreach (int layerIndex in dna.PartsByLayer.Keys)
            {
                partsByLayer.Add(layerIndex, dna.PartsByLayer[layerIndex].Select(o => CreateDesignPart(o, _editorOptions)).ToList());
            }

            _editor.SetDesign(dna.ShipName, dna.LayerNames, partsByLayer);

            #endregion

            // Remember what parts came from the ship
            _fromShip = dna.PartsByLayer.
                        SelectMany(o => o.Value).
                        ToArray();
        }
コード例 #9
0
        private static ShipDNA RotateDNA_ToExternal(ShipDNA dna)
        {
            Quaternion quat = new Quaternion(new Vector3D(1, 0, 0), 90);

            RotateTransform3D rotation = new RotateTransform3D(new QuaternionRotation3D(quat));

            return(RotateDNA_DoIt(dna, quat, rotation));
        }
コード例 #10
0
            public WinningBean(ShipDNA dna, double score, double age)
            {
                this.Ship = null;
                this.DNA  = dna;

                this.Score = score;
                this.Age   = age;
            }
コード例 #11
0
            public WinningBean(ShipDNA dna, double score, double age)
            {
                this.Ship = null;
                this.DNA = dna;

                this.Score = score;
                this.Age = age;
            }
コード例 #12
0
        public static ShipPlayer GetNewShip(ShipDNA dna, World world, int material_Ship, Map map, ShipExtraArgs extra)
        {
            ShipDNA rotatedDNA = RotateDNA_FromExternal(dna);

            #region asserts

            //ShipDNA rockedDNA1 = RotateDNA_ToExternal(RotateDNA_FromExternal(dna));
            //ShipDNA rockedDNA2 = RotateDNA_FromExternal(rockedDNA1);

            //var compare1a = dna.PartsByLayer.SelectMany(o => o.Value).ToArray();
            //var compare1b = rockedDNA1.PartsByLayer.SelectMany(o => o.Value).ToArray();

            //var compare2a = rotatedDNA.PartsByLayer.SelectMany(o => o.Value).ToArray();
            //var compare2b = rockedDNA2.PartsByLayer.SelectMany(o => o.Value).ToArray();

            //for(int cntr = 0; cntr < compare1a.Length; cntr++)
            //{
            //    var com1a = compare1a[cntr];
            //    var com1b = compare1b[cntr];

            //    var com2a = compare2a[cntr];
            //    var com2b = compare2b[cntr];

            //    if(!Math3D.IsNearValue(com1a.Position, com1b.Position))
            //    {
            //        int three = 3;
            //    }
            //    if (!Math3D.IsNearValue(com1a.Orientation, com1b.Orientation))
            //    {
            //        int three = 3;
            //    }

            //    if (!Math3D.IsNearValue(com2a.Position, com2b.Position))
            //    {
            //        int four = 4;
            //    }
            //    if (!Math3D.IsNearValue(com2a.Orientation, com2b.Orientation))
            //    {
            //        int four = 4;
            //    }
            //}

            #endregion

            ShipCoreArgs core = new ShipCoreArgs()
            {
                Map           = map,
                Material_Ship = material_Ship,
                World         = world,
            };

            //var construction = await GetNewShipConstructionAsync(options, itemOptions, rotatedDNA, world, material_Ship, material_Projectile, radiation, gravity, cameraPool, map, true, true);
            //var construction = await GetNewShipConstructionAsync(rotatedDNA, world, material_Ship, map, extra);
            var construction = BotConstructor.ConstructBot(rotatedDNA, core, extra);

            return(new ShipPlayer(construction));
        }
コード例 #13
0
        private void AddIconVisual(string name, ShipDNA dna, World world)
        {
            Icon3D icon = new Icon3D(name, dna, world);

            icon.VerticalAlignment = VerticalAlignment.Top;
            icon.MouseDown        += new MouseButtonEventHandler(Icon_MouseDown);

            _icons.Add(icon);
            grdIcons.Children.Add(icon);
        }
コード例 #14
0
        private void AddItem(ShipDNA dna, string filename)
        {
            Grid grid = new Grid();

            grid.ColumnDefinitions.Add(new ColumnDefinition()
            {
                Width = new GridLength(1d, GridUnitType.Auto)
            });
            grid.ColumnDefinitions.Add(new ColumnDefinition()
            {
                Width = new GridLength(4d)
            });
            grid.ColumnDefinitions.Add(new ColumnDefinition()
            {
                Width = new GridLength(1d, GridUnitType.Star)
            });

            Icon3D icon = new Icon3D(dna.ShipName, dna, _world);

            icon.ShowName = false;
            Grid.SetColumn(icon, 0);
            grid.Children.Add(icon);
            icon.Width = 60d;           // this has logic to keep itself square

            StackPanel panel = new StackPanel();

            panel.HorizontalAlignment = HorizontalAlignment.Left;
            panel.VerticalAlignment   = VerticalAlignment.Center;

            Label label = new Label();

            label.Content             = dna.ShipName;
            label.FontSize            = 14;
            label.FontWeight          = FontWeights.DemiBold;
            label.HorizontalAlignment = HorizontalAlignment.Left;
            label.VerticalAlignment   = VerticalAlignment.Center;
            panel.Children.Add(label);

            if (!string.IsNullOrEmpty(filename))
            {
                label                     = new Label();
                label.Content             = filename;
                label.FontSize            = 10;
                label.Foreground          = new SolidColorBrush(Color.FromRgb(96, 96, 96));
                label.HorizontalAlignment = HorizontalAlignment.Left;
                label.VerticalAlignment   = VerticalAlignment.Center;
                panel.Children.Add(label);
            }

            Grid.SetColumn(panel, 2);
            grid.Children.Add(panel);

            lstItems.Items.Add(grid);
            _currentDNA.Add(dna);
        }
コード例 #15
0
        public ShipSelectorWindow(ShipDNA[] dna, NewtonDynamics.World world)
            : this(world)
        {
            grdFolder.Visibility = Visibility.Collapsed;
            lblStatus.Visibility = Visibility.Collapsed;

            foreach (ShipDNA item in dna)
            {
                AddItem(item, null);
            }
        }
コード例 #16
0
ファイル: Egg.cs プロジェクト: charlierix/AsteroidMiner
        public Egg(Point3D position, World world, int materialID, ItemOptions itemOptions, ShipDNA dna)
        {
            // The radius should be 20% the size of the adult ship
            this.Radius = dna.PartsByLayer.SelectMany(o => o.Value).
                Max(o => o.Position.ToVector().Length + Math1D.Max(o.Scale.X, o.Scale.Y, o.Scale.Z))
                * .2d;

            Vector3D scale = new Vector3D(.75d, .75d, 1d);

            #region WPF Model

            // Material
            MaterialGroup materials = new MaterialGroup();
            materials.Children.Add(new DiffuseMaterial(new SolidColorBrush(WorldColors.EggColor)));
            materials.Children.Add(WorldColors.EggSpecular);

            // Geometry Model
            GeometryModel3D geometry = new GeometryModel3D();
            geometry.Material = materials;
            geometry.BackMaterial = materials;
            geometry.Geometry = UtilityWPF.GetSphere_LatLon(5, this.Radius);
            geometry.Transform = new ScaleTransform3D(scale);

            this.Model = geometry;

            // Model Visual
            ModelVisual3D model = new ModelVisual3D();
            model.Content = geometry;

            #endregion

            #region Physics Body

            Transform3DGroup transform = new Transform3DGroup();
            transform.Children.Add(new RotateTransform3D(new QuaternionRotation3D(Math3D.GetRandomRotation())));
            transform.Children.Add(new TranslateTransform3D(position.ToVector()));

            double volume = (4d / 3d) * Math.PI * scale.X * this.Radius * scale.Y * this.Radius * scale.Z * this.Radius;
            double mass = volume * itemOptions.Egg_Density;

            using (CollisionHull hull = CollisionHull.CreateSphere(world, 0, scale * this.Radius, null))
            {
                this.PhysicsBody = new Body(hull, transform.Value, mass, new Visual3D[] { model });
                this.PhysicsBody.MaterialGroupID = materialID;
                this.PhysicsBody.LinearDamping = .01f;
                this.PhysicsBody.AngularDamping = new Vector3D(.001f, .001f, .001f);
            }

            #endregion

            this.CreationTime = DateTime.UtcNow;
        }
コード例 #17
0
        private static string[] FindMissingParts(ShipDNA dna)
        {
            // Without this minimum list of parts, the ship won't work
            //TODO: When I come up with more sensor types, look for any type of sensor
            //NOTE: Brain isn't required if the sensor-thruster link multiplier has been increased, but I'll just say it's required
            string[] partList = new string[] { SensorGravity.PARTTYPE, Brain.PARTTYPE, EnergyTank.PARTTYPE, FuelTank.PARTTYPE, Thruster.PARTTYPE };

            // Get all the parts in the ship
            string[] usedParts = dna.PartsByLayer.Values.SelectMany(o => o).Select(o => o.PartType).Distinct().ToArray();

            // Return the missing ones
            return(partList.Where(o => !usedParts.Contains(o)).ToArray());
        }
コード例 #18
0
        /// <summary>
        /// This should get called on an infrequent basis, and randomize the available inventory
        /// </summary>
        public void RandomizeInventory(bool completelyNew)
        {
            RandomizePrices();

            if (completelyNew)
            {
                this.StationInventory.Clear();
            }

            List <Inventory> inventory = new List <Inventory>();

            // Ships
            inventory.AddRange(AdjustInventory(
                                   this.StationInventory.Where(o => o.Ship != null),
                                   3,
                                   () =>
            {
                DefaultShipType shipType = GetRandomItemChance(_shipChances).ShipType;
                ShipDNA shipDNA          = DefaultShips.GetDNA(shipType);
                return(new Inventory(shipDNA, StaticRandom.NextDouble(.5, 2)));
            }));


            // Parts
            inventory.AddRange(AdjustInventory(
                                   this.StationInventory.Where(o => o.Part != null),
                                   4,
                                   () =>
            {
                PartCreateChance partType = GetRandomItemChance(_partChances);
                ShipPartDNA partDNA       = GetRandomPart(partType);    //TODO: Have a chance to make 2 if it's something that could come in pairs (thruster, gun, etc)
                return(new Inventory(partDNA));
            }));

            // Minerals
            inventory.AddRange(AdjustInventory(
                                   this.StationInventory.Where(o => o.Mineral != null),
                                   4,
                                   () =>
            {
                MineralType type = UtilityCore.GetRandomEnum <MineralType>();
                double volume    = StaticRandom.NextPercent(ItemOptionsAstMin2D.MINERAL_AVGVOLUME, 2);
                return(new Inventory(ItemOptionsAstMin2D.GetMineral(type, volume)));
            }));

            this.StationInventory.Clear();
            this.StationInventory.AddRange(inventory);

            _inventoryRandomizeCountdown = StaticRandom.NextDouble(3 * 60, 8 * 60);
        }
コード例 #19
0
        public Icon3D(string name, ShipDNA dna, NewtonDynamics.World world)
        {
            InitializeComponent();

            this.ItemName = name;
            this.ShipDNA = dna;

            lblName.Text = name;
            lblName.Visibility = _showName ? Visibility.Visible : Visibility.Collapsed;

            InitializeTrackball();

            // Load the ship asyncronously
            FinishLoadingShipAsync(world);
        }
コード例 #20
0
        public Icon3D(string name, ShipDNA dna, NewtonDynamics.World world)
        {
            InitializeComponent();

            this.ItemName = name;
            this.ShipDNA  = dna;

            lblName.Text       = name;
            lblName.Visibility = _showName ? Visibility.Visible : Visibility.Collapsed;

            InitializeTrackball();

            // Load the ship asyncronously
            FinishLoadingShipAsync(world);
        }
コード例 #21
0
        public Inventory(ShipDNA ship, double scale)
        {
            ShipDNA scaledShip = scale.IsNearValue(1) ? ship : ShipDNA.Resize(ship, scale);

            this.Ship    = scaledShip;
            this.Part    = null;
            this.Mineral = null;

            this.Count = 1;

            //TODO: calculate these properly
            this.Volume = scale;
            this.Mass   = 1;

            this.Token = TokenGenerator.NextToken();
        }
コード例 #22
0
ファイル: Inventory.cs プロジェクト: charlierix/AsteroidMiner
        public Inventory(ShipDNA ship, double scale)
        {
            ShipDNA scaledShip = scale.IsNearValue(1) ? ship : ShipDNA.Resize(ship, scale);

            this.Ship = scaledShip;
            this.Part = null;
            this.Mineral = null;

            this.Count = 1;

            //TODO: calculate these properly
            this.Volume = scale;
            this.Mass = 1;

            this.Token = TokenGenerator.NextToken();
        }
コード例 #23
0
        public void Add(ShipDNA ship, double score)
        {
            lock (_lock)
            {
                if (!_list.ContainsKey(ship.ShipName))
                {
                    _list.Add(ship.ShipName, new List <Tuple <ShipDNA, double> >());
                }

                _list[ship.ShipName].Add(Tuple.Create(ship, score));

                if (_list[ship.ShipName].Count > MAX * 3)
                {
                    PurgeLowScores(_list[ship.ShipName]);
                }
            }
        }
コード例 #24
0
        public static ShipDNA LoadShip(out string errMsg)
        {
            string foldername = System.IO.Path.Combine(UtilityCore.GetOptionsFolder(), SHIPFOLDER);

            Directory.CreateDirectory(foldername);

            // Even if the folder is empty, they may want a folder nearby
            //if (!Directory.Exists(foldername) || Directory.GetFiles(foldername).Length == 0)
            //{
            //    errMsg = "No existing ships were found";
            //    return null;
            //}

            OpenFileDialog dialog = new OpenFileDialog();

            dialog.InitialDirectory = foldername;
            dialog.Multiselect      = false;
            dialog.Title            = "Please select a ship";
            bool?result = dialog.ShowDialog();

            if (result == null || !result.Value)
            {
                errMsg = "";
                return(null);
            }

            // Load the file
            object  deserialized = UtilityCore.DeserializeFromFile <ShipDNA>(dialog.FileName);
            ShipDNA retVal       = deserialized as ShipDNA;

            if (retVal == null && deserialized != null)
            {
                if (deserialized == null)
                {
                    errMsg = "Couldn't deserialize file";
                }
                else
                {
                    errMsg = string.Format("File is not a ShipDNA ({0})", deserialized.GetType().ToString());
                }
            }

            // Exit Function
            errMsg = "";
            return(retVal);
        }
コード例 #25
0
        public TrainingSession(ShipDNA dna, ShipExtraArgs shipExtraArgs, int inputCount, int outputCount, Func <WorldAccessor, TrainingRoom, IPhenomeTickEvaluator <IBlackBox, NeatGenome> > getNewEvaluator, int roomCount = 25, double roomSize = ROOMSIZE)
        {
            DNA           = dna;
            ShipExtraArgs = shipExtraArgs;

            double roomMargin = roomSize / 10;

            Arena = new ArenaAccessor(roomCount, roomSize, roomMargin, false, false, new Type[] { typeof(Bot) }, new Type[] { typeof(Bot) }, shipExtraArgs.NeuralPoolManual, (.1, .25));
            Arena.WorldCreated += Arena_WorldCreated;

            foreach (var(room, _) in Arena.AllRooms)
            {
                room.Evaluator = getNewEvaluator(Arena.WorldAccessor, room);
            }

            #region experiment args

            ExperimentInitArgs experimentArgs = new ExperimentInitArgs()
            {
                Description    = "Trains an individual BrainNEAT part",
                InputCount     = inputCount,
                OutputCount    = outputCount,
                IsHyperNEAT    = false,
                PopulationSize = roomCount,        // may want to do a few more than rooms in case extra are made
                SpeciesCount   = Math.Max(2, (roomCount / 4d).ToInt_Ceiling()),
                Activation     = GetActivationFunctionArgs(),
                Complexity_RegulationStrategy = ComplexityCeilingType.Absolute,
                Complexity_Threshold          = 200,
            };

            #endregion

            Experiment = new ExperimentNEATBase();

            // Use the overload that takes the tick phenome
            Experiment.Initialize("BrainNEAT Trainer", experimentArgs, Arena.AllRooms.Select(o => o.room.Evaluator).ToArray(), Arena.WorldAccessor.RoundRobinManager, Arena.WorldAccessor.UpdateWorld);

            EA = Experiment.CreateEvolutionAlgorithm();

            // look in AnticipatePositionWindow for an example.  The update event just displays stats
            //ea.UpdateEvent += EA_UpdateEvent;
            //ea.PausedEvent += EA_PausedEvent;
        }
コード例 #26
0
        /// <summary>
        /// This will return a constructed arcbot (arcbots have hardcoded dna)
        /// </summary>
        public static BotConstruction_Result GetConstruction(int level, ShipCoreArgs core, ShipExtraArgs extra, DragHitShape dragPlane, bool addHomingSensor)
        {
            BotConstructor_Events events = new BotConstructor_Events
            {
                InstantiateUnknownPart_Standard = InstantiateUnknownPart_Standard,
            };

            object[] botObjects = new object[]
            {
                new ArcBot2_ConstructionProps()
                {
                    DragPlane = dragPlane,
                    Level     = level,
                },
            };

            ShipDNA dna = GetDefaultDNA(addHomingSensor);

            return(BotConstructor.ConstructBot(dna, core, extra, events, botObjects));
        }
コード例 #27
0
        public virtual ShipDNA GetNewDNA()
        {
            // Create dna for each part using that part's current stats
            List <ShipPartDNA> dnaParts = new List <ShipPartDNA>();

            foreach (PartBase part in _parts.AllPartsArray)
            {
                ShipPartDNA dna = part.GetNewDNA();

                if (_neuronLinks != null && part is INeuronContainer)
                {
                    NeuralUtility.PopulateDNALinks(dna, (INeuronContainer)part, _neuronLinks);
                }

                dnaParts.Add(dna);
            }

            // Build the ship dna
            return(ShipDNA.Create(_dna, dnaParts));
        }
コード例 #28
0
        public ShipDNA Pop(string name)
        {
            lock (_lock)
            {
                if (!_list.ContainsKey(name))
                {
                    return(null);
                }

                var list = _list[name];

                double maxScore = double.MinValue;
                int    index    = -1;

                // Find the highest scorer
                for (int cntr = 0; cntr < list.Count; cntr++)
                {
                    if (list[cntr].Item2 > maxScore)
                    {
                        maxScore = list[cntr].Item2;
                        index    = cntr;
                    }
                }

                if (index < 0)
                {
                    return(null);
                }
                else
                {
                    // Pop it
                    ShipDNA retVal = list[index].Item1;
                    list.RemoveAt(index);

                    return(retVal);
                }
            }
        }
コード例 #29
0
        private static ShipDNA RotateDNA_DoIt(ShipDNA dna, Quaternion rotation, Transform3D positionTransform)
        {
            ShipDNA retVal = UtilityCore.Clone(dna);

            foreach (ShipPartDNA part in retVal.PartsByLayer.SelectMany(o => o.Value))
            {
                // Rotate the orientation
                //part.Orientation = part.Orientation.RotateBy(rotation);
                part.Orientation = rotation.RotateBy(part.Orientation);


                // Apply a transform to the poisition
                part.Position = positionTransform.Transform(part.Position);


                //TODO: See if these need to be rotated as well
                //part.Neurons;
                //part.ExternalLinks;
                //part.InternalLinks;
            }

            return(retVal);
        }
コード例 #30
0
        private void LoadShip()
        {
            string  errMsg;
            ShipDNA ship = LoadShip(out errMsg);

            if (ship == null)
            {
                if (!string.IsNullOrEmpty(errMsg))
                {
                    MessageBox.Show(errMsg, this.Title, MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }

            // Convert dna into design parts
            SortedList <int, List <DesignPart> > partsByLayer = new SortedList <int, List <DesignPart> >();

            foreach (int layerIndex in ship.PartsByLayer.Keys)
            {
                partsByLayer.Add(layerIndex, ship.PartsByLayer[layerIndex].Select(o => CreateDesignPart(o)).ToList());
            }

            // Show the ship
            editor1.SetDesign(ship.ShipName, ship.LayerNames, partsByLayer);
        }
コード例 #31
0
        private static ShipDNA GetDNAFromEditor(Editor editor)
        {
            // Get dna from editor
            string        name;
            List <string> layerNames;
            SortedList <int, List <DesignPart> > partsByLayer;

            editor.GetDesign(out name, out layerNames, out partsByLayer);

            // Create ship dna
            ShipDNA retVal = new ShipDNA()
            {
                ShipName     = name,
                LayerNames   = layerNames,
                PartsByLayer = new SortedList <int, List <ShipPartDNA> >(),
            };

            foreach (int layerIndex in partsByLayer.Keys)
            {
                retVal.PartsByLayer.Add(layerIndex, partsByLayer[layerIndex].Select(o => o.Part3D.GetDNA()).ToList());
            }

            return(retVal);
        }
コード例 #32
0
        private async void btnLoadShip_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string errMsg;
                ShipDNA shipDNA = ShipEditorWindow.LoadShip(out errMsg);
                if (shipDNA == null)
                {
                    if (!string.IsNullOrEmpty(errMsg))
                    {
                        MessageBox.Show(errMsg, this.Title, MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                    return;
                }

                EnsureWorldStarted();

                ShipCoreArgs core = new ShipCoreArgs()
                {
                    Map = _map,
                    Material_Ship = _material_Bot,
                    World = _world,
                };

                ShipExtraArgs extra = new ShipExtraArgs()
                {
                    Options = _editorOptions,
                    ItemOptions = _itemOptions,
                    Material_Projectile = _material_Bot,
                    Radiation = _radiation,
                    Gravity = _gravity,
                    RunNeural = false,
                    RepairPartPositions = chkLoadRepairPositions.IsChecked.Value,
                };

                //Ship ship = await Ship.GetNewShipAsync(shipDNA, _world, _material_Bot, _map, extra);
                Bot bot = new Bot(BotConstructor.ConstructBot(shipDNA, core, extra));

                ClearCurrent();

                _shipDNA = shipDNA;
                _bot = bot;

                _bot.PhysicsBody.ApplyForceAndTorque += new EventHandler<BodyApplyForceAndTorqueArgs>(Ship_ApplyForceAndTorque);

                _thrustController = new ThrustController(_bot, _viewport, _itemOptions);

                if (_bot.Fuel != null)
                {
                    _bot.Fuel.QuantityCurrent = _bot.Fuel.QuantityMax;
                }
                _bot.RecalculateMass();
                _thrustController.MassChanged(chkShipSimple.IsChecked.Value);

                if (chkShipDebugVisuals.IsChecked.Value)
                {
                    _thrustController.DrawDebugVisuals_Pre();
                }

                _map.AddItem(_bot);

                grdViewPort.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
コード例 #33
0
        public Bot(BotConstruction_Result construction)
        {
            _options     = construction.ArgsExtra.Options;
            _itemOptions = construction.ArgsExtra.ItemOptions;

            _radiation  = construction.ArgsExtra.Radiation;
            _gravity    = construction.ArgsExtra.Gravity;
            _cameraPool = construction.ArgsExtra.CameraPool;

            _parts                     = construction.PartConstruction;
            _thrusters                 = construction.PartConstruction.GetStandardParts <Thruster>(Thruster.PARTTYPE).ToArray();
            _impulseEngines            = construction.PartConstruction.GetStandardParts <ImpulseEngine>(ImpulseEngine.PARTTYPE).ToArray();
            _projectileGuns            = construction.PartConstruction.GetStandardParts <ProjectileGun>(ProjectileGun.PARTTYPE).ToArray();
            _updatableParts_MainThread = construction.UpdatableParts_MainThread;
            _updatableParts_AnyThread  = construction.UpdatableParts_AnyThread;
            _dna      = construction.DNA;
            _dnaParts = construction.DNAParts;

            this.Model     = construction.Model;
            _visualEffects = construction.VisualEffects;

            _isPhysicsStatic = construction.ArgsExtra.IsPhysicsStatic;
            this.PhysicsBody = construction.PhysicsBody;

            this.Radius = construction.Radius;

            _partTransformToModel = _parts.AllPartsArray.
                                    Select(o =>
            {
                Transform3DGroup transform = new Transform3DGroup();
                transform.Children.Add(new TranslateTransform3D(-o.Position.ToVector()));
                transform.Children.Add(new RotateTransform3D(new QuaternionRotation3D(o.Orientation.ToReverse())));
                return(transform);
            }).
                                    ToArray();

            // Hook up events
            if (!_isPhysicsStatic)
            {
                this.PhysicsBody.ApplyForceAndTorque += new EventHandler <BodyApplyForceAndTorqueArgs>(PhysicsBody_ApplyForceAndTorque);
            }

            foreach (var part in _parts.AllPartsArray)
            {
                part.RequestWorldLocation += new EventHandler <PartRequestWorldLocationArgs>(Part_RequestWorldLocation);
                part.RequestWorldSpeed    += new EventHandler <PartRequestWorldSpeedArgs>(Part_RequestWorldSpeed);
                part.RequestParent        += new EventHandler <PartRequestParentArgs>(Part_RequestParent);

                part.Resurrected += Part_Resurrected;
                part.Destroyed   += Part_Destroyed;
            }

            // See if there are parts that can gradually change the ship's mass
            if ((_parts.Containers.Fuels.Count > 0 && _parts.StandardParts.ContainsKey(Thruster.PARTTYPE)) ||
                (_parts.Containers.CargoBays.Count > 0 && (_parts.StandardParts.ContainsKey(ConverterMatterToEnergy.PARTTYPE) || _parts.StandardParts.ContainsKey(ConverterMatterToFuel.PARTTYPE))) ||
                (_parts.Containers.Energies.Count > 0 && _parts.Containers.Fuels.Count > 0 && (_parts.StandardParts.ContainsKey(ConverterEnergyToFuel.PARTTYPE) || _parts.StandardParts.ContainsKey(ConverterFuelToEnergy.PARTTYPE)))
                )
            {
                _hasMassChangingUpdatables_Small = true;
            }
            else
            {
                _hasMassChangingUpdatables_Small = false;
            }

            if (_parts.Containers.Ammos.Count > 0 && _parts.StandardParts.ContainsKey(ProjectileGun.PARTTYPE))
            {
                _hasMassChangingUpdatables_Medium = true;
            }
            else
            {
                _hasMassChangingUpdatables_Medium = false;
            }

            // Set up a neural processor on its own thread/task
            _neuronLinks = construction.Links;
            if (_neuronLinks != null)
            {
                var result = AddToNeuralPool(_neuronLinks, construction.ArgsExtra.NeuralPoolManual);
                _linkBucket           = result.bucket;
                _neuralPoolAddTask    = result.addTask;
                _neuralPoolManualTick = result.manualPool;
            }

            _lifeEvents = construction.PartConstruction.LifeEventWatcher;

            this.ShouldRecalcMass_Large = false;
            this.ShouldRecalcMass_Small = false;

            this.CreationTime = DateTime.UtcNow;
        }
コード例 #34
0
        private async void btnShipBasic_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                EnsureWorldStarted();
                ClearCurrent();

                List<ShipPartDNA> parts = new List<ShipPartDNA>();
                parts.Add(new ShipPartDNA() { PartType = FuelTank.PARTTYPE, Position = new Point3D(-.75, 0, 0), Orientation = Quaternion.Identity, Scale = new Vector3D(1, 1, 1) });
                parts.Add(new ShipPartDNA() { PartType = EnergyTank.PARTTYPE, Position = new Point3D(.75, 0, 0), Orientation = Quaternion.Identity, Scale = new Vector3D(1, 1, 1) });

                ShipDNA shipDNA = ShipDNA.Create(parts);

                ShipCoreArgs core = new ShipCoreArgs()
                {
                    Map = _map,
                    Material_Ship = _material_Bot,
                    World = _world,
                };

                ShipExtraArgs extra = new ShipExtraArgs()
                {
                    Options = _editorOptions,
                    ItemOptions = _itemOptions,
                    Material_Projectile = _material_Bot,
                    Radiation = _radiation,
                    Gravity = _gravity,
                    RunNeural = false,
                    RepairPartPositions = false,
                };

                //Ship ship = await Ship.GetNewShipAsync(shipDNA, _world, _material_Ship, _map, extra);
                Bot bot = new Bot(BotConstructor.ConstructBot(shipDNA, core, extra));

                ClearCurrent();

                _shipDNA = shipDNA;
                _bot = bot;

                _map.AddItem(_bot);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
コード例 #35
0
        private static ShipDNA GetDNAFromEditor(Editor editor)
        {
            // Get dna from editor
            string name;
            List<string> layerNames;
            SortedList<int, List<DesignPart>> partsByLayer;
            editor.GetDesign(out name, out layerNames, out partsByLayer);

            // Create ship dna
            ShipDNA retVal = new ShipDNA()
            {
                ShipName = name,
                LayerNames = layerNames,
                PartsByLayer = new SortedList<int, List<ShipPartDNA>>(),
            };

            foreach (int layerIndex in partsByLayer.Keys)
            {
                retVal.PartsByLayer.Add(layerIndex, partsByLayer[layerIndex].Select(o => o.Part3D.GetDNA()).ToList());
            }

            return retVal;
        }
コード例 #36
0
        public static void Load(out FlyingBeanSession session, out FlyingBeanOptions options, out ItemOptions itemOptions, out ShipDNA[] winningBeans, string baseFolder, string saveFolder)
        {
            #region Session

            string filename = Path.Combine(baseFolder, FILENAME_SESSION);
            if (File.Exists(filename))
            {
                session = UtilityCore.DeserializeFromFile <FlyingBeanSession>(filename);
            }
            else
            {
                session = new FlyingBeanSession();
            }

            #endregion

            #region FlyingBeanOptions

            filename = Path.Combine(saveFolder, FILENAME_OPTIONS);
            if (File.Exists(filename))
            {
                options = UtilityCore.DeserializeFromFile <FlyingBeanOptions>(filename);
            }
            else
            {
                //options = new FlyingBeanOptions();
                throw new ArgumentException("Didn't find " + FILENAME_OPTIONS + "\r\n\r\nThe folder might not be a valid save folder");
            }

            #endregion

            // This currently isn't stored to file
            session = new FlyingBeanSession();

            #region ItemOptions

            filename = Path.Combine(saveFolder, FILENAME_ITEMOPTIONS);
            if (File.Exists(filename))
            {
                itemOptions = UtilityCore.DeserializeFromFile <ItemOptions>(filename);
            }
            else
            {
                itemOptions = new ItemOptions();
            }

            #endregion

            #region Winning Beans

            List <Tuple <string, ShipDNA> > winners = new List <Tuple <string, ShipDNA> >();

            foreach (string filename2 in Directory.GetFiles(saveFolder))
            {
                Match match = Regex.Match(Path.GetFileName(filename2), @"^(.+?( - )){2}(?<rank>\d+)\.xml$", RegexOptions.IgnoreCase);
                if (!match.Success)
                {
                    continue;
                }

                // All other xml files should be winning beans
                ShipDNA dna = null;
                try
                {
                    dna = UtilityCore.DeserializeFromFile <ShipDNA>(filename2);
                }
                catch (Exception)
                {
                    // Must not be a ship
                    continue;
                }

                winners.Add(Tuple.Create(Path.GetFileName(filename2), dna));
            }

            winningBeans = winners.Select(o => o.Item2).ToArray();

            #endregion

            // WinnersFinal
            options.WinnersFinal = MergeHistory(options.WinningScores, winners, options.TrackingMaxLineagesFinal, options.TrackingMaxPerLineageFinal);
        }
コード例 #37
0
        private void ClearCurrent()
        {
            ClearBalanceVisualizer();

            foreach (Visual3D visual in _currentVisuals)
            {
                _viewport.Children.Remove(visual);
            }
            _currentVisuals.Clear();

            if (_currentBody != null)
            {
                _currentBody.Dispose();
                _currentBody = null;
            }

            if (_bot != null)
            {
                _map.RemoveItem(_bot, true);
                _bot.Dispose();
                _bot = null;
            }

            _shipDNA = null;

            if (_thrustController != null)
            {
                _thrustController.Dispose();
                _thrustController = null;
            }
        }
コード例 #38
0
        public void Add(ShipDNA ship, double score)
        {
            lock (_lock)
            {
                if (!_list.ContainsKey(ship.ShipName))
                {
                    _list.Add(ship.ShipName, new List<Tuple<ShipDNA, double>>());
                }

                _list[ship.ShipName].Add(Tuple.Create(ship, score));

                if (_list[ship.ShipName].Count > MAX * 3)
                {
                    PurgeLowScores(_list[ship.ShipName]);
                }
            }
        }
コード例 #39
0
        private async Task<Bean> AddBeanAsync(ShipDNA dna)
        {
            ShipCoreArgs core = new ShipCoreArgs()
            {
                //Map = _map,       // this wasn't passed in when it was a ship
                Material_Ship = _material_Bean,
                World = _world,
            };

            ShipExtraArgs args = new ShipExtraArgs()
            {
                Options = _editorOptions,
                ItemOptions = _itemOptions,
                Material_Projectile = _material_Projectile,
                Radiation = _radiation,
                Gravity = _options.GravityField,
            };

            //Bean retVal = await Bean.GetNewBeanAsync(dna, _world, _material_Bean, args, _options);
            var seed = BotConstructor.ConstructBot(dna, core, args);
            Bean retVal = new Bean(seed, _options);

            //retVal.PhysicsBody.AngularDamping = new Vector3D(1, 1, 1);
            retVal.PhysicsBody.ApplyForceAndTorque += new EventHandler<BodyApplyForceAndTorqueArgs>(Bean_ApplyForceAndTorque);
            retVal.Dead += new EventHandler<DeadBeanArgs>(Bean_Dead);

            if (_options.NewBeanRandomOrientation)
            {
                retVal.PhysicsBody.Rotation = Math3D.GetRandomRotation();
            }

            if (_options.NewBeanRandomSpin)
            {
                Vector3D angularVelocity = Math3D.GetRandomVector_Spherical_Shell(1d);
                angularVelocity *= _options.AngularVelocityDeath * .5d;

                retVal.PhysicsBody.AngularVelocity = angularVelocity;
            }

            if (retVal.Energy != null)
            {
                retVal.Energy.QuantityCurrent = retVal.Energy.QuantityMax;
            }
            if (retVal.Fuel != null)
            {
                retVal.Fuel.QuantityCurrent = retVal.Fuel.QuantityMax;
            }
            retVal.RecalculateMass();

            Vector3D position = Math3D.GetRandomVector_Circular(TERRAINRADIUS * .5d);
            retVal.PhysicsBody.Position = new Point3D(position.X, position.Y, STARTHEIGHT);

            _map.AddItem(retVal);
            _beans.Add(retVal);

            _options.TotalBeans++;
            this.TotalBeansText = _options.TotalBeans.ToString("N0");

            return retVal;
        }
コード例 #40
0
        public static void SaveShip(ShipDNA ship)
        {
            //TODO: Store these in a database (RavenDB), fail over to storing on file if can't connect to DB


            // Make sure the folder exists
            string foldername = System.IO.Path.Combine(UtilityCore.GetOptionsFolder(), SHIPFOLDER);
            if (!Directory.Exists(foldername))
            {
                Directory.CreateDirectory(foldername);
            }

            //string xamlText = XamlWriter.Save(ship);		// this is the old one, it doesn't like generic lists
            string xamlText = XamlServices.Save(ship);

            int infiniteLoopDetector = 0;
            while (true)
            {
                char[] illegalChars = System.IO.Path.GetInvalidFileNameChars();
                string filename = new string(ship.ShipName.Select(o => illegalChars.Contains(o) ? '_' : o).ToArray());
                filename = DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss.fff") + " - " + filename + ".xml";
                filename = System.IO.Path.Combine(foldername, filename);

                try
                {
                    using (StreamWriter writer = new StreamWriter(new FileStream(filename, FileMode.CreateNew)))
                    {
                        writer.Write(xamlText);
                        break;
                    }
                }
                catch (IOException ex)
                {
                    infiniteLoopDetector++;
                    if (infiniteLoopDetector > 100)
                    {
                        throw new ApplicationException("Couldn't create the file\r\n" + filename, ex);
                    }
                }
            }
        }
コード例 #41
0
        private static ShipDNA RotateDNA_DoIt(ShipDNA dna, Quaternion rotation, Transform3D positionTransform)
        {
            ShipDNA retVal = UtilityCore.Clone(dna);

            foreach (ShipPartDNA part in retVal.PartsByLayer.SelectMany(o => o.Value))
            {
                // Rotate the orientation
                //part.Orientation = part.Orientation.RotateBy(rotation);
                part.Orientation = rotation.RotateBy(part.Orientation);


                // Apply a transform to the poisition
                part.Position = positionTransform.Transform(part.Position);


                //TODO: See if these need to be rotated as well
                //part.Neurons;
                //part.ExternalLinks;
                //part.InternalLinks;
            }

            return retVal;
        }
コード例 #42
0
        private static string GetName_Ship(ShipDNA dna)
        {
            string retVal = dna.ShipName;

            if (string.IsNullOrWhiteSpace(retVal))
            {
                retVal = dna.ShipLineage ?? "";
            }

            retVal = retVal.Trim();

            return retVal;
        }
コード例 #43
0
        private static ShipDNA RotateDNA_ToExternal(ShipDNA dna)
        {
            Quaternion quat = new Quaternion(new Vector3D(1, 0, 0), 90);

            RotateTransform3D rotation = new RotateTransform3D(new QuaternionRotation3D(quat));

            return RotateDNA_DoIt(dna, quat, rotation);
        }
コード例 #44
0
        private static ShipDNA RotateDNA_FromExternal(ShipDNA dna)
        {
            Quaternion quat = new Quaternion(new Vector3D(1, 0, 0), -90);

            RotateTransform3D rotation = new RotateTransform3D(new QuaternionRotation3D(quat));


            //double sqrt2div2 = Math.Sqrt(2d) / 2d;
            //Quaternion orig = new Quaternion(0, -sqrt2div2, 0, sqrt2div2);
            //Quaternion rotated = orig.RotateBy(quat);
            //Quaternion rotated3 = quat.RotateBy(orig);


            //Vector3D z = new Vector3D(0, 0, 1);
            //Vector3D zOrig = orig.GetRotatedVector(z);
            //Vector3D zRot = rotated.GetRotatedVector(z);
            //Vector3D zRot3 = rotated3.GetRotatedVector(z);


            //Transform3DGroup group = new Transform3DGroup();
            //group.Children.Add(new RotateTransform3D(new QuaternionRotation3D(orig)));
            //group.Children.Add(new RotateTransform3D(new QuaternionRotation3D(quat)));

            //Vector3D zRot2 = group.Transform(z);


            //Thruster testThrust = new Thruster();


            return RotateDNA_DoIt(dna, quat, rotation);
        }
コード例 #45
0
        public static ShipPlayer GetNewShip(ShipDNA dna, World world, int material_Ship, Map map, ShipExtraArgs extra)
        {
            ShipDNA rotatedDNA = RotateDNA_FromExternal(dna);

            #region asserts

            //ShipDNA rockedDNA1 = RotateDNA_ToExternal(RotateDNA_FromExternal(dna));
            //ShipDNA rockedDNA2 = RotateDNA_FromExternal(rockedDNA1);

            //var compare1a = dna.PartsByLayer.SelectMany(o => o.Value).ToArray();
            //var compare1b = rockedDNA1.PartsByLayer.SelectMany(o => o.Value).ToArray();

            //var compare2a = rotatedDNA.PartsByLayer.SelectMany(o => o.Value).ToArray();
            //var compare2b = rockedDNA2.PartsByLayer.SelectMany(o => o.Value).ToArray();

            //for(int cntr = 0; cntr < compare1a.Length; cntr++)
            //{
            //    var com1a = compare1a[cntr];
            //    var com1b = compare1b[cntr];

            //    var com2a = compare2a[cntr];
            //    var com2b = compare2b[cntr];

            //    if(!Math3D.IsNearValue(com1a.Position, com1b.Position))
            //    {
            //        int three = 3;
            //    }
            //    if (!Math3D.IsNearValue(com1a.Orientation, com1b.Orientation))
            //    {
            //        int three = 3;
            //    }

            //    if (!Math3D.IsNearValue(com2a.Position, com2b.Position))
            //    {
            //        int four = 4;
            //    }
            //    if (!Math3D.IsNearValue(com2a.Orientation, com2b.Orientation))
            //    {
            //        int four = 4;
            //    }
            //}

            #endregion

            ShipCoreArgs core = new ShipCoreArgs()
            {
                Map = map,
                Material_Ship = material_Ship,
                World = world,
            };

            //var construction = await GetNewShipConstructionAsync(options, itemOptions, rotatedDNA, world, material_Ship, material_Projectile, radiation, gravity, cameraPool, map, true, true);
            //var construction = await GetNewShipConstructionAsync(rotatedDNA, world, material_Ship, map, extra);
            var construction = BotConstructor.ConstructBot(rotatedDNA, core, extra);

            return new ShipPlayer(construction);
        }
コード例 #46
0
 public TrackingCandidate(ShipDNA dna)
 {
     this.DNA = dna;
     this.Token = TokenGenerator.NextToken();
 }
コード例 #47
0
        private void SaveShip()
        {
            // Get ship from the editor
            string name;		// the editor returns this trimmed
            List<string> layerNames;
            SortedList<int, List<DesignPart>> partsByLayer;
            editor1.GetDesign(out name, out layerNames, out partsByLayer);

            if (name == "")
            {
                MessageBox.Show("Please give the ship a name first", this.Title, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // Get the definition of the ship
            ShipDNA ship = new ShipDNA();
            ship.ShipName = name;
            //TODO: Validate the ship
            //ship.IsValid = 
            ship.LayerNames = layerNames;
            ship.PartsByLayer = new SortedList<int, List<ShipPartDNA>>();
            foreach (int layerIndex in partsByLayer.Keys)
            {
                ship.PartsByLayer.Add(layerIndex, partsByLayer[layerIndex].Select(o => o.Part3D.GetDNA()).ToList());
            }

            SaveShip(ship);
        }
コード例 #48
0
ファイル: Bot.cs プロジェクト: charlierix/AsteroidMiner
        public Bot(BotConstruction_Result construction)
        {
            _options = construction.ArgsExtra.Options;
            _itemOptions = construction.ArgsExtra.ItemOptions;

            _radiation = construction.ArgsExtra.Radiation;
            _gravity = construction.ArgsExtra.Gravity;
            _cameraPool = construction.ArgsExtra.CameraPool;

            _parts = construction.PartConstruction;
            _thrusters = construction.PartConstruction.GetStandardParts<Thruster>(Thruster.PARTTYPE).ToArray();
            _projectileGuns = construction.PartConstruction.GetStandardParts<ProjectileGun>(ProjectileGun.PARTTYPE).ToArray();
            _updatableParts_MainThread = construction.UpdatableParts_MainThread;
            _updatableParts_AnyThread = construction.UpdatableParts_AnyThread;
            _dna = construction.DNA;
            _dnaParts = construction.DNAParts;

            this.Model = construction.Model;
            _visualEffects = construction.VisualEffects;

            _isPhysicsStatic = construction.ArgsExtra.IsPhysicsStatic;
            this.PhysicsBody = construction.PhysicsBody;

            this.Radius = construction.Radius;

            _partTransformToModel = _parts.AllPartsArray.
                Select(o =>
                {
                    Transform3DGroup transform = new Transform3DGroup();
                    transform.Children.Add(new TranslateTransform3D(-o.Position.ToVector()));
                    transform.Children.Add(new RotateTransform3D(new QuaternionRotation3D(o.Orientation.ToReverse())));
                    return transform;
                }).
                ToArray();

            // Hook up events
            if (!_isPhysicsStatic)
            {
                this.PhysicsBody.ApplyForceAndTorque += new EventHandler<BodyApplyForceAndTorqueArgs>(PhysicsBody_ApplyForceAndTorque);
            }

            foreach (var part in _parts.AllPartsArray)
            {
                part.RequestWorldLocation += new EventHandler<PartRequestWorldLocationArgs>(Part_RequestWorldLocation);
                part.RequestWorldSpeed += new EventHandler<PartRequestWorldSpeedArgs>(Part_RequestWorldSpeed);
                part.RequestParent += new EventHandler<PartRequestParentArgs>(Part_RequestParent);

                part.Resurrected += Part_Resurrected;
                part.Destroyed += Part_Destroyed;
            }

            // See if there are parts that can gradually change the ship's mass
            if ((_parts.Containers.Fuels.Count > 0 && _parts.StandardParts.ContainsKey(Thruster.PARTTYPE)) ||
                (_parts.Containers.CargoBays.Count > 0 && (_parts.StandardParts.ContainsKey(ConverterMatterToEnergy.PARTTYPE) || _parts.StandardParts.ContainsKey(ConverterMatterToFuel.PARTTYPE))) ||
                (_parts.Containers.Energies.Count > 0 && _parts.Containers.Fuels.Count > 0 && (_parts.StandardParts.ContainsKey(ConverterEnergyToFuel.PARTTYPE) || _parts.StandardParts.ContainsKey(ConverterFuelToEnergy.PARTTYPE)))
                )
            {
                _hasMassChangingUpdatables_Small = true;
            }
            else
            {
                _hasMassChangingUpdatables_Small = false;
            }

            if (_parts.Containers.Ammos.Count > 0 && _parts.StandardParts.ContainsKey(ProjectileGun.PARTTYPE))
            {
                _hasMassChangingUpdatables_Medium = true;
            }
            else
            {
                _hasMassChangingUpdatables_Medium = false;
            }

            // Set up a neural processor on its own thread/task
            _neuronLinks = construction.Links;
            if (_neuronLinks != null)
            {
                var bucketTask = AddToNeuralPool(_neuronLinks);
                _neuralPoolAddTask = bucketTask.Item1;
                _linkBucket = bucketTask.Item2;
            }

            _lifeEvents = construction.PartConstruction.LifeEventWatcher;

            this.ShouldRecalcMass_Large = false;
            this.ShouldRecalcMass_Small = false;

            this.CreationTime = DateTime.UtcNow;
        }
コード例 #49
0
        private async void btnShipChallenge2_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                EnsureWorldStarted();
                ClearCurrent();

                List<ShipPartDNA> parts = new List<ShipPartDNA>();
                parts.Add(new ShipPartDNA() { PartType = FuelTank.PARTTYPE, Position = new Point3D(0.611527511599856, 0, 0.0153375982352619), Orientation = new Quaternion(0, -0.706493084706277, 0, 0.707719945502605), Scale = new Vector3D(4.70545346938791, 4.70545346938791, 1.04748080326409) });
                parts.Add(new ThrusterDNA() { PartType = Thruster.PARTTYPE, Position = new Point3D(-1.48216852903668, 0, 0), Orientation = Quaternion.Identity, Scale = new Vector3D(1.65021551755816, 1.65021551755816, 1.65021551755816), ThrusterDirections = ThrusterDesign.GetThrusterDirections(ThrusterType.Two), ThrusterType = ThrusterType.Two });
                parts.Add(new ThrusterDNA() { PartType = Thruster.PARTTYPE, Position = new Point3D(-2.60730396412872, 1.18811621237628, -0.0147591913688635), Orientation = new Quaternion(0, 0, -0.846976393198269, 0.531630500784946), Scale = new Vector3D(0.71390056433019, 0.71390056433019, 0.71390056433019), ThrusterDirections = ThrusterDesign.GetThrusterDirections(ThrusterType.Two_Two_One), ThrusterType = ThrusterType.Two_Two_One });
                parts.Add(new ThrusterDNA() { PartType = Thruster.PARTTYPE, Position = new Point3D(-2.60721450068017, -1.18828382189838, -0.0147591913688617), Orientation = new Quaternion(0, 0, -0.496864090131338, 0.867828367788216), Scale = new Vector3D(0.71390056433019, 0.71390056433019, 0.71390056433019), ThrusterDirections = ThrusterDesign.GetThrusterDirections(ThrusterType.Two_Two_One), ThrusterType = ThrusterType.Two_Two_One });

                ShipDNA shipDNA = ShipDNA.Create(parts);

                ShipCoreArgs core = new ShipCoreArgs()
                {
                    Map = _map,
                    Material_Ship = _material_Bot,
                    World = _world,
                };

                ShipExtraArgs extra = new ShipExtraArgs()
                {
                    Options = _editorOptions,
                    ItemOptions = _itemOptions,
                    Material_Projectile = _material_Bot,
                    Radiation = _radiation,
                    Gravity = _gravity,
                    RunNeural = false,
                    RepairPartPositions = false,
                };

                //Ship ship = await Ship.GetNewShipAsync(shipDNA, _world, _material_Bot, _map, extra);
                Bot bot = new Bot(BotConstructor.ConstructBot(shipDNA, core, extra));

                ClearCurrent();

                _shipDNA = shipDNA;
                _bot = bot;

                _bot.PhysicsBody.ApplyForceAndTorque += new EventHandler<BodyApplyForceAndTorqueArgs>(Ship_ApplyForceAndTorque);

                _thrustController = new ThrustController(_bot, _viewport, _itemOptions);

                //double mass = _ship.PhysicsBody.Mass;

                _bot.Fuel.QuantityCurrent = _bot.Fuel.QuantityMax;
                _bot.RecalculateMass();
                _thrustController.MassChanged(chkShipSimple.IsChecked.Value);

                if (chkShipDebugVisuals.IsChecked.Value)
                {
                    _thrustController.DrawDebugVisuals_Pre();
                }

                //mass = _ship.PhysicsBody.Mass;

                _map.AddItem(_bot);

                grdViewPort.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
コード例 #50
0
 public TrackingCandidate(ShipDNA dna)
 {
     this.DNA   = dna;
     this.Token = TokenGenerator.NextToken();
 }
コード例 #51
0
        private static ShipDNA GetDefaultDNA(bool addHomingSensor)
        {
            // Create bot dna (remember the unique ID of the brainneat part)
            var parts = new List <ShipPartDNA>();

            #region misc

            // If there are more than one, give each a unique guid to know which to train (only want to train one at a time)
            parts.Add(new BrainNEATDNA()
            {
                PartType    = BrainNEAT.PARTTYPE,
                Position    = new Point3D(0, 0, 0),
                Orientation = Quaternion.Identity,
                Scale       = new Vector3D(1, 1, 1)
            });

            parts.Add(new ShipPartDNA()
            {
                PartType    = MotionController2.PARTTYPE,
                Position    = new Point3D(0, 0, -.65),
                Orientation = Quaternion.Identity,
                Scale       = new Vector3D(.75, .75, .75)
            });

            #endregion

            #region cargo parts

            // These go in a ring around the brain

            const double RING_Z = 0;

            Point3D[] positions_cargo = Math3D.GetRandomVectors_Circular_EvenDist(3, .66).
                                        Select(o => o.ToPoint3D(RING_Z)).
                                        ToArray();

            Point3D pointTo = new Point3D(0, 0, RING_Z);

            // Make the cargo bay long, because it's storing pole arms
            Vector3D cargo_vect  = pointTo - positions_cargo[0];
            Vector3D cargo_vectX = Vector3D.CrossProduct(cargo_vect, new Vector3D(0, 1, 0));
            Vector3D cargo_vectY = pointTo - positions_cargo[0];

            parts.Add(new ShipPartDNA()
            {
                PartType    = CargoBay.PARTTYPE,
                Position    = positions_cargo[0],
                Orientation = Math3D.GetRotation(new DoubleVector(1, 0, 0, 0, 1, 0), new DoubleVector(cargo_vectX, cargo_vectY)),       // need a double vector because the cargo bay is a box.  The other two are cylinders, so it doesn't matter which way the orth vector is pointing
                Scale       = new Vector3D(.35, .15, 1.35)
            });

            parts.Add(new ShipPartDNA()
            {
                PartType    = EnergyTank.PARTTYPE,
                Position    = positions_cargo[1],
                Orientation = Math3D.GetRotation(new Vector3D(0, 0, 1), pointTo - positions_cargo[1]),
                Scale       = new Vector3D(.6, .6, .15)
            });

            parts.Add(new ShipPartDNA()
            {
                PartType    = PlasmaTank.PARTTYPE,
                Position    = positions_cargo[2],
                Orientation = Math3D.GetRotation(new Vector3D(0, 0, 1), pointTo - positions_cargo[2]),
                Scale       = new Vector3D(.6, .6, .15)
            });

            #endregion

            #region sensors

            int sensorCount = 2;
            if (addHomingSensor)
            {
                sensorCount++;
            }

            Point3D[] positions_sensor = Math3D.GetRandomVectors_Cone_EvenDist(sensorCount, new Vector3D(0, 0, 1), 40, 1.1, 1.1).
                                         Select(o => o.ToPoint() + new Vector3D(0, 0, -.3)).
                                         ToArray();

            // Vision Far
            parts.Add(new SensorVisionDNA()
            {
                PartType     = SensorVision.PARTTYPE,
                Position     = positions_sensor[0],
                Orientation  = Quaternion.Identity,
                Scale        = new Vector3D(1, 1, 1),
                SearchRadius = 60,
                Filters      = new[]
                {
                    SensorVisionFilterType.Nest,
                    SensorVisionFilterType.Bot_Family,
                    SensorVisionFilterType.Bot_Other,
                    SensorVisionFilterType.TreasureBox,
                    SensorVisionFilterType.Weapon_FreeFloating,
                },
            });

            // Vision Near
            parts.Add(new SensorVisionDNA()
            {
                PartType     = SensorVision.PARTTYPE,
                Position     = positions_sensor[1],
                Orientation  = Quaternion.Identity,
                Scale        = new Vector3D(1, 1, 1),
                SearchRadius = 12,
                Filters      = new[]
                {
                    SensorVisionFilterType.Bot_Family,
                    SensorVisionFilterType.Bot_Other,
                    SensorVisionFilterType.Weapon_Attached_Personal,
                    SensorVisionFilterType.Weapon_Attached_Other,
                },
            });

            // Homing
            if (addHomingSensor)
            {
                parts.Add(new ShipPartDNA()
                {
                    PartType    = SensorHoming.PARTTYPE,
                    Position    = positions_sensor[2],
                    Orientation = Quaternion.Identity,
                    Scale       = new Vector3D(1, 1, 1)
                });
            }


            //new ShipPartDNA() { PartType = SensorVision.PARTTYPE, Position = new Point3D(0, 0, 1.5), Orientation = Quaternion.Identity, Scale = new Vector3D(1, 1, 1) },
            //new ShipPartDNA() { PartType = SensorCollision.PARTTYPE, Position = new Point3D(-sensorXY, sensorXY, sensorZ), Orientation = new Quaternion(halfSqrt2,0,0,halfSqrt2), Scale = new Vector3D(1, 1, 1) },
            //new ShipPartDNA() { PartType = SensorHoming.PARTTYPE, Position = new Point3D(-sensorXY, -sensorXY, sensorZ), Orientation = new Quaternion(halfSqrt2,0,0,halfSqrt2), Scale = new Vector3D(1, 1, 1) },
            //new ShipPartDNA() { PartType = SensorVelocity.PARTTYPE, Position = new Point3D(sensorXY, -sensorXY, sensorZ), Orientation = new Quaternion(halfSqrt2,0,0,halfSqrt2), Scale = new Vector3D(1, 1, 1) },

            // gravity is constant, so the only reason it would be needed is if the bot spins around
            //new ShipPartDNA() { PartType = SensorGravity.PARTTYPE, Position = new Point3D(sensorXY, sensorXY, sensorZ), Orientation = new Quaternion(halfSqrt2,0,0,halfSqrt2), Scale = new Vector3D(1, 1, 1) },

            // SensorPain

            #endregion

            return(ShipDNA.Create("ArcBot2", parts));
        }
コード例 #52
0
        private async void btnShipWackyFlyer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                EnsureWorldStarted();
                ClearCurrent();

                List<ShipPartDNA> parts = new List<ShipPartDNA>();
                parts.Add(new ShipPartDNA() { PartType = FuelTank.PARTTYPE, Position = new Point3D(0, 0, 0), Orientation = Quaternion.Identity, Scale = new Vector3D(3, 3, 1) });

                ThrusterType thrustType = UtilityCore.GetRandomEnum<ThrusterType>(ThrusterType.Custom);
                parts.Add(new ThrusterDNA() { PartType = Thruster.PARTTYPE, Position = new Point3D(1, 0, 0), Orientation = Math3D.GetRandomRotation(), Scale = new Vector3D(.5d, .5d, .5d), ThrusterDirections = ThrusterDesign.GetThrusterDirections(thrustType), ThrusterType = thrustType });

                thrustType = UtilityCore.GetRandomEnum<ThrusterType>(ThrusterType.Custom);
                parts.Add(new ThrusterDNA() { PartType = Thruster.PARTTYPE, Position = new Point3D(-1, 0, 0), Orientation = Math3D.GetRandomRotation(), Scale = new Vector3D(.5d, .5d, .5d), ThrusterDirections = ThrusterDesign.GetThrusterDirections(thrustType), ThrusterType = thrustType });

                thrustType = UtilityCore.GetRandomEnum<ThrusterType>(ThrusterType.Custom);
                parts.Add(new ThrusterDNA() { PartType = Thruster.PARTTYPE, Position = new Point3D(0, 1, 0), Orientation = Math3D.GetRandomRotation(), Scale = new Vector3D(.5d, .5d, .5d), ThrusterDirections = ThrusterDesign.GetThrusterDirections(thrustType), ThrusterType = thrustType });

                thrustType = UtilityCore.GetRandomEnum<ThrusterType>(ThrusterType.Custom);
                parts.Add(new ThrusterDNA() { PartType = Thruster.PARTTYPE, Position = new Point3D(0, -1, 0), Orientation = Math3D.GetRandomRotation(), Scale = new Vector3D(.5d, .5d, .5d), ThrusterDirections = ThrusterDesign.GetThrusterDirections(thrustType), ThrusterType = thrustType });

                ShipDNA shipDNA = ShipDNA.Create(parts);

                ShipCoreArgs core = new ShipCoreArgs()
                {
                    Map = _map,
                    Material_Ship = _material_Bot,
                    World = _world,
                };

                ShipExtraArgs extra = new ShipExtraArgs()
                {
                    Options = _editorOptions,
                    ItemOptions = _itemOptions,
                    Material_Projectile = _material_Bot,
                    Radiation = _radiation,
                    Gravity = _gravity,
                    RunNeural = false,
                    RepairPartPositions = false,
                };

                //Ship ship = await Ship.GetNewShipAsync(shipDNA, _world, _material_Bot, _map, extra);
                Bot bot = new Bot(BotConstructor.ConstructBot(shipDNA, core, extra));

                ClearCurrent();

                _shipDNA = shipDNA;
                _bot = bot;

                _bot.PhysicsBody.ApplyForceAndTorque += new EventHandler<BodyApplyForceAndTorqueArgs>(Ship_ApplyForceAndTorque);

                _thrustController = new ThrustController(_bot, _viewport, _itemOptions);

                //double mass = _ship.PhysicsBody.Mass;

                _bot.Fuel.QuantityCurrent = _bot.Fuel.QuantityMax;
                _bot.RecalculateMass();
                _thrustController.MassChanged(chkShipSimple.IsChecked.Value);

                if (chkShipDebugVisuals.IsChecked.Value)
                {
                    _thrustController.DrawDebugVisuals_Pre();
                }

                //mass = _ship.PhysicsBody.Mass;

                _map.AddItem(_bot);

                grdViewPort.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
コード例 #53
0
        private ShipPlayer CreateShip(ShipDNA dna)
        {
            ShipPlayer ship = ShipPlayer.GetNewShip(dna, _world, _material_Ship, _map, _shipExtra);

            //ship.PhysicsBody.ApplyForceAndTorque += new EventHandler<BodyApplyForceAndTorqueArgs>(Bot_ApplyForceAndTorque);

            if (ship.Energy != null)
            {
                ship.Energy.QuantityCurrent = ship.Energy.QuantityMax;
            }
            if (ship.Plasma != null)
            {
                ship.Plasma.QuantityCurrent = ship.Plasma.QuantityMax;
            }
            if (ship.Fuel != null)
            {
                ship.Fuel.QuantityCurrent = ship.Fuel.QuantityMax;
            }
            if (ship.Ammo != null)
            {
                ship.Ammo.QuantityCurrent = ship.Ammo.QuantityMax;
            }
            ship.RecalculateMass();

            _player.Ship = ship;        // the ship changed event listener will add the ship to the map

            return ship;
        }
コード例 #54
0
        private static string[] FindMissingParts(ShipDNA dna)
        {
            // Without this minimum list of parts, the ship won't work
            //TODO: When I come up with more sensor types, look for any type of sensor
            //NOTE: Brain isn't required if the sensor-thruster link multiplier has been increased, but I'll just say it's required
            string[] partList = new string[] { SensorGravity.PARTTYPE, Brain.PARTTYPE, EnergyTank.PARTTYPE, FuelTank.PARTTYPE, Thruster.PARTTYPE };

            // Get all the parts in the ship
            string[] usedParts = dna.PartsByLayer.Values.SelectMany(o => o).Select(o => o.PartType).Distinct().ToArray();

            // Return the missing ones
            return partList.Where(o => !usedParts.Contains(o)).ToArray();
        }
コード例 #55
0
        private void AddItem(ShipDNA dna, string filename)
        {
            Grid grid = new Grid();
            grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1d, GridUnitType.Auto) });
            grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(4d) });
            grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1d, GridUnitType.Star) });

            Icon3D icon = new Icon3D(dna.ShipName, dna, _world);
            icon.ShowName = false;
            Grid.SetColumn(icon, 0);
            grid.Children.Add(icon);
            icon.Width = 60d;		// this has logic to keep itself square

            StackPanel panel = new StackPanel();
            panel.HorizontalAlignment = HorizontalAlignment.Left;
            panel.VerticalAlignment = VerticalAlignment.Center;

            Label label = new Label();
            label.Content = dna.ShipName;
            label.FontSize = 14;
            label.FontWeight = FontWeights.DemiBold;
            label.HorizontalAlignment = HorizontalAlignment.Left;
            label.VerticalAlignment = VerticalAlignment.Center;
            panel.Children.Add(label);

            if (!string.IsNullOrEmpty(filename))
            {
                label = new Label();
                label.Content = filename;
                label.FontSize = 10;
                label.Foreground = new SolidColorBrush(Color.FromRgb(96, 96, 96));
                label.HorizontalAlignment = HorizontalAlignment.Left;
                label.VerticalAlignment = VerticalAlignment.Center;
                panel.Children.Add(label);
            }

            Grid.SetColumn(panel, 2);
            grid.Children.Add(panel);

            lstItems.Items.Add(grid);
            _currentDNA.Add(dna);
        }
コード例 #56
0
        private void FinishLoad(FlyingBeanSession session, FlyingBeanOptions options, ItemOptions itemOptions, ShipDNA[] winningBeans, string saveFolder, bool startEmpty)
        {
            // Manually instantiate some of the properties that didn't get serialized
            options.DefaultBeanList = _defaultBeanList;

            if (options.NewBeanList == null)		// if this was called by new, it will still be null
            {
                options.NewBeanList = new SortedList<string, ShipDNA>();

                if (!startEmpty)
                {
                    string[] beanKeys = options.DefaultBeanList.Keys.ToArray();

                    foreach (int keyIndex in UtilityCore.RandomRange(0, beanKeys.Length, Math.Min(3, beanKeys.Length)))		// only do 3 of the defaults
                    {
                        string key = beanKeys[keyIndex];
                        options.NewBeanList.Add(key, options.DefaultBeanList[key]);
                    }
                }
            }

            options.MutateArgs = PanelMutation.BuildMutateArgs(options);

            options.GravityField = new GravityFieldUniform();
            options.Gravity = options.Gravity;		// the property set modifies the gravity field

            options.WinnersLive = new WinnerList(true, options.TrackingMaxLineagesLive, options.TrackingMaxPerLineageLive);

            if (options.WinnersFinal == null)		// if a previous save had winning ships, this will already be loaded with them
            {
                options.WinnersFinal = new WinnerList(false, options.TrackingMaxLineagesFinal, options.TrackingMaxPerLineageFinal);
            }

            options.WinnerCandidates = new CandidateWinners();
            // These are already in the final list, there's no point in putting them in the candidate list as well
            //if (winningBeans != null)
            //{
            //    foreach (ShipDNA dna in winningBeans)
            //    {
            //        options.WinnerCandidates.Add(dna);
            //    }
            //}

            // Make sure the session folder is up to date
            if (saveFolder == null)
            {
                this.SessionFolder = null;
            }
            else
            {
                string dirChar = Regex.Escape(System.IO.Path.DirectorySeparatorChar.ToString());

                string pattern = dirChar + Regex.Escape(FlyingBeansWindow.SESSIONFOLDERPREFIX) + "[^" + dirChar + "]+(?<upto>" + dirChar + ")" + Regex.Escape(FlyingBeansWindow.SAVEFOLDERPREFIX);
                Match match = Regex.Match(saveFolder, pattern, RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    this.SessionFolder = saveFolder.Substring(0, match.Groups["upto"].Index);		// the session folder is everything before the save subfolder
                }
                else
                {
                    // They may have chosen a folder that they unziped onto their desktop, or wherever.  Leaving this null so that if they hit save, it will be saved
                    // in the appropriate location
                    this.SessionFolder = null;
                }
            }

            // Swap out the settings
            this.Session = session;
            this.Options = options;
            this.ItemOptions = itemOptions;

            // Inform the world
            if (this.SessionChanged != null)
            {
                this.SessionChanged(this, new EventArgs());
            }
        }
コード例 #57
0
        private void AddIconVisual(string name, ShipDNA dna, World world)
        {
            Icon3D icon = new Icon3D(name, dna, world);
            icon.VerticalAlignment = VerticalAlignment.Top;
            icon.MouseDown += new MouseButtonEventHandler(Icon_MouseDown);

            _icons.Add(icon);
            grdIcons.Children.Add(icon);
        }