private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _itemOptions = new ItemOptions();
                _itemOptions.MatterToEnergy_ConversionRate *= .12;
                _itemOptions.MatterToEnergy_AmountToDraw *= 1.25;        //NOTE: In bot, the matter converter group doesn't check if empty often enough.  So if you draw much more, then there will be noticable pulses of not refilling (I assume that's the cause anyway)

                #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);

                //NOTE: No need to draw a boundry

                #endregion
                #region Materials

                _materialManager = new MaterialManager(_world);

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

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

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

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

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

                // Collisions
                //_materialManager.RegisterCollisionEvent(_material_Bot, _material_Bot, Collision_BotBot);
                //_materialManager.RegisterCollisionEvent(_material_Bot, _material_Item, Collision_BotItem);
                //TODO: projectile collisions

                #endregion
                #region Camera Pool

                //TODO: Make the number of threads more configurable, look at how many processors there are
                _cameraPool = new CameraPool(1, Colors.Black);

                #endregion
                #region Map

                _map = new Map(_viewport, _cameraPool, _world);
                _map.SnapshotFequency_Milliseconds = 250;// 125;
                _map.SnapshotMaxItemsPerNode = 10;
                _map.ShouldBuildSnapshots = true;
                _map.ShouldShowSnapshotLines = false;
                _map.ShouldSnapshotCentersDrift = true;

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

                #endregion

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _itemOptions = new ItemOptions();

                #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);

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

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

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

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

                // Egg
                material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .5d;
                _material_Egg = _materialManager.AddMaterial(material);

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

                // Collisions
                _materialManager.RegisterCollisionEvent(_material_Bot, _material_Bot, Collision_BotBot);
                _materialManager.RegisterCollisionEvent(_material_Bot, _material_Food, Collision_BotFood);
                //TODO: May want to listen to projectile collisions

                #endregion
                #region Trackball

                // 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.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.Keyboard_ASDW_In));
                _trackball.ShouldHitTestOnOrbit = true;
                //_trackball.UserMovedCamera += new EventHandler<UserMovedCameraArgs>(Trackball_UserMovedCamera);
                //_trackball.GetOrbitRadius += new EventHandler<GetOrbitRadiusArgs>(Trackball_GetOrbitRadius);

                #endregion
                #region Camera Pool

                //TODO: Make the number of threads more configurable, look at how many processors there are
                //_cameraPool = new CameraPool(2, Colors.Black);
                _cameraPool = new CameraPool(1, Colors.Black);

                #endregion
                #region Map

                _map = new Map(_viewport, _cameraPool, _world)
                {
                    SnapshotFequency_Milliseconds = 250,        // 125
                    SnapshotMaxItemsPerNode = 10,
                    ShouldBuildSnapshots = true,
                    ShouldShowSnapshotLines = false,
                    ShouldSnapshotCentersDrift = true,
                };

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

                #endregion
                #region Fields

                _radiation = new RadiationField()
                {
                    AmbientRadiation = 0d,
                };

                //_gravity = new GravityFieldUniform()
                //{
                //    Gravity = new Vector3D(0, 0, 0),
                //};

                //TODO: Support a uniform fluid
                //FluidField

                #endregion
                #region ItemSelectDragLogic

                _selectionLogic = new ItemSelectDragLogic(_map, _camera, _viewport, grdViewPort)
                {
                    ShouldMoveItemWithSpring = true,
                    ShouldSpringCauseTorque = false,
                    SpringColor = null,     // Colors.Chartreuse
                    ShowDebugVisuals = false,       // true
                };

                _selectionLogic.SelectableTypes.Add(typeof(Bot));
                _selectionLogic.SelectableTypes.Add(typeof(Mineral));
                _selectionLogic.SelectableTypes.Add(typeof(Egg));

                _selectionLogic.ItemSelected += new EventHandler<ItemSelectedArgs>(SelectionLogic_ItemSelected);

                #endregion

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _itemOptions = new ItemOptions();

                #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);

                #endregion
                #region Materials

                _materialManager = new MaterialManager(_world);

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

                // Collisions
                //_materialManager.RegisterCollisionEvent(_material_Asteroid, _material_Asteroid, Collision_AsteroidAsteroid);

                #endregion
                #region Map

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

                // Asteroid doesn't implement up IPartUpdatable
                //_updateManager = new UpdateManager(
                //    new Type[] { typeof(Asteroid) },
                //    new Type[] { typeof(Asteroid) },
                //    _map);

                #endregion

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                #region Init World

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

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

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

                // Don't bother with the boundry lines.  It looks funny with a partial viewport
                //// Draw the lines
                //_boundryLines = new ScreenSpaceLines3D(true);
                //_boundryLines.Thickness = 1d;
                //_boundryLines.Color = _colors.BoundryLines;
                //_viewport.Children.Add(_boundryLines);

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

                #endregion
                #region Materials

                _materialManager = new MaterialManager(_world);

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

                //_materialManager.RegisterCollisionEvent(_material_Terrain, _material_Bean, Collision_BeanTerrain);

                #endregion
                #region Trackball

                // Trackball
                _trackball = new TrackBallRoam(_camera);
                //_trackball.KeyPanScale = 15d;
                _trackball.EventSource = pnlViewport;		//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));
                //_trackball.GetOrbitRadius += new GetOrbitRadiusHandler(Trackball_GetOrbitRadius);
                _trackball.ShouldHitTestOnOrbit = false;

                // Trackball
                _trackballNeural = new TrackBallRoam(_cameraNeural);
                //_trackballNeural.KeyPanScale = 15d;
                _trackballNeural.EventSource = pnlViewportNeural;		//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)
                _trackballNeural.AllowZoomOnMouseWheel = true;
                _trackballNeural.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.MouseComplete));
                //_trackballNeural.GetOrbitRadius += new GetOrbitRadiusHandler(Trackball_GetOrbitRadius);
                _trackballNeural.ShouldHitTestOnOrbit = false;

                #endregion
                #region Map

                //_map = new Map(_viewport, null, _world);
                //_map.SnapshotFequency_Milliseconds = 125;
                //_map.SnapshotMaxItemsPerNode = 10;
                //_map.ShouldBuildSnapshots = false;// true;
                //_map.ShouldShowSnapshotLines = false;
                //_map.ShouldSnapshotCentersDrift = true;

                #endregion
                #region Fields

                _radiation = new RadiationField()
                {
                    AmbientRadiation = 0d,
                };

                _gravityField = new GravityFieldUniform();

                #endregion

                // Trackball Controls
                SetupGravityTrackball();

                UpdateGravity();

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        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);
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _itemOptions = new ItemOptions();

                #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);

                #endregion
                #region Materials

                _materialManager = new MaterialManager(_world);

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

                // Ball
                material = new Game.Newt.v2.NewtonDynamics.Material();
                _material_Ball = _materialManager.AddMaterial(material);

                #endregion
                #region Trackball

                // 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.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.Keyboard_ASDW_In));
                _trackball.ShouldHitTestOnOrbit = true;
                //_trackball.UserMovedCamera += new EventHandler<UserMovedCameraArgs>(Trackball_UserMovedCamera);
                //_trackball.GetOrbitRadius += new EventHandler<GetOrbitRadiusArgs>(Trackball_GetOrbitRadius);

                #endregion

                #region Chased Ball

                _chasedBall = new ChasedBall();

                _chasedBall.MotionType_Position = MotionType_Position.Stop;
                _chasedBall.MotionType_Orientation = MotionType_Orientation.Stop;

                _chasedBall.BoundrySizeChanged += new EventHandler(ChasedBall_BoundrySizeChanged);

                // Ball visual
                _chasedBallVisual = GetChaseBallVisual_Position();
                _chasedBallTransform = new TranslateTransform3D();
                _chasedBallVisual.Transform = _chasedBallTransform;
                _viewport.Children.Add(_chasedBallVisual);

                // Direction Visual
                var directionVisual = GetChaseBallVisual_Orientation();
                _chasedDirectionModel = directionVisual.Item1;
                _chasedDirectionVisual = directionVisual.Item2;
                _viewport.Children.Add(_chasedDirectionVisual);

                // Panels (the act of instantiating them will update the ball's properties)
                pnlChasePosition.Content = new ChasedPosition(_chasedBall)
                {
                    Foreground = Brushes.White,
                };

                pnlChaseOrientation.Content = new ChasedOrientation(_chasedBall)
                {
                    Foreground = Brushes.White,
                };

                #endregion
                #region Debug Visuals

                // Put these on the viewport before the ball so that it is propertly semitransparent

                //TODO: Draw the bounding box.  Use XYZ colors.  This will help the user stay oriented

                #endregion
                #region Body Ball

                _bodyBall = new BodyBall(_world);

                //_bodyBall.PhysicsBody.AngularDamping = new Vector3D(.0001, .0001, .0001);
                //_bodyBall.PhysicsBody.AngularVelocity = new Vector3D(0, 0, 4 * Math.PI);

                _viewport.Children.AddRange(_bodyBall.Visuals3D);

                #endregion

                RedrawBoundry();

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                #region Trackball

                // Trackball
                _trackball = new TrackBallRoam(_camera);
                _trackball.KeyPanScale = 1d;
                _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;

                #region copied from MouseComplete_NoLeft - middle button changed

                TrackBallMapping complexMapping = null;

                // Middle Button
                complexMapping = new TrackBallMapping(CameraMovement.RotateAroundLookDirection_AutoScroll);
                complexMapping.Add(MouseButton.Middle);
                complexMapping.Add(new Key[] { Key.LeftCtrl, Key.RightCtrl });
                complexMapping.Add(new Key[] { Key.LeftAlt, Key.RightAlt });
                _trackball.Mappings.Add(complexMapping);
                _trackball.Mappings.Add(new TrackBallMapping(CameraMovement.RotateAroundLookDirection, MouseButton.Middle, new Key[] { Key.LeftCtrl, Key.RightCtrl }));

                complexMapping = new TrackBallMapping(CameraMovement.Zoom_AutoScroll);
                complexMapping.Add(MouseButton.Middle);
                complexMapping.Add(new Key[] { Key.LeftShift, Key.RightShift });
                complexMapping.Add(new Key[] { Key.LeftAlt, Key.RightAlt });
                _trackball.Mappings.Add(complexMapping);
                _trackball.Mappings.Add(new TrackBallMapping(CameraMovement.Zoom, MouseButton.Middle, new Key[] { Key.LeftShift, Key.RightShift }));

                //retVal.Add(new TrackBallMapping(CameraMovement.Pan_AutoScroll, MouseButton.Middle));
                _trackball.Mappings.Add(new TrackBallMapping(CameraMovement.Pan, MouseButton.Middle));

                // Left+Right Buttons (emulate middle)
                complexMapping = new TrackBallMapping(CameraMovement.RotateAroundLookDirection_AutoScroll);
                complexMapping.Add(MouseButton.Left);
                complexMapping.Add(MouseButton.Right);
                complexMapping.Add(new Key[] { Key.LeftCtrl, Key.RightCtrl });
                complexMapping.Add(new Key[] { Key.LeftAlt, Key.RightAlt });
                _trackball.Mappings.Add(complexMapping);

                complexMapping = new TrackBallMapping(CameraMovement.RotateAroundLookDirection);
                complexMapping.Add(MouseButton.Left);
                complexMapping.Add(MouseButton.Right);
                complexMapping.Add(new Key[] { Key.LeftCtrl, Key.RightCtrl });
                _trackball.Mappings.Add(complexMapping);

                complexMapping = new TrackBallMapping(CameraMovement.Zoom_AutoScroll);
                complexMapping.Add(MouseButton.Left);
                complexMapping.Add(MouseButton.Right);
                complexMapping.Add(new Key[] { Key.LeftShift, Key.RightShift });
                complexMapping.Add(new Key[] { Key.LeftAlt, Key.RightAlt });
                _trackball.Mappings.Add(complexMapping);

                complexMapping = new TrackBallMapping(CameraMovement.Zoom);
                complexMapping.Add(MouseButton.Left);
                complexMapping.Add(MouseButton.Right);
                complexMapping.Add(new Key[] { Key.LeftShift, Key.RightShift });
                _trackball.Mappings.Add(complexMapping);

                //complexMapping = new TrackBallMapping(CameraMovement.Pan_AutoScroll);
                complexMapping = new TrackBallMapping(CameraMovement.Pan);
                complexMapping.Add(MouseButton.Left);
                complexMapping.Add(MouseButton.Right);
                _trackball.Mappings.Add(complexMapping);

                // Right Button
                complexMapping = new TrackBallMapping(CameraMovement.RotateInPlace_AutoScroll);
                complexMapping.Add(MouseButton.Right);
                complexMapping.Add(new Key[] { Key.LeftCtrl, Key.RightCtrl });
                complexMapping.Add(new Key[] { Key.LeftAlt, Key.RightAlt });
                _trackball.Mappings.Add(complexMapping);
                _trackball.Mappings.Add(new TrackBallMapping(CameraMovement.RotateInPlace, MouseButton.Right, new Key[] { Key.LeftCtrl, Key.RightCtrl }));

                _trackball.Mappings.Add(new TrackBallMapping(CameraMovement.Orbit_AutoScroll, MouseButton.Right, new Key[] { Key.LeftAlt, Key.RightAlt }));
                _trackball.Mappings.Add(new TrackBallMapping(CameraMovement.Orbit, MouseButton.Right));

                #endregion

                //_trackball.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.Keyboard_ASDW_In));		// let the ship get asdw instead of the camera
                //_trackball.GetOrbitRadius += new GetOrbitRadiusHandler(Trackball_GetOrbitRadius);
                _trackball.ShouldHitTestOnOrbit = true;

                #endregion

                #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 = 50d;
                _boundryMin = new Point3D(-halfSize, -halfSize, -halfSize);
                _boundryMax = new Point3D(halfSize, halfSize, halfSize);

                _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 = _colors.BoundryLines;
                _viewport.Children.Add(_boundryLines);

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

                #endregion
                #region Materials

                _materialManager = new MaterialManager(_world);

                // Part
                Game.Newt.v2.NewtonDynamics.Material material = new Game.Newt.v2.NewtonDynamics.Material();
                _material_Part = _materialManager.AddMaterial(material);

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

                //_materialManager.RegisterCollisionEvent(_material_Ship, _material_Asteroid, Collision_Ship);

                #endregion
                #region Map

                _map = new Map(_viewport, null, _world);
                //_map.SnapshotFequency_Milliseconds = 125;
                //_map.SnapshotMaxItemsPerNode = 10;
                _map.ShouldBuildSnapshots = false;
                //_map.ShouldShowSnapshotLines = true;
                //_map.ShouldSnapshotCentersDrift = false;

                #endregion
                #region Fields

                _radiation = new RadiationField();
                _radiation.AmbientRadiation = 1d;

                _gravity = new GravityFieldUniform();

                #endregion

                _world.UnPause();

                #region Solver Timer

                _solverTimer = new DispatcherTimer();
                _solverTimer.Interval = TimeSpan.FromMilliseconds(trkSimSpeed.Value);
                _solverTimer.Tick += new EventHandler(SolverTimer_Tick);
                _solverTimer.IsEnabled = true;

                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                double terrainHeight = TERRAINRADIUS / 20d;

                #region Load last save

                _session = new FlyingBeanSession();
                _options = new FlyingBeanOptions();
                _itemOptions = new ItemOptions();

                _panelFile = new PanelFile(null, _session, _options, _itemOptions, GetDefaultBeans());
                _panelFile.SessionChanged += new EventHandler(PanelFile_SessionChanged);
                if (!_panelFile.TryLoadLastSave(false))
                {
                    _panelFile.New(false, false);		// by calling new, all of the options initialization is done by the file panel instead of doing it here
                }

                #endregion

                #region Winners

                _winnerManager = new WinnerManager(_options.WinnersLive, _options.WinnerCandidates, _options.WinnersFinal, _options.FinalistCount);

                #endregion
                #region Init World

                double boundryXY = TERRAINRADIUS * 1.25d;

                _boundryMin = new Point3D(-boundryXY, -boundryXY, terrainHeight * -2d);
                _boundryMax = new Point3D(boundryXY, boundryXY, TERRAINRADIUS * 25d);

                _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)
                {
                    Thickness = 1d,
                    Color = _colors.BoundryLines,
                };
                _viewport.Children.Add(_boundryLines);

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

                #endregion
                #region Materials

                _materialManager = new MaterialManager(_world);

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

                // Bean
                material = new Game.Newt.v2.NewtonDynamics.Material();
                _material_Bean = _materialManager.AddMaterial(material);

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

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

                _materialManager.RegisterCollisionEvent(0, _material_Bean, Collision_BeanTerrain);		// zero should be the boundry (it should be the default material if no other is applied)
                _materialManager.RegisterCollisionEvent(_material_Terrain, _material_Bean, Collision_BeanTerrain);
                _materialManager.RegisterCollisionEvent(_material_Bean, _material_Bean, Collision_BeanBean);

                #endregion
                #region Trackball

                // 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.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.Keyboard_ASDW_In));
                _trackball.ShouldHitTestOnOrbit = true;
                _trackball.UserMovedCamera += new EventHandler<UserMovedCameraArgs>(Trackball_UserMovedCamera);
                _trackball.GetOrbitRadius += new EventHandler<GetOrbitRadiusArgs>(Trackball_GetOrbitRadius);

                #endregion
                #region Map

                _map = new Map(_viewport, null, _world)
                {
                    SnapshotFequency_Milliseconds = 125,
                    SnapshotMaxItemsPerNode = 10,
                    ShouldBuildSnapshots = false,
                    ShouldShowSnapshotLines = false,
                    ShouldSnapshotCentersDrift = true,
                };

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

                #endregion
                #region Terrain

                //TODO: Texture map this so it's not so boring
                #region WPF Model (plus collision hull)

                // Material
                MaterialGroup materials = new MaterialGroup();
                materials.Children.Add(new DiffuseMaterial(new SolidColorBrush(_colors.Terrain)));
                materials.Children.Add(_colors.TerrainSpecular);

                // Geometry Model
                GeometryModel3D geometry = new GeometryModel3D();
                geometry.Material = materials;
                geometry.BackMaterial = materials;

                geometry.Geometry = UtilityWPF.GetCylinder_AlongX(100, TERRAINRADIUS, terrainHeight);
                CollisionHull hull = CollisionHull.CreateCylinder(_world, 0, TERRAINRADIUS, terrainHeight, null);

                // Transform
                Transform3DGroup transform = new Transform3DGroup();		// rotate needs to be added before translate
                transform.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), -90)));
                transform.Children.Add(new TranslateTransform3D(new Vector3D(0, 0, terrainHeight / -2d)));		// I want the objects to be able to add to z=0

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

                // Add to the viewport
                _viewport.Children.Add(model);

                #endregion

                // Make a physics body that represents this shape
                _terrain = new Body(hull, transform.Value, 0, new Visual3D[] { model });		// using zero mass tells newton it's static scenery (stuff bounces off of it, but it will never move)
                hull.Dispose();
                _terrain.MaterialGroupID = _material_Terrain;

                #endregion
                #region Fields

                // gravity was done by the file panel

                _radiation = new RadiationField()
                {
                    AmbientRadiation = 0d,
                };

                _boundryField = new BoundryField(.5d, 7500d, 2d, _boundryMin, _boundryMax);

                #endregion

                // Doing this so that if they hit the import button, it will call a method in beantypes (not the best design, but it works)
                _panelBeanTypes = new PanelBeanTypes(_options, _world);
                _panelFile.BeanTypesPanel = _panelBeanTypes;

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

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        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);
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                //_camera.Position = new Point3D(0, 0, -1000);
                //_camera.LookDirection = new Vector3D(0, 0, 1);
                //_camera.UpDirection = new Vector3D(0, 1, 0);

                #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 *= 1d + (StaticRandom.NextDouble() * 5d);
                _boundryMin = new Point3D(-halfSize, -halfSize, halfSize * -.25);
                _boundryMax = new Point3D(halfSize, halfSize, halfSize * .25);

                _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);

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

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

                // Space Station (force field)
                material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .99d;
                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);

                #endregion
                #region Trackball

                // 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_RightRotateInPlace));
                _trackball.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.Keyboard_ASDW_In));
                //_trackball.GetOrbitRadius += new GetOrbitRadiusHandler(Trackball_GetOrbitRadius);
                _trackball.ShouldHitTestOnOrbit = true;

                #endregion
                #region Map

                _map = new Map(_viewport, null, _world);
                _map.SnapshotFequency_Milliseconds = 125;
                _map.SnapshotMaxItemsPerNode = 10;
                _map.ShouldBuildSnapshots = true;
                _map.ShouldShowSnapshotLines = _optionsPanel.OctreeShowLines;
                _map.ShouldSnapshotCentersDrift = _optionsPanel.OctreeCentersDrift;

                #endregion
                #region UpdateManager

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

                #endregion
                CreateFields();

                //TODO:  Add these during a timer to minimize the load time
                if (_optionsPanel.ShowStars)
                {
                    CreateStars();
                }
                CreateAsteroids();
                CreateMinerals();
                CreateSpaceStations();		// creating these last so stuff shows up behind them

                #region Start Position

                #region Farthest Station

                //// The center is too chaotic, so choose the farthest out space station
                //Point3D farthestStationPoint = new Point3D(0, 0, 0);
                //double farthestStationDistance = 0d;
                //foreach (Point3D stationPosition in _map.GetAllObjects().Where(o => o is SpaceStation).Select(o => o.PositionWorld))
                //{
                //    double distance = stationPosition.ToVector().LengthSquared;
                //    if (distance > farthestStationDistance)
                //    {
                //        farthestStationPoint = stationPosition;
                //        farthestStationDistance = distance;
                //    }
                //}

                //// Set the camera near there
                //_camera.Position = farthestStationPoint + (farthestStationPoint.ToVector().ToUnit() * 75d) + Math3D.GetRandomVectorSphericalShell(25d);
                //_camera.LookDirection = _camera.Position.ToVector() * -1d;
                //_camera.UpDirection = new Vector3D(0, 0, 1);

                #endregion
                #region Random Station

                List<Point3D> stationPoints = _map.GetAllItems().Where(o => o is SpaceStation).Select(o => o.PositionWorld).ToList();
                Point3D stationPoint = stationPoints[StaticRandom.Next(stationPoints.Count)];

                // Set the camera near there
                _camera.Position = stationPoint + (stationPoint.ToVector().ToUnit() * 75d) + Math3D.GetRandomVector_Spherical_Shell(25d);
                _camera.LookDirection = _camera.Position.ToVector() * -1d;
                _camera.UpDirection = new Vector3D(0, 0, 1);

                #endregion

                #endregion

                //TODO:  kuler for dialogs

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void EnsureWorldStarted()
        {
            if (_world != null)
            {
                return;
            }

            #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 = 50d;
            _boundryMin = new Point3D(-halfSize, -halfSize, -halfSize);
            _boundryMax = new Point3D(halfSize, halfSize, halfSize);

            _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 = _colors.BoundryLines;
            _viewport.Children.Add(_boundryLines);

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

            #endregion
            #region Materials

            _materialManager = new MaterialManager(_world);

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

            // Ship
            material = new Game.Newt.v2.NewtonDynamics.Material();
            material.Elasticity = .75d;
            material.StaticFriction = .5d;
            material.KineticFriction = .2d;
            _material_Bot = _materialManager.AddMaterial(material);

            // Sand
            material = new Game.Newt.v2.NewtonDynamics.Material();
            material.Elasticity = .5d;
            material.StaticFriction = .5d;
            material.KineticFriction = .33d;
            _material_Sand = _materialManager.AddMaterial(material);

            _materialManager.RegisterCollisionEvent(_material_Bot, _material_Asteroid, Collision_Ship);
            _materialManager.RegisterCollisionEvent(_material_Bot, _material_Sand, Collision_Sand);

            #endregion

            _map = new Map(_viewport, null, _world);
            //_map.SnapshotFequency_Milliseconds = 125;
            //_map.SnapshotMaxItemsPerNode = 10;
            _map.ShouldBuildSnapshots = false;
            //_map.ShouldShowSnapshotLines = true;
            //_map.ShouldSnapshotCentersDrift = false;

            _radiation = new RadiationField();
            _radiation.AmbientRadiation = 1d;

            _gravity = new GravityFieldUniform();

            _world.UnPause();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                #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);

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

                #endregion
                #region Map

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

                #endregion
                #region Update Manager

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

                #endregion

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                // Init World
                _world = new World();
                //_world.SetSolverModel(SolverModel.ExactMode);		// all of them are slower than adaptive
                _world.Updating += new EventHandler<WorldUpdatingArgs>(World_Updating);
                _world.SetWorldSize(new Point3D(-1000, -1000, -1000), new Point3D(1000, 1000, 1000));
                _world.UnPause();

                #region Materials

                _materialManager = new MaterialManager(_world);

                // Terrain
                Game.Newt.v2.NewtonDynamics.Material material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .2d;
                _material_Terrain = _materialManager.AddMaterial(material);

                // Brick
                material = new Game.Newt.v2.NewtonDynamics.Material();
                _material_Brick = _materialManager.AddMaterial(material);

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

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

                _materialManager.RegisterCollisionEvent(_material_Projectile, _material_Brick, Collision_ProjectileBrick);
                _materialManager.RegisterCollisionEvent(_material_Brick, _material_Brick, Collision_BrickBrick);

                #endregion

                #region Terrain

                #region WPF Model (plus collision hull)

                // Material
                MaterialGroup materials = new MaterialGroup();
                materials.Children.Add(new DiffuseMaterial(new SolidColorBrush(Color.FromArgb(255, 110, 96, 72))));
                materials.Children.Add(new SpecularMaterial(new SolidColorBrush(UtilityWPF.AlphaBlend(Colors.Ivory, Colors.Transparent, .15d)), 25d));

                // Geometry Model
                GeometryModel3D geometry = new GeometryModel3D();
                geometry.Material = materials;
                geometry.BackMaterial = materials;

                double terrainHeight = TERRAINRADIUS / 10d;

                geometry.Geometry = UtilityWPF.GetCylinder_AlongX(100, TERRAINRADIUS, terrainHeight);
                CollisionHull hull = CollisionHull.CreateCylinder(_world, 0, TERRAINRADIUS, terrainHeight, null);

                // Transform
                Transform3DGroup transform = new Transform3DGroup();		// rotate needs to be added before translate
                transform.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), -90)));
                transform.Children.Add(new TranslateTransform3D(new Vector3D(0, 0, terrainHeight / -2d)));		// I want the objects to be able to add to z=0

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

                // Add to the viewport
                _viewport.Children.Add(model);

                #endregion

                // Make a physics body that represents this shape
                _terrain = new Body(hull, transform.Value, 0, new Visual3D[] { model });		// using zero mass tells newton it's static scenery (stuff bounces off of it, but it will never move)
                hull.Dispose();
                _terrain.MaterialGroupID = _material_Terrain;



                //AddDebugDot(new Point3D(0, 0, 0), 5, Colors.Yellow);
                //AddDebugDot(new Point3D(0, 0, 8), 3, Colors.Yellow);
                //AddDebugDot(new Point3D(0, 0, 12), 1, Colors.Yellow);


                #endregion

                // 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.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.MouseComplete));
                //_trackball.GetOrbitRadius += new GetOrbitRadiusHandler(Trackball_GetOrbitRadius);

                RadioLeftClick_Checked(this, new RoutedEventArgs());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }