コード例 #1
0
ファイル: SwarmBay.cs プロジェクト: charlierix/AsteroidMiner
        public SwarmBay(EditorOptions options, ItemOptions itemOptions, ShipPartDNA dna, Map map, World world, int material_SwarmBot, IContainer plasma, SwarmObjectiveStrokes strokes)
            : base(options, dna, itemOptions.SwarmBay_Damage.HitpointMin, itemOptions.SwarmBay_Damage.HitpointSlope, itemOptions.SwarmBay_Damage.Damage)
        {
            _itemOptions = itemOptions;
            _map = map;
            _world = world;
            _material_SwarmBot = material_SwarmBot;
            _plasma = plasma;
            _strokes = strokes;

            this.Design = new SwarmBayDesign(options, true);
            this.Design.SetDNA(dna);

            double volume, radius;
            GetMass(out _mass, out volume, out radius, out _scaleActual, dna, itemOptions);
            //this.Radius = radius;

            _timeBetweenBots = StaticRandom.NextPercent(itemOptions.SwarmBay_BirthRate, .1);

            int maxCount = (itemOptions.SwarmBay_MaxCount * Math1D.Avg(dna.Scale.X, dna.Scale.Y, dna.Scale.Z)).ToInt_Round();
            if (maxCount < 0)
            {
                maxCount = 1;
            }
            _maxBots = maxCount;

            _plasmaTankThreshold = itemOptions.SwarmBay_Birth_TankThresholdPercent;

            _birthCost = itemOptions.SwarmBay_BirthCost;
            _birthRadius = itemOptions.SwarmBay_BirthSize / 2d;

            if (_map != null)
            {
                _map.ItemRemoved += Map_ItemRemoved;
            }

            this.Destroyed += SwarmBay_Destroyed;
        }
コード例 #2
0
        private Vector3D? GetStrokeAccel(SwarmObjectiveStrokes.Stroke objectiveStroke, Point3D position, Vector3D velocity)
        {
            const double VELOCITYINFLUENCERADIUS = 2d;
            const double TOWARDRADIUSMULT = .5;     // making this smaller than the size of the velocity influence radius so there aren't any dead spots
            const double SKIPPOINTRADIUSMULT = 1d;

            if (objectiveStroke == null)
            {
                return null;
            }

            // Current stroke
            CurrentChasingStroke currentlyChasingStroke = _currentlyChasingStroke;
            if (currentlyChasingStroke == null || currentlyChasingStroke.Token != objectiveStroke.Token)
            {
                currentlyChasingStroke = new CurrentChasingStroke(objectiveStroke.Token);
                _currentlyChasingStroke = currentlyChasingStroke;
            }

            // Get affected by the stroke
            var hits = GetNearestSegmentsOrPoint(objectiveStroke.Points, position, currentlyChasingStroke.MinIndex);
            if (hits == null || (hits.Item1 == null && (hits.Item2 == null || hits.Item2.Length == 0)))
            {
                currentlyChasingStroke.MinIndex = objectiveStroke.Points.Length;
                currentlyChasingStroke.MinDistance = double.MaxValue;
                return null;
            }

            // Stats
            UpdateStrokeStats(currentlyChasingStroke, hits, objectiveStroke.Points, position, this.Radius * SKIPPOINTRADIUSMULT);

            #region build return

            Vector3D retVal = new Vector3D(0, 0, 0);

            double accel = this.MaxAccel;

            if (hits.Item1 != null)
            {
                retVal += GetStrokeAccel_Point(hits.Item1, position, accel, VELOCITYINFLUENCERADIUS, TOWARDRADIUSMULT);
            }

            if (hits.Item2 != null)
            {
                for (int cntr = 0; cntr < hits.Item2.Length; cntr++)
                {
                    bool shouldAttractToward = cntr == 0 && hits.Item1 == null;

                    retVal += GetStrokeAccel_Segment(hits.Item2[cntr], position, accel, VELOCITYINFLUENCERADIUS, TOWARDRADIUSMULT, shouldAttractToward);
                }
            }

            #endregion

            return retVal;
        }
コード例 #3
0
        public SwarmBot1a(double radius, Point3D position, World world, Map map, SwarmObjectiveStrokes strokes, int materialID, Color? color = null)
        {
            _map = map;
            _strokes = strokes;

            this.Radius = radius;
            this.SearchRadius = radius * 100;

            _settings_OtherBot_Chase = CreateForceSettingInitial_OtherBot_Chase();
            _settings_OtherBot_Passive = CreateForceSettingInitial_OtherBot_Passive();
            _settings_Asteroid = CreateForceSettingInitial_Asteroid();

            #region WPF Model

            this.Model = GetModel(radius, color);
            this.Model.Transform = new ScaleTransform3D(radius, radius, radius);

            // Model Visual
            ModelVisual3D visual = new ModelVisual3D();
            visual.Content = this.Model;

            #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 mass = GetMass(radius);

            using (CollisionHull hull = CollisionHull.CreateSphere(world, 0, new Vector3D(radius / 2, radius / 2, radius / 2), null))
            {
                this.PhysicsBody = new Body(hull, transform.Value, mass, new Visual3D[] { visual });
                //this.PhysicsBody.IsContinuousCollision = true;
                this.PhysicsBody.MaterialGroupID = materialID;
                this.PhysicsBody.LinearDamping = .01d;
                this.PhysicsBody.AngularDamping = new Vector3D(.01d, .01d, .01d);

                this.PhysicsBody.ApplyForceAndTorque += new EventHandler<BodyApplyForceAndTorqueArgs>(Body_ApplyForceAndTorque);
            }

            #endregion

            this.CreationTime = DateTime.UtcNow;
        }
コード例 #4
0
        private void Strokes_PointsChanged(object sender, SwarmObjectiveStrokes.PointsChangedArgs e)
        {
            try
            {
                switch (e.ChangeType)
                {
                    case SwarmObjectiveStrokes.PointChangeType.AddingPointsToStroke:
                        // Just draw the points in a simple way
                        break;

                    case SwarmObjectiveStrokes.PointChangeType.AddNewStroke:
                    case SwarmObjectiveStrokes.PointChangeType.ConvertStroke_Add:
                        #region add stroke

                        if (e.Points == null || e.Points.Length == 0)
                        {
                            throw new ArgumentException("Added stroke is empty");
                        }
                        else if (e.StrokeToken == null)
                        {
                            throw new ArgumentException("Expected token to be populated for a new stroke");
                        }

                        foreach (Visual3D visual in GetStrokeVisual(e.Points))
                        {
                            _strokeVisuals.Add(Tuple.Create(e.StrokeToken.Value, visual));
                            _viewport.Children.Add(visual);
                        }

                        #endregion
                        break;

                    case SwarmObjectiveStrokes.PointChangeType.ConvertStroke_Remove:
                    case SwarmObjectiveStrokes.PointChangeType.RemoveStroke_Clear:
                    case SwarmObjectiveStrokes.PointChangeType.RemoveStroke_Remove:
                    case SwarmObjectiveStrokes.PointChangeType.RemoveStroke_Timeout:
                        if (e.StrokeToken == null)
                        {
                            // Remove the pre stroke
                        }
                        else
                        {
                            // Remove the full stroke
                            _viewport.Children.RemoveAll(
                                _strokeVisuals.RemoveWhere(o => o.Item1 == e.StrokeToken.Value).
                                    Select(o => o.Item2));
                        }
                        break;

                    default:
                        throw new ApplicationException("Unknown SwarmObjectiveStrokes.PointChangeType: " + e.ChangeType.ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
コード例 #5
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                //_backgroundTiles = new BackgoundTiles(_sceneCanvas, _camera, (Brush)this.FindResource("color_SceneBackAlt"));

                #region Init World

                _boundryMin = new Point3D(-BOUNDRYSIZEHALF, -BOUNDRYSIZEHALF, -BOUNDRYSIZEHALF);
                _boundryMax = new Point3D(BOUNDRYSIZEHALF, BOUNDRYSIZEHALF, BOUNDRYSIZEHALF);

                _world = new World();
                _world.Updating += new EventHandler<WorldUpdatingArgs>(World_Updating);

                List<Point3D[]> innerLines, outerLines;
                _world.SetCollisionBoundry(out innerLines, out outerLines, _boundryMin, _boundryMax);

                //TODO: Only draw the boundry lines if options say to

                #endregion
                #region Materials

                _materialManager = new MaterialManager(_world);

                // Bot
                var material = new Game.Newt.v2.NewtonDynamics.Material();
                _material_Bot = _materialManager.AddMaterial(material);

                // Asteroid
                material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .1d;
                _material_Asteroid = _materialManager.AddMaterial(material);

                // Collisions
                _materialManager.RegisterCollisionEvent(_material_Bot, _material_Bot, Collision_BotBot);
                _materialManager.RegisterCollisionEvent(_material_Bot, _material_Asteroid, Collision_BotAsteroid);

                #endregion
                #region Trackball

                // Camera Trackball
                _trackball = new TrackBallRoam(_camera);
                _trackball.EventSource = grdViewPort;		//NOTE:  If this control doesn't have a background color set, the trackball won't see events (I think transparent is ok, just not null)
                _trackball.AllowZoomOnMouseWheel = true;
                _trackball.ShouldHitTestOnOrbit = true;
                _trackball.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.MouseComplete_NoLeft));
                //_trackball.GetOrbitRadius += new GetOrbitRadiusHandler(Trackball_GetOrbitRadius);

                #endregion
                #region Map

                _map = new Map(_viewport, null, _world);
                _map.SnapshotFequency_Milliseconds = 250;// 125;
                _map.SnapshotMaxItemsPerNode = 10;
                _map.ShouldBuildSnapshots = true;
                _map.ShouldShowSnapshotLines = false;
                _map.ShouldSnapshotCentersDrift = true;
                _map.ItemAdded += Map_ItemAdded;
                _map.ItemRemoved += Map_ItemRemoved;

                #endregion
                #region Update Manager

                _updateManager = new UpdateManager(
                    new Type[] { typeof(SwarmBot1a) },
                    new Type[] { typeof(SwarmBot1a) },
                    _map);

                #endregion
                #region Strokes

                _strokes = new SwarmObjectiveStrokes(_world.WorldClock, SUBSTROKESIZE, 15);
                _strokes.PointsChanged += Strokes_PointsChanged;

                #endregion
                #region Bot Clusters

                _botClusters = new SwarmClusters(_map);

                _botClusterTimer = new System.Timers.Timer();
                _botClusterTimer.Interval = 1111;
                _botClusterTimer.AutoReset = false;       // makes sure only one tick is firing at a time
                _botClusterTimer.Elapsed += BotClusterTimer_Elapsed;
                _botClusterTimer.Start();

                #endregion

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
コード例 #6
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _itemOptions = new ItemOptions();
                _itemOptions.Thruster_StrengthRatio *= 4.5;
                _itemOptions.FuelToThrustRatio *= .03;
                _itemOptions.Projectile_Color = UtilityWPF.ColorFromHex("FFE330");        // using bee/wasp colors, because white looks too much like the stars

                _progressBars = new ShipProgressBarManager(pnlProgressBars);
                _progressBars.Foreground = new SolidColorBrush(UtilityWPF.ColorFromHex("BBB"));

                #region Init World

                // Set the size of the world to something a bit random (gets boring when it's always the same size)
                double halfSize = 325 + StaticRandom.Next(500);
                //halfSize *= 2;
                _boundryMin = new Point3D(-halfSize, -halfSize, -35);
                _boundryMax = new Point3D(halfSize, halfSize, 35);

                _world = new World();
                _world.Updating += new EventHandler<WorldUpdatingArgs>(World_Updating);

                List<Point3D[]> innerLines, outerLines;
                _world.SetCollisionBoundry(out innerLines, out outerLines, _boundryMin, _boundryMax);

                // Draw the lines
                _boundryLines = new ScreenSpaceLines3D(true);
                _boundryLines.Thickness = 1d;
                _boundryLines.Color = WorldColors.BoundryLines;
                _viewport.Children.Add(_boundryLines);

                foreach (Point3D[] line in innerLines)
                {
                    _boundryLines.AddLine(line[0], line[1]);
                }

                #endregion
                #region Materials

                _materialManager = new MaterialManager(_world);

                // Ship
                Game.Newt.v2.NewtonDynamics.Material material = new Game.Newt.v2.NewtonDynamics.Material();
                _material_Ship = _materialManager.AddMaterial(material);

                // Exploding Ship
                material = new Game.Newt.v2.NewtonDynamics.Material();
                material.IsCollidable = false;
                _material_ExplodingShip = _materialManager.AddMaterial(material);

                // Space Station (force field)
                material = new Game.Newt.v2.NewtonDynamics.Material();
                material.IsCollidable = false;
                //material.Elasticity = .99d;       // uncomment these if it should be collidable (it's an ellipse, and briefly shows a force field)
                //material.StaticFriction = .02d;
                //material.KineticFriction = .01d;
                _material_SpaceStation = _materialManager.AddMaterial(material);

                //_materialManager.RegisterCollisionEvent(_material_SpaceStation, _material_Asteroid, Collision_SpaceStation);
                //_materialManager.RegisterCollisionEvent(_material_SpaceStation, _material_Mineral, Collision_SpaceStation);

                // Mineral
                material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .5d;
                material.StaticFriction = .9d;
                material.KineticFriction = .4d;
                _material_Mineral = _materialManager.AddMaterial(material);

                // Asteroid
                material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .25d;
                material.StaticFriction = .9d;
                material.KineticFriction = .75d;
                _material_Asteroid = _materialManager.AddMaterial(material);

                // Projectile
                material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .95d;
                _material_Projectile = _materialManager.AddMaterial(material);

                // Swarmbot
                material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .95d;
                _material_SwarmBot = _materialManager.AddMaterial(material);

                // Collisions
                _materialManager.RegisterCollisionEvent(_material_Ship, _material_Mineral, Collision_ShipMineral);
                _materialManager.RegisterCollisionEvent(_material_Ship, _material_Asteroid, Collision_ShipAsteroid);
                _materialManager.RegisterCollisionEvent(_material_Ship, _material_Projectile, Collision_ShipProjectile);

                _materialManager.RegisterCollisionEvent(_material_Asteroid, _material_Projectile, Collision_AsteroidProjectile);
                _materialManager.RegisterCollisionEvent(_material_Asteroid, _material_SwarmBot, Collision_AsteroidSwarmBot);
                _materialManager.RegisterCollisionEvent(_material_Asteroid, _material_Asteroid, Collision_AsteroidAsteroid);

                #endregion
                #region Trackball

                //TODO: Only use this when debugging the scene

                //// Trackball
                //_trackball = new TrackBallRoam(_camera);
                //_trackball.KeyPanScale = 15d;
                //_trackball.EventSource = grdViewPort;		//NOTE:  If this control doesn't have a background color set, the trackball won't see events (I think transparent is ok, just not null)
                //_trackball.AllowZoomOnMouseWheel = true;
                //_trackball.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.MouseComplete_NoLeft));
                ////_trackball.GetOrbitRadius += new GetOrbitRadiusHandler(Trackball_GetOrbitRadius);
                //_trackball.ShouldHitTestOnOrbit = true;

                #endregion
                #region Map

                _map = new Map(_viewport, null, _world);
                //_map.SnapshotFequency_Milliseconds = 250;     // just use the map's default values
                //_map.SnapshotMaxItemsPerNode = 13;
                _map.ShouldBuildSnapshots = true;
                _map.ShouldShowSnapshotLines = false;
                _map.ShouldSnapshotCentersDrift = true;

                _map.ItemRemoved += new EventHandler<MapItemArgs>(Map_ItemRemoved);

                #endregion
                #region Radiation

                //TODO: Make radiation sources instead of a constant ambient -- sort of mini stars, or something manmade looking
                _radiation = new RadiationField()
                {
                    AmbientRadiation = 1,
                };

                #endregion
                #region UpdateManager

                //TODO: UpdateManager needs to inspect types as they are added to the map (map's ItemAdded event)
                _updateManager = new UpdateManager(
                    new Type[] { typeof(ShipPlayer), typeof(SpaceStation2D), typeof(Projectile), typeof(Asteroid), typeof(SwarmBot1b) },
                    new Type[] { typeof(ShipPlayer), typeof(SwarmBot1b) },
                    _map);

                #endregion
                #region Brush Strokes

                _brushStrokes = new SwarmObjectiveStrokes(_world.WorldClock, _itemOptions.SwarmBay_BirthSize * 4, 6);

                // This would be for drawing the strokes
                //_brushStrokes.PointsChanged += BrushStrokes_PointsChanged;

                #endregion
                #region Player

                _player = new Player();
                _player.Credits = 10;

                _player.ShipChanged += new EventHandler<ShipChangedArgs>(Player_ShipChanged);

                #endregion
                #region Minimap

                _miniMap = new MinimapHelper(_map, _viewportMap);

                #endregion
                #region Camera Helper

                _cameraHelper = new CameraHelper(_player, _camera, _cameraMap, _miniMap);

                #endregion
                #region MapPopulationManager

                _mapPopulationManager = new MapPopulationManager(_map, _world, new Point3D(_boundryMin.X, _boundryMin.Y, 0), new Point3D(_boundryMax.X, _boundryMax.Y, 0), _material_Asteroid, _material_Mineral, GetAsteroidMassByRadius, GetMineralsFromDestroyedAsteroid, ItemOptionsAstMin2D.MINASTEROIDRADIUS);
                _updateManager.AddNonMapItem(_mapPopulationManager, TokenGenerator.NextToken());

                #endregion
                #region MapForcesManager

                _mapForcesManager = new MapForcesManager(_map, _boundryMin, _boundryMax);
                _updateManager.AddNonMapItem(_mapForcesManager, TokenGenerator.NextToken());

                #endregion
                #region BackImageManager

                _backImageManager = new BackImageManager(backgroundCanvas, _player);

                #endregion

                #region Ship Extra

                _shipExtra = new ShipExtraArgs()
                {
                    Options = _editorOptions,
                    ItemOptions = _itemOptions,
                    Material_Projectile = _material_Projectile,
                    Material_SwarmBot = _material_SwarmBot,
                    SwarmObjectiveStrokes = _brushStrokes,
                    RunNeural = false,
                    Radiation = _radiation,
                };

                #endregion

                CreateStars3D();      //TODO: Move this to BackImageManager
                                      //CreateStars3DGrid();
                                      //CreateShip(UtilityCore.GetRandomEnum<DefaultShipType>());

                if (!LoadLatestSession())
                {
                    CreateNewSession();
                }

                CreateAsteroids();
                CreateMinerals();
                //CreateProjectile();

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }