Beispiel #1
1
        public Human(Game game, SpriteBatch screenSpriteBatch,
            PlayerSide playerSide)
            : base(game, screenSpriteBatch)
        {
            string idleTextureName = "";
            this.playerSide = playerSide;

            if (playerSide == PlayerSide.Left)
            {
                catapultPosition = new Vector2(140, 332);
                idleTextureName = "Textures/Catapults/Blue/blueIdle/blueIdle";
            }
            else
            {
                catapultPosition = new Vector2(600, 332);
                spriteEffect = SpriteEffects.FlipHorizontally;
                idleTextureName = "Textures/Catapults/Red/redIdle/redIdle";
            }

            Catapult = new Catapult(game, screenSpriteBatch,
                                    idleTextureName, catapultPosition,
                                    spriteEffect,
                                    playerSide == PlayerSide.Left
                                        ? false : true, true);
        }
Beispiel #2
1
		public Board(Game game, int posX = 224, int posY = 64, int width = 384, int height = 384)
			: base(game) {
			State = EBoardState.Initialize;
			Score = 0;

			Bounds = new Rectangle(posX, posY, width, height);
		}
 /// <summary>
 /// Initialize game
 /// </summary>
 /// <param name="game">game</param>
 public static void Initialize(Game game)
 {
     if (instance == null)
     {
         instance = new ZRTSCompositeViewUIFactory(game);
     }
 }
Beispiel #4
0
        public Bus(Game game, GraphicsDeviceManager graphics, Vector2 location)
            : base(game, graphics, "content/bus", true)
        {
            this.mLocation = location;

     
        }
 public ActionScene(
     IController playerOneController,
     IController playerTwoController,
     Game game,
     Texture2D theTexture,
     Texture2D backgroundTexture,
     Rectangle screenBounds,
     SpriteFont font,
     Vector2 gameoverPosition)
     : this(game, theTexture, backgroundTexture, font, gameoverPosition)
 {
     this.TwoPlayers = true;
     this._player1 = new Player(Game, ref this._actionTexture, new Vector2(x: screenBounds.Width / 3, y: 0), new Rectangle(323, 15, 30, 30), playerOneController);
     this._player1.Initialize();
     Components.Add(this._player1);
     this._scorePlayer2 = new Score(game, font, Color.Red)
                        {
                            Position =
                                new Vector2(
                                this.Game.Window.ClientBounds.Width - 200, 10)
                        };
     Components.Add(this._scorePlayer2);
     this._player2 = new Player(Game, ref this._actionTexture, new Vector2((int)(screenBounds.Width / 1.5), 0), new Rectangle(360, 17, 30, 30), playerTwoController);
     this._player2.Initialize();
     Components.Add(this._player2);
 }
Beispiel #6
0
		public GameWindow(Game game, RectangleF frame) : base (frame)
		{
            if (game == null)
                throw new ArgumentNullException("game");
            _game = game;
            _platform = (MacGamePlatform)_game.Services.GetService(typeof(MacGamePlatform));

			//LayerRetainsBacking = false; 
			//LayerColorFormat	= EAGLColorFormat.RGBA8;
			this.AutoresizingMask = MonoMac.AppKit.NSViewResizingMask.HeightSizable
					| MonoMac.AppKit.NSViewResizingMask.MaxXMargin 
					| MonoMac.AppKit.NSViewResizingMask.MinYMargin
					| MonoMac.AppKit.NSViewResizingMask.WidthSizable;
			
			RectangleF rect = NSScreen.MainScreen.Frame;
			
			clientBounds = new Rectangle (0,0,(int)rect.Width,(int)rect.Height);

			// Enable multi-touch
			//MultipleTouchEnabled = true;

			// Initialize GameTime
			_updateGameTime = new GameTime ();
			_drawGameTime = new GameTime (); 

			// Initialize _lastUpdate
			_lastUpdate = DateTime.Now;
		}
        public MonoGameAndroidGameView(Context context, AndroidGameWindow androidGameWindow, Game game)
            : base(context)
        {
            _gameWindow = androidGameWindow;
			_game = game;
            _touchManager = new AndroidTouchEventManager(androidGameWindow);
        }
Beispiel #8
0
 public AudioController(Game game, bool muted, bool playing)
     : base(game)
 {
     this.muted = muted;
     this.playing = playing;
     this.game = (LeGame)game;
 }
        public AndroidGameWindow(AndroidGameActivity activity, Game game)
        {
            _game = game;
            Initialize(activity);

            game.Services.AddService(typeof(View), GameView);
        }
Beispiel #10
0
 public Interface(Game game)
     : base(game)
 {
     _font = Game.Content.Load<SpriteFont>("Test");
     _heartTexture = Game.Content.Load<Texture2D>("heart");
     _potionTexture = Game.Content.Load<Texture2D>("potion");
 }
Beispiel #11
0
 public SceneManager(Game game)
     : base(game)
 {
     Game.Components.Add(this);
     Game.Services.AddService(typeof(SceneManager), this);
     Game.Services.AddService(typeof(ISceneManager), this);
 }
Beispiel #12
0
        public APNGHelper(Game game, string pngFile)
        {
            this.game = game;

            var image = new APNG(pngFile);
            numPlays = (int)image.acTLChunk.NumPlays;
            baseFrame = new APNGFrame(game, image.DefaultImage);

            if (image.IsSimplePNG)
            {
                CurrentFrame = baseFrame.FrameTexture;
            }
            else
            {
                numPlays = (int)image.acTLChunk.NumPlays;

                foreach (Frame frame in image.Frames)
                {
                    frameList.Add(new APNGFrame(this.game, frame));
                }

                sb = new SpriteBatch(this.game.GraphicsDevice);

                RenderEachFrame();

                CurrentFrame = renderedTextureList[0];
            }
        }
        public InputComponent(Game game)
            : base(game)
        {
            InteractTrigger = new Trigger<bool>();
            ApplyTrigger = new Trigger<bool>();
            InventoryTrigger = new Trigger<bool>();
            JumpTrigger = new Trigger<bool>();
            SlotLeftTrigger = new Trigger<bool>();
            SlotRightTrigger = new Trigger<bool>();
            SlotTrigger = new Trigger<bool>[SlotTriggerLength];
            for (int i = 0; i < SlotTrigger.Length; i++)
                SlotTrigger[i] = new Trigger<bool>();

            gamepad = new GamePadInput();
            keyboard = new KeyboardInput();
            mouse = new MouseInput(game);
            screenMouse = new MouseScreenInput();

            inputDevices = new List<IInputSet>{
                gamepad,
                keyboard,
                mouse
            };

            screenInputDevices = new List<IScreenInputSet>{
                screenMouse
            };
        }
 public FrameRateCounter(Game game)
     : base(game)
 {
     this.frameRate = 0;
     this.frameCounter = 0;
     this.secondsPassed = 0;
 }
Beispiel #15
0
 public GameState(Game game, GameStateManager manager)
     : base(game)
 {
     StateManager = manager;
     childComponents = new List<GameComponent>();
     tag = this;
 }
Beispiel #16
0
        private Texture2D texturaSelecionado; //  botão em estado selecionado

        #endregion Fields

        #region Constructors

        public clsButton(Game game, Texture2D TexturaNaoSelecionado, Texture2D TexturaSelecionado, Vector2 Posicao, EventHandler evento)
        {
            texturaNaoSelecionado = TexturaNaoSelecionado;
            texturaSelecionado = TexturaSelecionado;
            posicao = Posicao;
            eventoClick = evento;
        }
Beispiel #17
0
 public Atelier(Game jeu, List<GameComponent> listeGameComponentsMenu, string nomModèleJoueur, int nbEnnemis)
     :base(jeu)
 {
     ListeGameComponentsMenu = listeGameComponentsMenu;
     NomModèleJoueur = nomModèleJoueur;
     NbEnnemis = nbEnnemis;
 }
Beispiel #18
0
 public LoadingScreen(Game game, GraphicsDeviceManager graphics, object[] parameters)
     : base(game)
 {
     this.game = game;
     this.graphics = graphics;
     isSave = (parameters[0].Equals("Save"));
 }
 public SplashScreen(Game game)
     : base(game)
 {
     this.game = game;
     game1 = (Game1)game;
     // TODO: Construct any child components here
 }
        public HeightMapModel2(Game game, HeightMap info, Boolean t, Vector3 pos, float scale)
            : base(game , null, t, pos, scale)
        {
            // Game game, Model m, Boolean t, Vector3 pos, float scale, Boolean solid
            //Game game, HeightMap m, Boolean t, Vector3 pos, float scale

            this.Visible = false;
            Body = new Body();
            Skin = new CollisionSkin(null);
            //Skin.CollisionType = (int)CollisionTypes.Terrain;

            Array2D field = new Array2D(info.heights.GetUpperBound(0), info.heights.GetUpperBound(1));

            for (int x = 0; x < info.heights.GetUpperBound(0); x++)
            {
                for (int z = 0; z < info.heights.GetUpperBound(1); z++)
                {
                    field.SetAt(x, z, info.heights[x, z]);
                }
            }

            Body.MoveTo(new Vector3(info.heightmapPosition.X, info.heightmapPosition.Y, info.heightmapPosition.Y), Matrix.Identity);

            Skin.AddPrimitive(new Heightmap(field, info.heightmapPosition.X, info.heightmapPosition.Y, scale, scale), (int)MaterialTable.MaterialID.NotBouncyRough);

            Body.Immovable = true;

            PhysicsSystem.CurrentPhysicsSystem.CollisionSystem.AddCollisionSkin(Skin);
        }
Beispiel #21
0
 public Player(Game game, Character character)
 {
     gameRef = (Game1)game;
     camera = new Camera(gameRef.ScreenRectangle);
     this.character = character;
     Sprite.Position = new Vector2(1000, 1000);
 }
Beispiel #22
0
 // this constructor doesn't really do much of anything, just calls the base
 // constructor, and saves the contentmanager so it can be used in
 // LoadContent.
 public Cursor(Game game, ContentManager content)
     : base(game)
 {
     this.content = content;
     currentMouseState = Mouse.GetState();
     previousMouseState = Mouse.GetState();
 }
Beispiel #23
0
 /// <summary>
 /// Constructs a new screen manager component.
 /// </summary>
 public ScreenManager(Game game)
     : base(game)
 {
     // we must set EnabledGestures before we can query for them, but
     // we don't assume the game wants to read them.
     TouchPanel.EnabledGestures = GestureType.None;
 }
Beispiel #24
0
        public Cmc(Game game)
            : base(game)
        {
            cmcTextures = new Texture2D[3];
            cmcTextures[0] = game.Content.Load<Texture2D>("cmc1");
            cmcTextures[1] = game.Content.Load<Texture2D>("cmc2");
            cmcTextures[2] = game.Content.Load<Texture2D>("cmc3");

            cmcTexels = new Color[3][];
            for (int i = 0; i < 3; i++)
            {
                cmcTexels[i] = new Color[WIDTH * HEIGHT];
                cmcTextures[i].GetData<Color>(cmcTexels[i]);
            }

            cmcChannels = new Color[][] {
                new Color[] { new Color(210, 20, 255), new Color(220, 220, 220) },       //Purple and gray for Sweetie Belle
                new Color[] { new Color(255, 150, 40), new Color(255, 64, 192) },       //Orange and maroon for Scootaloo
                new Color[] { new Color(255, 255, 0), new Color(255, 0, 64) }         //Yellow and red for Apple Bloom
            };

            texture = new Texture2D(device, WIDTH, HEIGHT);
            textureColors = new Color[WIDTH * HEIGHT];

            PrecalculatePoints();
        }
Beispiel #25
0
 public GameObject(Game1 game, Vector2 startLocation)
 {
     this.Game = game;
     this.Location = startLocation;
     this.Transparency = 1;
     SpriteEffect = SpriteEffects.None;
 }
Beispiel #26
0
        public CarObject(Game game, Model model,Model wheels, bool FWDrive,
                       bool RWDrive,
                       float maxSteerAngle,
                       float steerRate,
                       float wheelSideFriction,
                       float wheelFwdFriction,
                       float wheelTravel,
                       float wheelRadius,
                       float wheelZOffset,
                       float wheelRestingFrac,
                       float wheelDampingFrac,
                       int wheelNumRays,
                       float driveTorque,
                       float gravity)
            : base(game, model)
        {
            car = new Car(FWDrive, RWDrive, maxSteerAngle, steerRate,
                wheelSideFriction, wheelFwdFriction, wheelTravel, wheelRadius,
                wheelZOffset, wheelRestingFrac, wheelDampingFrac,
                wheelNumRays, driveTorque, gravity);

            this.body = car.Chassis.Body;
            this.collision = car.Chassis.Skin;
            this.wheel = wheels;

            SetCarMass(100.0f);
        }
 public EntitéPhysiqueGraphique(Game jeu, string nomModele, Vector3 position,Vector3 dimension, float intervalMAJ)
    :base(jeu,position, intervalMAJ)
 {
     Dimension = dimension;
    NomModèle = nomModele;
    Échelle = 1;
 }
Beispiel #28
0
 public void Initialize(Game game, SpriteBatch spriteBatch, ICamera2D camera)
 {
     for (int i = 0; i < _nanobots.Count; i++)
        {
        _nanobots[i].Initialize(game, spriteBatch, camera);
        }
 }
Beispiel #29
0
 public ScreenItem(Game game, ApplicationSkin applicationSkin, float x, float y, float width, float height)
     : base(game)
 {
     _position = new Vector2(x, y);
     _size = new Vector2(width, height);
     skin = applicationSkin;
 }
Beispiel #30
0
 public PauseScreenController(Game game, SpriteBatch sb)
     : base(game)
 {
     spriteBatch = sb;
        // graphics = new GraphicsDevice(game);
     // TODO: Construct any child components here
 }
Beispiel #31
0
        public FacialAnimationSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            _graphicsScreen = new DeferredGraphicsScreen(Services)
            {
                DrawReticle = false
            };
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add a game object which adds some GUI controls for the deferred graphics
            // screen to the Options window.
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            // Use a fixed camera.
            var projection = new PerspectiveProjection();

            projection.SetFieldOfView(
                ConstantsF.PiOver4,
                GraphicsService.GraphicsDevice.Viewport.AspectRatio,
                0.1f,
                10);
            var cameraNode = new CameraNode(new Camera(projection));

            cameraNode.LookAt(new Vector3(0.15f, 0.15f, 0.5f), new Vector3(0.1f, 0.15f, 0), Vector3.Up);
            _graphicsScreen.Scene.Children.Add(cameraNode);
            _graphicsScreen.ActiveCameraNode = cameraNode;

            // Lighting setup:
            var keyLight = new LightNode(new Spotlight {
                DiffuseIntensity = 0.6f, SpecularIntensity = 0.4f
            });

            keyLight.LookAt(new Vector3(-2, 2, 2), new Vector3(), Vector3.Up);
            _graphicsScreen.Scene.Children.Add(keyLight);

            var backLight = new LightNode(new Spotlight {
                DiffuseIntensity = 0.3f, SpecularIntensity = 0.3f
            });

            backLight.LookAt(new Vector3(1, 0.5f, -2), new Vector3(), Vector3.Up);
            _graphicsScreen.Scene.Children.Add(backLight);

            var fillLight = new LightNode(new AmbientLight {
                HemisphericAttenuation = 1, Intensity = 0.1f
            });

            _graphicsScreen.Scene.Children.Add(fillLight);

            // The scene does not have a proper background. That's why the exposure is a
            // bit off. --> Reduce the max exposure.
            var hdrFilter = _graphicsScreen.PostProcessors.OfType <HdrFilter>().First();

            hdrFilter.MaxExposure = 6;

            // Load the customized "Sintel" model (original: Durian Open Movie Project - http://www.sintel.org/).
            var model = ContentManager.Load <ModelNode>("Sintel/Sintel-Head").Clone();

            model.PoseWorld = new Pose(new Vector3(0, 0, 0), Matrix.CreateRotationY(MathHelper.ToRadians(10)) * Matrix.CreateRotationX(-MathHelper.ToRadians(90)));
            _graphicsScreen.Scene.Children.Add(model);

            // The model consists of a root node and a mesh node.
            //  ModelNode "Sintel-Head"
            //    MeshNode "Sintel"
            _sintel = (MeshNode)model.Children[0];

            // The model contains two skeletal animations:
            // - "MOUTH-open" is just a single frame.
            // - "Test" is a short animation (250 frames).

            // In the Options window, we will add a slider to move the jaw.
            // Slider.Value = 0 ... mouth closed (default)
            _mouthClosedPose = SkeletonPose.Create(_sintel.Mesh.Skeleton);
            // Slider.Value = 1 ... mouth open (copied from the "MOUTH-open" animation)
            SkeletonKeyFrameAnimation mouthOpen = _sintel.Mesh.Animations["MOUTH-open"];

            _mouthOpenPose = SkeletonPose.Create(_sintel.Mesh.Skeleton);
            mouthOpen.GetValue(TimeSpan.Zero, ref _mouthOpenPose, ref _mouthOpenPose, ref _mouthOpenPose);

            // Turn the "Test" animation into an endless loop.
            _skeletalAnimation = new AnimationClip <SkeletonPose>(_sintel.Mesh.Animations["Test"])
            {
                Duration     = TimeSpan.MaxValue,
                LoopBehavior = LoopBehavior.Cycle
            };

            // Mesh has several morph targets for facial animation, which are imported
            // automatically via the content pipeline. Unfortunately, the XNA content
            // pipeline cannot import morph target animations automatically.
            // In this demo, we will create a morph target animation in code.
            _morphingAnimation = CreateMorphingAnimation();

            CreateGuiControls();
        }
        private bool _cullingEnabled = true;  // True to use frustum culling. False to disable frustum culling.


        public FrustumCullingSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            GraphicsScreen.ClearBackground = true;
            GraphicsScreen.BackgroundColor = Color.CornflowerBlue;

            // The top-down camera.
            var orthographicProjection = new OrthographicProjection();

            orthographicProjection.Set(
                LevelSize * 1.1f * GraphicsService.GraphicsDevice.Viewport.AspectRatio,
                LevelSize * 1.1f,
                1,
                10000f);
            var topDownCamera = new Camera(orthographicProjection);

            _topDownCameraNode = new CameraNode(topDownCamera)
            {
                View = Matrix44F.CreateLookAt(new Vector3F(0, 1000, 0), new Vector3F(0, 0, 0), -Vector3F.UnitZ),
            };

            // The perspective camera moving through the scene.
            var perspectiveProjection = new PerspectiveProjection();

            perspectiveProjection.SetFieldOfView(
                MathHelper.ToRadians(45),
                GraphicsService.GraphicsDevice.Viewport.AspectRatio,
                1,
                500);
            var sceneCamera = new Camera(perspectiveProjection);

            _sceneCameraNode = new CameraNode(sceneCamera);

            // Initialize collision detection.
            // We use one collision domain that manages all objects.
            _domain = new CollisionDomain(new CollisionDetection())
            {
                // We exchange the default broad phase with a DualPartition. The DualPartition
                // has special support for frustum culling.
                BroadPhase = new DualPartition <CollisionObject>(),
            };

            // Create a lot of random objects and add them to the collision domain.
            RandomHelper.Random = new Random(12345);
            for (int i = 0; i < NumberOfObjects; i++)
            {
                // A real scene consists of a lot of complex objects such as characters, vehicles,
                // buildings, lights, etc. When doing frustum culling we need to test each objects against
                // the viewing frustum. If it intersects with the viewing frustum, the object is visible
                // from the camera's point of view. However, in practice we do not test the exact object
                // against the viewing frustum. Each objects is approximated by a simpler shape. In our
                // example, we assume that each object is approximated with an oriented bounding box.
                // (We could also use an other shape, such as a bounding sphere.)

                // Create a random box.
                Shape randomShape = new BoxShape(RandomHelper.Random.NextVector3F(1, 10));

                // Create a random position.
                Vector3F randomPosition;
                randomPosition.X = RandomHelper.Random.NextFloat(-LevelSize / 2, LevelSize / 2);
                randomPosition.Y = RandomHelper.Random.NextFloat(0, 2);
                randomPosition.Z = RandomHelper.Random.NextFloat(-LevelSize / 2, LevelSize / 2);

                // Create a random orientation.
                QuaternionF randomOrientation = RandomHelper.Random.NextQuaternionF();

                // Create object and add it to collision domain.
                var geometricObject = new GeometricObject(randomShape, new Pose(randomPosition, randomOrientation));
                var collisionObject = new CollisionObject(geometricObject)
                {
                    CollisionGroup = 0,
                };
                _domain.CollisionObjects.Add(collisionObject);
            }

            // Per default, the collision domain computes collision between all objects.
            // In this sample we do not need this information and disable it with a collision
            // filter.
            // In a real application, we would use this collision information for rendering,
            // for example, to find out which lights overlap with which meshes, etc.
            var filter = new CollisionFilter();

            // Disable collision between objects in collision group 0.
            filter.Set(0, 0, false);
            _domain.CollisionDetection.CollisionFilter = filter;

            // Start with the scene camera.
            GraphicsScreen.CameraNode = _sceneCameraNode;

            // We will collect a few statistics for debugging.
            Profiler.SetFormat("NoCull", 1000, "Time in ms to submit DebugRenderer draw jobs without frustum culling.");
            Profiler.SetFormat("WithCull", 1000, "Time in ms to submit DebugRenderer draw jobs with frustum culling.");
        }
Beispiel #33
0
 protected Object(Microsoft.Xna.Framework.Game game, Object parent) : base(game)
 {
     Parent       = parent;
     _spriteBatch = (SpriteBatch)game.Services.GetService(typeof(SpriteBatch));
     Initialize();
 }
        public IntersectionSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;
            var delegateGraphicsScreen = new DelegateGraphicsScreen(GraphicsService)
            {
                RenderCallback = Render,
            };

            GraphicsService.Screens.Insert(0, delegateGraphicsScreen);

            // Add a custom game object which controls the camera.
            _cameraObject = new CameraObject(Services, 10);
            _cameraObject.ResetPose(new Vector3(0, 0, -4), ConstantsF.Pi, 0);
            GameObjectService.Objects.Add(_cameraObject);

            // Create a new scene with some lights.
            _scene = new Scene();
            SceneSample.InitializeDefaultXnaLights(_scene);

            _meshRenderer  = new MeshRenderer();
            _debugRenderer = new DebugRenderer(GraphicsService, null);

            _intersectionRenderer = new IntersectionRenderer(GraphicsService, ContentManager)
            {
                DownsampleFactor = 1,
            };

            //_submeshA = MeshHelper.CreateSubmesh(GraphicsService.GraphicsDevice, new SphereShape(0.5f).GetMesh(0.001f, 5), MathHelper.ToRadians(70));
            //_submeshB = MeshHelper.CreateSubmesh(GraphicsService.GraphicsDevice, new BoxShape(1, 1, 2).GetMesh(0.001f, 5), MathHelper.ToRadians(70));

            var meshNodeA = CreateMeshNode(new[]
            {
                MeshHelper.CreateTorus(GraphicsService.GraphicsDevice, 1, 0.3f, 30),
                MeshHelper.CreateSubmesh(GraphicsService.GraphicsDevice, new BoxShape(1, 1, 2).GetMesh(0.001f, 5), MathHelper.ToRadians(70)),
            },
                                           Color.DarkBlue);

            meshNodeA.PoseWorld = new Pose(RandomHelper.Random.NextVector3(-0.5f, 0.5f),
                                           RandomHelper.Random.NextQuaternion());
            _scene.Children.Add(meshNodeA);
            _debugRenderer.DrawObject(meshNodeA, Color.Green, true, false);

            var shape = new TransformedShape(
                new GeometricObject(new SphereShape(0.5f), new Pose(new Vector3(1, 0, 0))));
            var meshNodeB = CreateMeshNode(new[]
            {
                MeshHelper.CreateTorus(GraphicsService.GraphicsDevice, 1, 0.3f, 30),
                MeshHelper.CreateSubmesh(GraphicsService.GraphicsDevice, shape.GetMesh(0.001f, 4), MathHelper.ToRadians(90)),
            },
                                           Color.Gray);

            meshNodeB.PoseWorld = new Pose(RandomHelper.Random.NextVector3(-1f, 1f),
                                           RandomHelper.Random.NextQuaternion());
            _scene.Children.Add(meshNodeB);
            _debugRenderer.DrawObject(meshNodeB, Color.Green, true, false);

            var meshNodeC = CreateMeshNode(new[]
            {
                MeshHelper.CreateBox(GraphicsService.GraphicsDevice),
                MeshHelper.CreateSubmesh(GraphicsService.GraphicsDevice, new BoxShape(1, 1, 2).GetMesh(0.001f, 5), MathHelper.ToRadians(70))
            },
                                           Color.DarkGreen);

            meshNodeC.PoseWorld = new Pose(RandomHelper.Random.NextVector3(-1f, 1f),
                                           RandomHelper.Random.NextQuaternion());
            meshNodeC.ScaleLocal = new Vector3(0.1f, 1f, 0.5f);
            _scene.Children.Add(meshNodeC);
            _debugRenderer.DrawObject(meshNodeC, Color.Green, true, false);

            _meshNodePairs.Add(new Pair <MeshNode>(meshNodeA, meshNodeB));
            _meshNodePairs.Add(new Pair <MeshNode>(meshNodeA, meshNodeC));
            _meshNodePairs.Add(new Pair <MeshNode>(meshNodeB, meshNodeC));

            CreateGuiControls();
        }
Beispiel #35
0
        public VolumetricLightSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            // Create a graphics screen. This screen has to call the VolumetricLightRenderer
            // to handle the VolumetricLightNode!
            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true)
            {
#if XBOX
                Time = new DateTime(2014, 06, 01, 0, 0, 0, 0),
#else
                Time = new DateTimeOffset(2014, 06, 01, 0, 0, 0, 0, TimeSpan.Zero),
#endif
            });

            //GameObjectService.Objects.Add(new GroundObject(Services));
            // Add a ground plane with some detail to see the water refractions.
            Simulation.RigidBodies.Add(new RigidBody(new PlaneShape(new Vector3F(0, 1, 0), 0)));
            GameObjectService.Objects.Add(new StaticObject(Services, "Gravel/Gravel", 1, new Pose(new Vector3F(0, 0.001f, 0))));

            GameObjectService.Objects.Add(new DudeObject(Services));
            GameObjectService.Objects.Add(new DynamicObject(Services, 1));
            GameObjectService.Objects.Add(new DynamicObject(Services, 2));
            GameObjectService.Objects.Add(new DynamicObject(Services, 3));
            GameObjectService.Objects.Add(new DynamicObject(Services, 4));
            GameObjectService.Objects.Add(new DynamicObject(Services, 5));
            GameObjectService.Objects.Add(new DynamicObject(Services, 6));
            GameObjectService.Objects.Add(new DynamicObject(Services, 7));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new FogObject(Services));

            var lavaBallsObject = new LavaBallsObject(Services);
            GameObjectService.Objects.Add(lavaBallsObject);
            lavaBallsObject.Spawn();

            // Add a few palm trees.
            Random random = new Random(12345);
            for (int i = 0; i < 10; i++)
            {
                Vector3F  position    = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
                Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float     scale       = random.NextFloat(0.5f, 1.2f);
                GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }

            // Add some additional test lights
            GameObjectService.Objects.Add(new TestLightsObject(Services));

            // The following lights are not needed.
            _graphicsScreen.Scene.GetDescendants().First(n => n.Name == "AmbientLight").IsEnabled = false;
            _graphicsScreen.Scene.GetDescendants().First(n => n.Name == "DirectionalLightWithShadow").IsEnabled = false;

            // Add a volumetric light node under each light node (except ambient and directional lights).
            foreach (var lightNode in _graphicsScreen.Scene.GetSubtree().OfType <LightNode>())
            {
                if (lightNode.Light is PointLight || lightNode.Light is Spotlight || lightNode.Light is ProjectorLight)
                {
                    if (lightNode.Children == null)
                    {
                        lightNode.Children = new SceneNodeCollection();
                    }

                    lightNode.Children.Add(new VolumetricLightNode
                    {
                        Color           = new Vector3F(0.1f),
                        NumberOfSamples = _numberOfSamples,
                        MipMapBias      = _mipMapBias,
                    });
                }
            }

            // Get the renderer used by the screen.
            _volumetricLightRenderer = _graphicsScreen.AlphaBlendSceneRenderer.Renderers.OfType <VolumetricLightRenderer>().First();
        }
Beispiel #36
0
        public BillboardSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            _delegateGraphicsScreen = new DelegateGraphicsScreen(GraphicsService)
            {
                RenderCallback = Render,
            };
            GraphicsService.Screens.Insert(0, _delegateGraphicsScreen);

            // Add a custom game object which controls the camera.
            _cameraObject = new CameraObject(Services);
            GameObjectService.Objects.Add(_cameraObject);

            // In this example we need three renderers:
            // The MeshRenderer handles MeshNodes.
            _meshRenderer = new MeshRenderer();

            // The BillboardRenderer handles BillboardNodes and ParticleSystemNodes.
            _billboardRenderer = new BillboardRenderer(GraphicsService, 2048);

            // The DebugRenderer is used to draw text.
            var spriteFont = UIContentManager.Load <SpriteFont>("Default");

            _debugRenderer = new DebugRenderer(GraphicsService, spriteFont);

            // Create a new empty scene.
            _scene = new Scene();

            // Add the camera node to the scene.
            _scene.Children.Add(_cameraObject.CameraNode);

            // Add a few models to the scene.
            var sandbox = ContentManager.Load <ModelNode>("Sandbox/Sandbox").Clone();

            _scene.Children.Add(sandbox);

            // Add some lights to the scene which have the same properties as the lights
            // of BasicEffect.EnableDefaultLighting().
            SceneSample.InitializeDefaultXnaLights(_scene);

            var texture = new PackedTexture(ContentManager.Load <Texture2D>("Billboard/BillboardReference"));

            // ----- View plane-aligned billboards with variations.
            // View plane-aligned billboards are rendered parallel to the screen.
            // The up-axis of the BillboardNode determines the up direction of the
            // billboard.
            var pose0         = new Pose(new Vector3F(-9, 1.0f, 1.5f));
            var pose1         = pose0;
            var billboard     = new ImageBillboard(texture);
            var billboardNode = new BillboardNode(billboard);

            billboardNode.Name      = "View plane-aligned\nVarying color\nVarying alpha";
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            billboardNode.Color     = new Vector3F(1, 0, 0);
            billboardNode.Alpha     = 0.9f;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            billboardNode.Color     = new Vector3F(0, 1, 0);
            billboardNode.Alpha     = 0.7f;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            billboardNode.Color     = new Vector3F(0, 0, 1);
            billboardNode.Alpha     = 0.3f;
            _scene.Children.Add(billboardNode);

            // ----- View plane-aligned billboards with different blend modes
            // blend mode = 0 ... additive blend
            // blend mode = 1 ... alpha blend
            pose0.Position.X       += 2;
            pose1                   = pose0;
            billboard               = new ImageBillboard(texture);
            billboard.BlendMode     = 0.0f;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.Name      = "View plane-aligned\nVarying blend mode";
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboard               = new ImageBillboard(texture);
            billboard.BlendMode     = 0.333f;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboard               = new ImageBillboard(texture);
            billboard.BlendMode     = 0.667f;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboard               = new ImageBillboard(texture);
            billboard.BlendMode     = 1.0f;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            // ----- View plane-aligned billboards with alpha test
            pose0.Position.X       += 2;
            pose1                   = pose0;
            billboard               = new ImageBillboard(texture);
            billboard.AlphaTest     = 0.9f;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.Name      = "View plane-aligned\nVarying reference alpha";
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboard               = new ImageBillboard(texture);
            billboard.AlphaTest     = 0.667f;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboard               = new ImageBillboard(texture);
            billboard.AlphaTest     = 0.333f;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboard               = new ImageBillboard(texture);
            billboard.AlphaTest     = 0.0f;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            // ----- View plane-aligned billboards with different scale and rotation
            pose0.Position.X        += 2;
            pose1                    = pose0;
            billboard                = new ImageBillboard(texture);
            billboard.Orientation    = BillboardOrientation.ViewPlaneAligned;
            billboardNode            = new BillboardNode(billboard);
            billboardNode.Name       = "View plane-aligned\nVarying scale\nVarying rotation";
            billboardNode.PoseWorld  = pose1;
            billboardNode.ScaleLocal = new Vector3F(0.4f);
            _scene.Children.Add(billboardNode);

            pose1.Position.Z        -= 1;
            billboardNode            = billboardNode.Clone();
            billboardNode.Name       = null;
            billboardNode.PoseWorld  = pose1 * new Pose(Matrix33F.CreateRotationZ(MathHelper.ToRadians(-15)));
            billboardNode.ScaleLocal = new Vector3F(0.6f);
            _scene.Children.Add(billboardNode);

            pose1.Position.Z        -= 1;
            billboardNode            = billboardNode.Clone();
            billboardNode.Name       = null;
            billboardNode.PoseWorld  = pose1 * new Pose(Matrix33F.CreateRotationZ(MathHelper.ToRadians(-30)));
            billboardNode.ScaleLocal = new Vector3F(0.8f);
            _scene.Children.Add(billboardNode);

            pose1.Position.Z        -= 1;
            billboardNode            = billboardNode.Clone();
            billboardNode.Name       = null;
            billboardNode.PoseWorld  = pose1 * new Pose(Matrix33F.CreateRotationZ(MathHelper.ToRadians(-45)));
            billboardNode.ScaleLocal = new Vector3F(1.0f);
            _scene.Children.Add(billboardNode);

            // ----- Viewpoint-oriented billboards
            // Viewpoint-orientated billboards always face the player. (The face normal
            // points directly to the camera.)
            pose0.Position.X       += 2;
            pose1                   = pose0;
            billboard               = new ImageBillboard(texture);
            billboard.Orientation   = BillboardOrientation.ViewpointOriented;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.Name      = "Viewpoint-oriented";
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            // ----- Screen-aligned billboards
            // View plane-aligned billboards and screen-aligned billboards are similar. The
            // billboards are rendered parallel to the screen. The orientation can be changed
            // by rotating the BillboardNode. The difference is that the orientation of view
            // plane-aligned billboards is relative to world space and the orientation of
            // screen-aligned billboards is relative to view space.
            // Screen-aligned billboards are, for example, used for text label.
            pose0.Position.X       += 2;
            pose1                   = pose0;
            billboard               = new ImageBillboard(texture);
            billboard.Orientation   = BillboardOrientation.ScreenAligned;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.Name      = "Screen-aligned";
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            // ----- Axial, view plane-aligned billboards
            pose0.Position.X       += 2;
            pose1                   = pose0;
            billboard               = new ImageBillboard(texture);
            billboard.Orientation   = BillboardOrientation.AxialViewPlaneAligned;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.Name      = "Axial, view plane-aligned";
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = billboardNode.Clone();
            billboardNode.Name      = null;
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            // ----- Axial, viewpoint-oriented billboards
            pose0.Position.X       += 2;
            pose1                   = pose0;
            billboard               = new ImageBillboard(texture);
            billboard.Orientation   = BillboardOrientation.AxialViewpointOriented;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.Name      = "Axial, viewpoint-oriented";
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            // ----- World-oriented billboards
            // World-oriented billboards have a fixed orientation in world space. The
            // orientation is determine by the BillboardNode.
            pose0.Position.X       += 2;
            pose1                   = pose0;
            pose1.Orientation      *= Matrix33F.CreateRotationY(0.2f);
            billboard               = new ImageBillboard(texture);
            billboard.Orientation   = BillboardOrientation.WorldOriented;
            billboardNode           = new BillboardNode(billboard);
            billboardNode.Name      = "World-oriented";
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            pose1.Orientation      *= Matrix33F.CreateRotationY(0.2f);
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1 * new Pose(Matrix33F.CreateRotationZ(MathHelper.ToRadians(15)));
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            pose1.Orientation      *= Matrix33F.CreateRotationY(0.2f);
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1 * new Pose(Matrix33F.CreateRotationZ(MathHelper.ToRadians(30)));
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            pose1.Orientation      *= Matrix33F.CreateRotationY(0.2f);
            billboardNode           = new BillboardNode(billboard);
            billboardNode.PoseWorld = pose1 * new Pose(Matrix33F.CreateRotationZ(MathHelper.ToRadians(45)));
            _scene.Children.Add(billboardNode);

            // ----- Animated billboards
            // DigitalRune Graphics supports "texture atlases". I.e. textures can be packed
            // together into a single, larger texture file. A PackedTexture can describe a
            // single texture packed into a texture atlas or a tile set packed into a
            // texture atlas. In this example the "beeWingFlap" is a set of three tiles.
            // Tile sets can be used for sprite animations. (The animation is set below in
            // Update().)
            pose0.Position.X       += 2;
            pose1                   = pose0;
            texture                 = new PackedTexture("Bee", ContentManager.Load <Texture2D>("Particles/beeWingFlap"), Vector2F.Zero, Vector2F.One, 3, 1);
            _animatedBillboard      = new ImageBillboard(texture);
            billboardNode           = new BillboardNode(_animatedBillboard);
            billboardNode.Name      = "Animated billboards";
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(_animatedBillboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            pose1.Position.Z       -= 1;
            billboardNode           = new BillboardNode(_animatedBillboard);
            billboardNode.PoseWorld = pose1;
            _scene.Children.Add(billboardNode);

            // Use DebugRenderer to draw node names above billboard nodes.
            foreach (var node in _scene.GetDescendants().OfType <BillboardNode>())
            {
                _debugRenderer.DrawText(node.Name, node.PoseWorld.Position + new Vector3F(0, 1, 0), new Vector2F(0.5f), Color.Yellow, false);
            }
        }
        public HealthBarSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            // The base class has created the graphics screen for the 3D objects.
            GraphicsScreen.ClearBackground = true;
            GraphicsScreen.BackgroundColor = Color.CornflowerBlue;
            SetCamera(new Vector3F(0, 1, 3), 0, 0);
            _cameraObject = GameObjectService.Objects.OfType <CameraObject>().First();

            // We add another graphics screen on top which renders the GUI.
            var graphicsScreen = new DelegateGraphicsScreen(GraphicsService)
            {
                RenderCallback = Render,
            };

            GraphicsService.Screens.Insert(1, graphicsScreen);

            // Create a UIScreen.
            Theme      theme    = ContentManager.Load <Theme>("UI Themes/BlendBlue/Theme");
            UIRenderer renderer = new UIRenderer(Game, theme);

            _uiScreen = new UIScreen("HealthBarScreen", renderer)
            {
                Background = Color.Transparent, // Background must not hide the 3D graphics screen.
            };
            UIService.Screens.Add(_uiScreen);

            // Standard force effects.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Standard game objects.
            GameObjectService.Objects.Add(new GroundObject(Services));

            // Create a new game object property. This allows to attach a z value to all UIControls.
            _zPropertyId = UIControl.CreateProperty <float>(
                typeof(UIControl),
                "Z",
                GamePropertyCategories.Appearance,
                "The layer depth. Objects with lower depth value are in front.",
                0.0f,
                UIPropertyOptions.AffectsRender);

            // Create 3D objects and a progress bar for each object.
            for (int i = 0; i < 10; i++)
            {
                var dynamicObject = new DynamicObject(Services, 1);
                GameObjectService.Objects.Add(dynamicObject);

                var progressBar = new ProgressBar
                {
                    Value   = RandomHelper.Random.NextFloat(0, 100),
                    Maximum = 100,
                    X       = 100,
                    Y       = 100,
                    Width   = 100,
                    Height  = 20,
                    Margin  = new Vector4F(-50, -10, 0, 0), // Use a margin to center the control.
                };
                _uiScreen.Children.Add(progressBar);

                _objects.Add(new Pair <DynamicObject, ProgressBar>(dynamicObject, progressBar));
            }
        }
Beispiel #38
0
        public WaterSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics Simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            // More standard objects.
            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            //GameObjectService.Objects.Add(new StaticSkyObject(Services));
            var dynamicSkyObject = new DynamicSkyObject(Services, true, false, true);

            GameObjectService.Objects.Add(dynamicSkyObject);

            // Add a ground plane with some detail to see the water refractions.
            Simulation.RigidBodies.Add(new RigidBody(new PlaneShape(new Vector3F(0, 1, 0), 0)));
            GameObjectService.Objects.Add(new StaticObject(Services, "Gravel/Gravel", 1, new Pose(new Vector3F(0, 0.001f, 0))));

            GameObjectService.Objects.Add(new DudeObject(Services));
            GameObjectService.Objects.Add(new DynamicObject(Services, 1));
            GameObjectService.Objects.Add(new DynamicObject(Services, 2));
            GameObjectService.Objects.Add(new DynamicObject(Services, 4));
            GameObjectService.Objects.Add(new DynamicObject(Services, 5));
            GameObjectService.Objects.Add(new DynamicObject(Services, 6));
            GameObjectService.Objects.Add(new DynamicObject(Services, 7));
            GameObjectService.Objects.Add(new FogObject(Services, true));

            // The LavaBalls class controls all lava ball instances.
            var lavaBalls = new LavaBallsObject(Services);

            GameObjectService.Objects.Add(lavaBalls);

            // Add a few palm trees.
            var random = new Random(12345);

            for (int i = 0; i < 10; i++)
            {
                Vector3F  position    = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
                Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float     scale       = random.NextFloat(0.5f, 1.2f);
                GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }

            // Add an options window.
            GameObjectService.Objects.Add(new OptionsObject(Services));

            // Define the appearance of the water.
            var water = new Water
            {
                SpecularColor = new Vector3F(10f),

                // Small water ripples/waves are created using scrolling normal maps.
                NormalMap0         = ContentManager.Load <Texture2D>("Water/Wave0"),
                NormalMap1         = ContentManager.Load <Texture2D>("Water/Wave1"),
                NormalMap0Scale    = 1.8f,
                NormalMap1Scale    = 2.2f,
                NormalMap0Velocity = new Vector3F(-0.02f, 0, 0.03f),
                NormalMap1Velocity = new Vector3F(0.02f, 0, -0.03f),
                NormalMap0Strength = 0.5f,
                NormalMap1Strength = 0.5f,

                ReflectionDistortion = 0.2f,
                ReflectionColor      = new Vector3F(0.7f),
                RefractionDistortion = 0.05f,
            };

            // Create a box-shaped body of water.
            // We use a TransformedShape containing a BoxShape because the top of the
            // water body must be at height 0.
            var shape = new TransformedShape(new GeometricObject(
                                                 new BoxShape(10, 1, 20),
                                                 new Pose(new Vector3F(0, -0.5f, 0))));

            _waterNode0 = new WaterNode(water, shape)
            {
                PoseWorld              = new Pose(new Vector3F(-1, 0.5f, 0), Matrix33F.CreateRotationY(0.1f)),
                SkyboxReflection       = _graphicsScreen.Scene.GetDescendants().OfType <SkyboxNode>().First(),
                DepthBufferWriteEnable = true,
            };
            _graphicsScreen.Scene.Children.Add(_waterNode0);

            // Optional: Create a WaterFlow to move the water using a flow texture.
            _waterFlow0 = new WaterFlow
            {
                FlowMapSpeed     = 0.5f,
                FlowMap          = GenerateFlowMap(),
                CycleDuration    = 3f,
                NoiseMapStrength = 0.1f,
                NoiseMapScale    = 0.5f,
            };
            _waterNode0.Flow = _waterFlow0;

            // Optional: Use a planar reflection instead of the skybox reflection.
            // We add a PlanarReflectionNode as a child of the WaterNode.
            var renderToTexture = new RenderToTexture
            {
                Texture = new RenderTarget2D(GraphicsService.GraphicsDevice, 512, 512, false, SurfaceFormat.HdrBlendable, DepthFormat.None),
            };
            var planarReflectionNode = new PlanarReflectionNode(renderToTexture)
            {
                // Same shape as WaterNode.
                Shape = _waterNode0.Shape,

                // Reflection plane is horizontal.
                NormalLocal = new Vector3F(0, 1, 0),
            };

            _waterNode0.PlanarReflection = planarReflectionNode;
            _waterNode0.Children         = new SceneNodeCollection(1)
            {
                planarReflectionNode
            };

            // Create a short river with an inclined water surface.
            // Using a WaterFlow with a SurfaceSlopeSpeed, the water automatically flows
            // down the inclined surface.
            _waterNode1 = new WaterNode(water, GetSpiralShape())
            {
                PoseWorld = new Pose(new Vector3F(10, 1.5f, 0), Matrix33F.CreateRotationY(0.1f)),
                EnableUnderwaterEffect = false,
                SkyboxReflection       = _graphicsScreen.Scene.GetDescendants().OfType <SkyboxNode>().First(),
                Flow = new WaterFlow
                {
                    SurfaceSlopeSpeed = 0.5f,
                    CycleDuration     = 2f,
                    NoiseMapStrength  = 0.1f,
                    NoiseMapScale     = 1,
                }
            };
            _graphicsScreen.Scene.Children.Add(_waterNode1);
        }
Beispiel #39
0
 public static void Create(string font, int consoleWidth, int consoleHeight, Action <Game> ctorCallback = null)
 {
     Instance = new Game(font, consoleWidth, consoleHeight, ctorCallback);
 }
Beispiel #40
0
 public MyUIRenderer(Microsoft.Xna.Framework.Game game, Theme theme)
     : base(game, theme)
 {
     // Add a new render method for the style "TreeViewItem".
     RenderCallbacks.Add("TreeViewItem", RenderTreeViewItem);
 }
        public PathAnimationSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            Rectangle bounds = GraphicsService.GraphicsDevice.Viewport.Bounds;

            // Create a 2D path.
            Path2F path = new Path2F
            {
                // Path is cyclic.
                PreLoop  = CurveLoopType.Cycle,
                PostLoop = CurveLoopType.Cycle,

                //  End of path should smoothly interpolate with start of path.
                SmoothEnds = true,
            };

            // The spline type.
            const SplineInterpolation splineInterpolation = SplineInterpolation.BSpline;

            // Add path keys. The parameter of a path key is the time in seconds.
            path.Add(new PathKey2F
            {
                Parameter     = 0,
                Point         = new Vector2F(bounds.Center.X, bounds.Center.Y),
                Interpolation = splineInterpolation,
            });
            path.Add(new PathKey2F
            {
                Parameter     = 0.5f,
                Point         = new Vector2F(bounds.Center.X / 2.0f, 2.0f * bounds.Center.Y / 3.0f),
                Interpolation = splineInterpolation,
            });
            path.Add(new PathKey2F
            {
                Parameter     = 1.0f,
                Point         = new Vector2F(bounds.Center.X, 1.0f * bounds.Center.Y / 3.0f),
                Interpolation = splineInterpolation,
            });
            path.Add(new PathKey2F
            {
                Parameter     = 1.5f,
                Point         = new Vector2F(3.0f * bounds.Center.X / 2.0f, 2.0f * bounds.Center.Y / 3.0f),
                Interpolation = splineInterpolation,
            });
            path.Add(new PathKey2F
            {
                Parameter     = 2.0f,
                Point         = new Vector2F(bounds.Center.X, bounds.Center.Y),
                Interpolation = splineInterpolation,
            });
            path.Add(new PathKey2F
            {
                Parameter     = 2.5f,
                Point         = new Vector2F(bounds.Center.X / 2.0f, 4.0f * bounds.Center.Y / 3.0f),
                Interpolation = splineInterpolation,
            });

            path.Add(new PathKey2F
            {
                Parameter     = 3.0f,
                Point         = new Vector2F(bounds.Center.X, 5.0f * bounds.Center.Y / 3.0f),
                Interpolation = splineInterpolation,
            });
            path.Add(new PathKey2F
            {
                Parameter     = 3.5f,
                Point         = new Vector2F(3.0f * bounds.Center.X / 2.0f, 4.0f * bounds.Center.Y / 3.0f),
                Interpolation = splineInterpolation,
            });
            path.Add(new PathKey2F
            {
                Parameter     = 4.0f,
                Point         = new Vector2F(bounds.Center.X, bounds.Center.Y),
                Interpolation = splineInterpolation,
            });

            // Create a path animation using the path.
            // (Start at parameter value 0 and loop forever.)
            Path2FAnimation pathAnimation = new Path2FAnimation(path)
            {
                StartParameter = 0,
                EndParameter   = float.PositiveInfinity,
            };

            AnimationService.StartAnimation(pathAnimation, _animatablePosition).UpdateAndApply();
        }
Beispiel #42
0
 public OdeIntegratorSample(Microsoft.Xna.Framework.Game game)
     : base(game)
 {
     GraphicsScreen.ClearBackground = true;
 }
 public static void loadTitleScreenImage(Microsoft.Xna.Framework.Game game)
 {
     titleImage = game.Content.Load <Texture2D>("BlackoutLogo");
 }
        public PickingSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;
            GraphicsScreen.ClearBackground = true;
            GraphicsScreen.BackgroundColor = Color.CornflowerBlue;
            GraphicsScreen.DrawReticle     = true;
            SetCamera(new Vector3F(0, 1, 10), 0, 0);

            // ----- Initialize collision detection system.
            // We use one collision domain that manages all objects.
            _domain = new CollisionDomain
            {
                // Optional: Change the broad phase type. The default type is the SweepAndPruneSpace,
                // which is very fast for physics simulation. The DualPartition is better for ray casts.
                // See also http://digitalrune.github.io/DigitalRune-Documentation/html/e32cab3b-cc7c-42ee-8ec9-23dd4467edd0.htm#WhichPartition
                BroadPhase = new DualPartition <CollisionObject>(),
            };

            // Optional: Set a broad phase filter.
            // Per default, the collision domain computes contacts between all collision objects. If we
            // are only interested in ray vs non-ray-shape contacts, we can set a filter to avoid
            // unnecessary intersection computations and improve performance.
            _domain.BroadPhase.Filter = new DelegatePairFilter <CollisionObject>(
                pair =>
            {
                var firstIsRay  = pair.First.GeometricObject.Shape is RayShape;
                var secondIsRay = pair.Second.GeometricObject.Shape is RayShape;
                return(firstIsRay != secondIsRay);
            });

            // Create a collision object with a box shape at position (0, 0, 0) with a random rotation.
            _box = new CollisionObject(
                new GeometricObject(
                    new BoxShape(1, 2, 3),
                    new Pose(new Vector3F(0, 0, 0), RandomHelper.Random.NextQuaternionF())));

            // Create a collision object with a sphere shape at position (-5, 0, 0).
            _sphere = new CollisionObject(new GeometricObject(new SphereShape(1), new Pose(new Vector3F(-5, 0, 0))));

            // Create a random list of points.
            var points = new List <Vector3F>();

            for (int i = 0; i < 100; i++)
            {
                points.Add(RandomHelper.Random.NextVector3F(-1.5f, 1.5f));
            }

            // Create a triangle mesh of the convex hull.
            // (See also the ConvexHullSample for info on convex hull creation.)
            TriangleMesh triangleMesh = GeometryHelper.CreateConvexHull(points).ToTriangleMesh();

            // We use this random triangle mesh to define a shape.
            TriangleMeshShape meshShape = new TriangleMeshShape(triangleMesh);

            // Optional: We can use a spatial partitioning method, to speed up collision
            // detection for large meshes. AABB trees are good for static triangle meshes.
            // To use spatial partitioning we have to set a valid spatial partition instance
            // in the Partition property.
            // The spatial partition will store indices of the mesh triangles, therefore
            // the generic type argument is "int".
            meshShape.Partition = new AabbTree <int>()
            {
                // Optional: The tree is automatically built using a mixed top-down/bottom-up approach.
                // Bottom-up building is slower but produces better trees. If the tree building takes too
                // long, we can lower the BottomUpBuildThreshold (default is 128).
                BottomUpBuildThreshold = 0,
            };

            // Optional: Build the AABB tree. (This is done automatically when the AABB tree is used for
            // the first time, but Update can also be called explicitly to control when the tree is built.)
            meshShape.Partition.Update(false);


            // Create a collision object with the random triangle mesh shape.
            _mesh = new CollisionObject(new GeometricObject(meshShape, new Pose(new Vector3F(5, 0, 0))));

            // Add collision object to collision domain.
            _domain.CollisionObjects.Add(_box);
            _domain.CollisionObjects.Add(_sphere);
            _domain.CollisionObjects.Add(_mesh);

            // For picking we create a ray.
            // The ray shoot from its local origin in +x direction.
            // (Note: The last parameter is the length of the ray. In theory, rays have
            // an infinite length. However, in the collision detection we use rays with
            // a finite length. This increases the performance and improves the numerical
            // stability of the algorithms.)
            RayShape rayShape = new RayShape(Vector3F.Zero, Vector3F.Forward, 1000);

            _ray = new CollisionObject(new GeometricObject(rayShape, Pose.Identity));

            // The ray is just one additional collision object in our collision domain.
            _domain.CollisionObjects.Add(_ray);

            // The collision domain manages now 4 objects: a box, a sphere, a triangle mesh and a ray.
        }
Beispiel #45
0
    public LdrSkySample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;
      var delegateGraphicsScreen = new DelegateGraphicsScreen(GraphicsService)
      {
        RenderCallback = Render,
      };
      GraphicsService.Screens.Insert(0, delegateGraphicsScreen);

      // Add a custom game object which controls the camera.
      _cameraObject = new CameraObject(Services);
      GameObjectService.Objects.Add(_cameraObject);


      var spriteFont = UIContentManager.Load<SpriteFont>("UI Themes/BlendBlue/Default");
      _debugRenderer = new DebugRenderer(GraphicsService, spriteFont);

      _cieSkyFilter = new CieSkyFilter(GraphicsService);
      _cieSkyFilter.Exposure = 5;
      _cieSkyFilter.Strength = 0.9f;

      _gradientSky = new GradientSkyNode();
      //_gradientSky.GroundColor = new Vector4(0, 0, 1, 1);
      //_gradientSky.ZenithColor = new Vector4(0, 0, 1, 1);
      //_gradientSky.FrontColor = new Vector4(0, 0, 1, 1);
      //_gradientSky.BackColor = new Vector4(0, 0, 1, 1);
      //_gradientSky.FrontZenithShift = 0.3f;
      //_gradientSky.FrontGroundShift = 0.1f;
      //_gradientSky.BackGroundShift = 0.1f;
      _gradientSky.CieSkyStrength = 0;

      _gradientTextureSky = new GradientTextureSkyNode();
      _gradientTextureSky.TimeOfDay = _time.TimeOfDay;
      _gradientTextureSky.Color = new Vector4(1);
      _gradientTextureSky.FrontTexture = ContentManager.Load<Texture2D>("Sky/GradientSkyFront");
      _gradientTextureSky.BackTexture = ContentManager.Load<Texture2D>("Sky/GradientSkyBack");
      _gradientTextureSky.CieSkyStrength = 1;

      _scatteringSky = new ScatteringSkyNode();
      _scatteringSky.SunIntensity *= 2;
      _scatteringSky.BetaMie *= 2;
      _scatteringSky.GMie = 0.75f;
      _scatteringSky.ScaleHeight = _scatteringSky.AtmosphereHeight * 0.25f;

      InitializeStarfield();

      _cloudMapRenderer = new CloudMapRenderer(GraphicsService);
      _skyRenderer = new SkyRenderer(GraphicsService);

      _milkyWay = ContentManager.Load<TextureCube>("Sky/MilkyWay");
      _milkyWaySkybox = new SkyboxNode(_milkyWay) { Color = new Vector3(0.05f) };

      _sun = new SkyObjectNode
      {
        GlowColor0 = new Vector3(1, 1, 1) * 5,
        GlowExponent0 = 4000,

        //GlowColor1 = new Vector3(0.4f) * 0.1f,
        //GlowExponent1 = 100
      };

      _moon = new SkyObjectNode
      {
        Texture = new PackedTexture(ContentManager.Load<Texture2D>("Sky/Moon")),
        SunLight = new Vector3(1, 1, 1) * 1,
        AmbientLight = new Vector3(0.001f) * 1,
        LightWrap = 0.1f,
        LightSmoothness = 1,
        AngularDiameter = new Vector2F(MathHelper.ToRadians(5)),

        GlowColor0 = new Vector3(0.005f * 0),
        GlowCutoffThreshold = 0.001f,
        GlowExponent0 = 100
      };

      var cloudMap = new LayeredCloudMap
      {
        Density = 10,
        Coverage = 0.5f,
        Size = 1024,
      };
      var scale = CreateScale(0.2f);
      cloudMap.Layers[0] = new CloudMapLayer(null, scale * CreateScale(1), -0.5f, 1, 0.011f * 0);
      cloudMap.Layers[1] = new CloudMapLayer(null, scale * CreateScale(1.7f), -0.5f, 1f / 2f, 0.017f * 0);
      cloudMap.Layers[2] = new CloudMapLayer(null, scale * CreateScale(3.97f), -0.5f, 1f / 4f, 0.033f * 0);
      cloudMap.Layers[3] = new CloudMapLayer(null, scale * CreateScale(8.1f), -0.5f, 1f / 8f, 0.043f * 0);
      cloudMap.Layers[4] = new CloudMapLayer(null, scale * CreateScale(16, 17), -0.5f, 1f / 16f, 0.051f * 0);
      cloudMap.Layers[5] = new CloudMapLayer(null, scale * CreateScale(32, 31), -0.5f, 1f / 32f, 0.059f * 0);
      cloudMap.Layers[6] = new CloudMapLayer(null, scale * CreateScale(64, 67), -0.5f, 1f / 64f, 0.067f * 0);
      cloudMap.Layers[7] = new CloudMapLayer(null, scale * CreateScale(128, 127), -0.5f, 1f / 128f, 0.081f * 0);
      _cloudLayerNode = new CloudLayerNode(cloudMap)
      {
        ForwardScatterScale = 2.5f,
        ForwardScatterOffset = 0.3f,
        TextureMatrix = CreateScale(0.5f),
        SkyCurvature = 0.9f,
        NumberOfSamples = 16,
      };

      _ephemeris = new Ephemeris();
      // Approx. location of Ternberg: Latitude = 48, Longitude = 15, Altitude = 300
      _ephemeris.Latitude = 0;
      _ephemeris.Longitude = 15;
      _ephemeris.Altitude = 300;

      //_time = new DateTime(2013, 5, 1, 17, 17, 0, 0);
      _time = DateTime.Now;
#else
      _time = new DateTimeOffset(2013, 5, 1, 12, 0, 0, 0, TimeSpan.Zero);
      //_time = DateTimeOffset.UtcNow;

      UpdateEphemeris();

      _milkyWaySkybox.DrawOrder = 0;
      _starfield.DrawOrder = 1;
      _sun.DrawOrder = 2;
      _moon.DrawOrder = 3;
      _scatteringSky.DrawOrder = 4;
      _gradientSky.DrawOrder = 4;
      _gradientTextureSky.DrawOrder = 4;
      _cloudLayerNode.DrawOrder = 5;

      _skyNodes = new SceneNode[]
      {
        _milkyWaySkybox,
        _starfield, 
        _sun, 
        _moon,
        _scatteringSky,
        //_gradientSky,
        //_gradientTextureSky,
        _cloudLayerNode,
      };

      var graphicsDevice = GraphicsService.GraphicsDevice;
      _skybox = new SkyboxNode(
        new RenderTargetCube(graphicsDevice, 512, false, SurfaceFormat.Color, DepthFormat.None))
      {
        Encoding = ColorEncoding.Rgbm,
      };

      _hdrFilter = new HdrFilter(GraphicsService)
      {
        MinExposure = 0.5f,
        MaxExposure = 2,
        BloomIntensity = 1,
        BloomThreshold = 0.6f,
        AdaptionSpeed = 100,
      };

      _colorEncoder = new ColorEncoder(GraphicsService)
      {
        SourceEncoding = ColorEncoding.Rgb,
        TargetEncoding = _skybox.Encoding,
      };
    }
        public PassiveRagdollSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            GraphicsScreen.DrawReticle = true;

            // Add game objects which allow to shoot balls and grab rigid bodies.
            _ballShooterObject = new BallShooterObject(Services)
            {
                Speed = 10
            };
            GameObjectService.Objects.Add(_ballShooterObject);
            _grabObject = new GrabObject(Services);
            GameObjectService.Objects.Add(_grabObject);

            var modelNode = ContentManager.Load <ModelNode>("Dude/Dude");

            _meshNode           = modelNode.GetSubtree().OfType <MeshNode>().First().Clone();
            _meshNode.PoseLocal = new Pose(new Vector3F(0, 0, 0));
            SampleHelper.EnablePerPixelLighting(_meshNode);
            GraphicsScreen.Scene.Children.Add(_meshNode);

            // Create a ragdoll for the Dude model.
            _ragdoll = new Ragdoll();
            DudeRagdollCreator.Create(_meshNode.SkeletonPose, _ragdoll, Simulation, 0.571f);

            // Set the world space pose of the whole ragdoll. And copy the bone poses of the
            // current skeleton pose.
            _ragdoll.Pose = _meshNode.PoseWorld;
            _ragdoll.UpdateBodiesFromSkeleton(_meshNode.SkeletonPose);

            // Uncomment to disable dynamic movement (for debugging during ragdoll creation):
            //foreach (var body in _ragdoll.Bodies)
            //  if (body != null)
            //    body.MotionType = MotionType.Kinematic;

            // In this sample we use a passive ragdoll where we need joints to hold the
            // limbs together and limits to restrict angular movement.
            _ragdoll.EnableJoints();
            _ragdoll.EnableLimits();

            // Set all motors to constraint motors that only use damping. This adds a damping
            // effect to all ragdoll limbs.
            foreach (RagdollMotor motor in _ragdoll.Motors)
            {
                if (motor != null)
                {
                    motor.Mode = RagdollMotorMode.Constraint;
                    motor.ConstraintDamping = 5;
                    motor.ConstraintSpring  = 0;
                }
            }
            _ragdoll.EnableMotors();

            // Add rigid bodies and the constraints of the ragdoll to the simulation.
            _ragdoll.AddToSimulation(Simulation);

            // Add a rigid body.
            var box = new RigidBody(new BoxShape(0.4f, 0.4f, 0.4f))
            {
                Name = "Box",
                Pose = new Pose(new Vector3F(0, 3, 0)),
            };

            Simulation.RigidBodies.Add(box);
        }
Beispiel #47
0
        public InGameUISample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Create the DeferredGraphicsScreen.
            var graphicsScreen = new DeferredGraphicsScreen(Services);

            graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, graphicsScreen);

            Services.Register(typeof(DebugRenderer), null, graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, graphicsScreen.Scene);

            // some 3D objects
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;
            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new StaticSkyObject(Services));
            GameObjectService.Objects.Add(new GroundObject(Services));
            for (int i = 0; i < 10; i++)
            {
                GameObjectService.Objects.Add(new DynamicObject(Services, 3));
            }

            // Create the UIScreen which is rendered into the back buffer.
            Theme      theme    = ContentManager.Load <Theme>("UI Themes/Aero/Theme");
            UIRenderer renderer = new UIRenderer(Game, theme);

            _normalUIScreen = new NormalUIScreen(renderer);
            UIService.Screens.Add(_normalUIScreen);

            // Handle the InputProcessed event of the Image control.
            _normalUIScreen.Image.InputProcessed += OnGameViewControlInputProcessed;

            // Create the DelegateGraphicsScreen. This graphics screen is on top of the
            // DeferredGraphicsScreen and instructs the graphics service to render the
            // previous screen into an off-screen render target.
            var delegateGraphicsScreen = new DelegateGraphicsScreen(GraphicsService)
            {
                RenderCallback = Render,
                RenderPreviousScreensToTexture = true,
                SourceTextureFormat            = new RenderTargetFormat(
                    (int)_normalUIScreen.Image.Width,
                    (int)_normalUIScreen.Image.Height,
                    false,
                    SurfaceFormat.Color,
                    DepthFormat.Depth24),
            };

            GraphicsService.Screens.Insert(1, delegateGraphicsScreen);

            // Create the UIScreen that is rendered into a render target and mapped onto the 3D game objects.
            _inGameUIScreenRenderTarget = new RenderTarget2D(GraphicsService.GraphicsDevice, 600, 250, false, SurfaceFormat.Color, DepthFormat.None);
            _inGameScreen = new InGameUIScreen(Services, renderer)
            {
                InputEnabled = false,
                Width        = _inGameUIScreenRenderTarget.Width,
                Height       = _inGameUIScreenRenderTarget.Height,
            };
            UIService.Screens.Add(_inGameScreen);

            // We can use the off-screen render target anywhere in the 3D scene. Here, we
            // use it to replace the normal "TestCard" texture of the TV objects and the ProjectorLights.
            foreach (var node in graphicsScreen.Scene.GetDescendants())
            {
                var meshNode = node as MeshNode;
                if (meshNode != null)
                {
                    foreach (var material in meshNode.Mesh.Materials)
                    {
                        if (material.Name == "TestCard")
                        {
                            material["Material"].Set("EmissiveTexture", (Texture)_inGameUIScreenRenderTarget);
                            material["Material"].Set("Exposure", 0.1f);
                        }
                    }
                    continue;
                }

                var lightNode = node as LightNode;
                if (lightNode != null && lightNode.Light is ProjectorLight)
                {
                    ((ProjectorLight)lightNode.Light).Texture = _inGameUIScreenRenderTarget;
                }
            }
        }
Beispiel #48
0
        public MeshNodeSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            _delegateGraphicsScreen = new DelegateGraphicsScreen(GraphicsService)
            {
                RenderCallback = Render,
            };
            GraphicsService.Screens.Insert(0, _delegateGraphicsScreen);

            // Add a custom game object which controls the camera.
            _cameraObject = new CameraObject(Services);
            GameObjectService.Objects.Add(_cameraObject);

            // For advanced users: Set this flag if you want to analyze the imported opaque data of
            // effect bindings.
            //EffectBinding.KeepOpaqueData = true;

            // Load a model. The model is processed using the DigitalRune Model Processor - not
            // the default XNA model processor!
            // In the folder that contains tank.fbx, there is an XML file tank.drmdl which defines
            // properties of the model. These XML files are automatically processed by the
            // DigitalRune Model Processor.
            // Each model itself is a tree of scene nodes. The grid model contains one mesh
            // node. The tank model contains several mesh nodes (turret, cannon, hatch,
            // wheels, ...).
            _model = ContentManager.Load <ModelNode>("Tank/tank");

            // The XNA ContentManager manages a single instance of each model. We clone
            // the model, to get a copy that we can modify without changing the original
            // instance. Cloning is fast because it only duplicates the scene nodes - but
            // not the mesh and material information.
            _model = _model.Clone();

            // _model is the root of a tree of scene nodes. The mesh nodes are the child
            // nodes. When we scale or move the _model, we automatically scale and move
            // all child nodes.
            _model.ScaleLocal = new Vector3F(0.8f);
            _model.PoseWorld  = new Pose(new Vector3F(0, 0, -2), Matrix33F.CreateRotationY(-0.3f));

            // Let's loop through the mesh nodes of the model:
            foreach (var meshNode in _model.GetSubtree().OfType <MeshNode>())
            {
                // Each MeshNode references a Mesh.
                Mesh mesh = meshNode.Mesh;

                // The mesh consists of several submeshes and several materials - usually
                // one material per submesh, but several submeshes could reference the same
                // materials.

                // Let's loop through the materials of this mesh.
                foreach (var material in mesh.Materials)
                {
                    // A material is a collection of EffectBindings - one EffectBinding for each
                    // render pass. For example, a complex game uses several render passes, like
                    // a pre-Z pass, a G-buffer pass, a shadow map pass, a deferred material pass,
                    // etc.In simple games there is only one pass which is called "Default".
                    var effectBinding = material["Default"];

                    // An EffectBinding references an Effect (the XNA Effect class) and it has
                    // "parameter bindings" and "technique bindings". These bindings select the
                    // values for the shader parameters when the mesh node is rendered.

                    // Let's change the binding for the DiffuseColor of the shader to give tank
                    // a red color.
                    effectBinding.Set("DiffuseColor", new Vector4(1, 0.7f, 0.7f, 1));

                    // The tank uses the default effect binding which is a BasicEffectBinding - this
                    // effect binding uses the XNA BasicEffect.
                    // In this sample we do not define any lights, therefore we disable the lighting
                    // in the shader.
                    ((BasicEffectBinding)effectBinding).LightingEnabled = false;
                }
            }

            _meshRenderer = new MeshRenderer();

            var spriteFont = UIContentManager.Load <SpriteFont>("Default");

            _debugRenderer = new DebugRenderer(GraphicsService, spriteFont);
        }
        public DistortionSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;
            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new StaticSkyObject(Services)); // Skybox + some lights.

            //GameObjectService.Objects.Add(new GroundObject(Services));
            // Add a ground plane with some detail to see the water refractions.
            Simulation.RigidBodies.Add(new RigidBody(new PlaneShape(new Vector3(0, 1, 0), 0)));
            GameObjectService.Objects.Add(new StaticObject(Services, "Gravel/Gravel", 1, new Pose(new Vector3(0, 0.001f, 0))));

            GameObjectService.Objects.Add(new DudeObject(Services));
            GameObjectService.Objects.Add(new DynamicObject(Services, 1));
            GameObjectService.Objects.Add(new DynamicObject(Services, 2));
            GameObjectService.Objects.Add(new DynamicObject(Services, 3));
            GameObjectService.Objects.Add(new DynamicObject(Services, 5));
            GameObjectService.Objects.Add(new DynamicObject(Services, 6));
            GameObjectService.Objects.Add(new DynamicObject(Services, 7));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new FogObject(Services));
            GameObjectService.Objects.Add(new CampfireObject(Services));
            GameObjectService.Objects.Add(new LavaBallsObject(Services));

            // Add a few palm trees.
            Random random = new Random(12345);

            for (int i = 0; i < 10; i++)
            {
                Vector3 position    = new Vector3(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
                Matrix  orientation = Matrix.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float   scale       = random.NextFloat(0.5f, 1.2f);
                GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }

            // Add DistortionFilter to post-processors.
            _distortionFilter = new DistortionFilter(GraphicsService, ContentManager);
            _graphicsScreen.PostProcessors.Add(_distortionFilter);

            // Add 3 particle systems.
            // The ParticleSystems are added to the IParticleSystemService.
            // The ParticleSystemNodes are added to the Scene of the DistortionFilter - not the usual Scene!
            _fireDistortionParticleSystemNode = new ParticleSystemNode(CreateFireDistortionParticleSystem())
            {
                PoseLocal = new Pose(new Vector3(0, 0f, -1), Matrix.CreateRotationX(ConstantsF.PiOver2)),
            };
            ParticleSystemService.ParticleSystems.Add(_fireDistortionParticleSystemNode.ParticleSystem);
            _distortionFilter.Scene.Children.Add(_fireDistortionParticleSystemNode);

            _explosionDistortionParticleSystemNode = new ParticleSystemNode(CreateExplosionDistortionParticleSystem())
            {
                PoseLocal = new Pose(new Vector3(0, 0, -1)),
            };
            ParticleSystemService.ParticleSystems.Add(_explosionDistortionParticleSystemNode.ParticleSystem);
            _distortionFilter.Scene.Children.Add(_explosionDistortionParticleSystemNode);

            _novaDistortionParticleSystemNode = new ParticleSystemNode(CreateNovaDistortionParticleSystem())
            {
                PoseLocal = new Pose(new Vector3(0, 0.5f, -1), Matrix.CreateRotationX(ConstantsF.PiOver2)),
            };
            ParticleSystemService.ParticleSystems.Add(_novaDistortionParticleSystemNode.ParticleSystem);
            _distortionFilter.Scene.Children.Add(_novaDistortionParticleSystemNode);
        }
Beispiel #50
0
 public TitleScreen(Microsoft.Xna.Framework.Game game)
     : base(game)
 {
     // TODO: Construct any child components here
 }
Beispiel #51
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Entity"/> class.
 /// </summary>
 internal Entity(IInput input, IGraphic graphics, Microsoft.Xna.Framework.Game game) : base(input, graphics, game)
 {
     Position = new Vector2(0, 0);
 }
Beispiel #52
0
 public ColorBox(Microsoft.Xna.Framework.Game game)
     : base(game)
 {
     renderer = new ColorRenderer(game, this);
     Brush    = new Brush(Color.Red, Color.Red, Color.White);
 }
Beispiel #53
0
 public Combatant(Game game) : base(game)
 {
 }
Beispiel #54
0
        public ShadowSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;
            _graphicsScreen = new DeferredGraphicsScreen(Services)
            {
                // For debugging: Disable materials and only show light buffer.
                DebugMode = DeferredGraphicsDebugMode.VisualizeDiffuseLightBuffer
            };
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);

            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));

            CreateScene(Services, ContentManager, _graphicsScreen);

            // Disable existing lights.
            foreach (var lightNode in _graphicsScreen.Scene.GetDescendants().OfType <LightNode>())
            {
                lightNode.IsEnabled = false;
            }

            // Add a dim ambient light.
            _graphicsScreen.Scene.Children.Add(
                new LightNode(
                    new AmbientLight
            {
                HemisphericAttenuation = 1,
                Intensity = 0.001f,
            }));

            // Add some test lights with shadows.
            _spotlight = new Spotlight {
                Range = 10, FalloffAngle = 0.8f, CutoffAngle = 1f
            };
            _standardShadow = new StandardShadow();
            _spotlightNode  = new LightNode(_spotlight)
            {
                PoseWorld = new Pose(new Vector3F(0, 1f, -2)),
                Shadow    = _standardShadow,
                IsEnabled = true,
            };
            _graphicsScreen.Scene.Children.Add(_spotlightNode);

            _cubeMapShadow = new CubeMapShadow();
            _pointLight    = new PointLight {
                Range = 10,
            };
            _pointLightNode = new LightNode(_pointLight)
            {
                PoseWorld = new Pose(new Vector3F(0, 1f, -2)),
                Shadow    = _cubeMapShadow,
                IsEnabled = false,
            };
            _graphicsScreen.Scene.Children.Add(_pointLightNode);

            CreateGuiControls();
        }
Beispiel #55
0
 public AbstractStage(Microsoft.Xna.Framework.Game g, GraphicsDeviceManager gdm)
     : base(g, gdm)
 {
 }
        public EnvironmentLightSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics Simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new GroundObject(Services));
            GameObjectService.Objects.Add(new DudeObject(Services));
            var lavaBallsObject = new LavaBallsObject(Services);

            GameObjectService.Objects.Add(lavaBallsObject);
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new FogObject(Services));
            GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Barrier", 0.9f, new Pose(new Vector3F(0, 0, -2))));
            GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Cylinder", 0.9f, new Pose(new Vector3F(3, 0, 0), QuaternionF.CreateRotationY(MathHelper.ToRadians(-20)))));
            GameObjectService.Objects.Add(new StaticSkyObject(Services));

            // Add a few palm trees.
            Random random = new Random(12345);

            for (int i = 0; i < 10; i++)
            {
                Vector3F  position    = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
                Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float     scale       = random.NextFloat(0.5f, 1.2f);
                GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }

            // Add some more dynamic objects.
            for (int i = 0; i < 5; i++)
            {
                lavaBallsObject.Spawn();
                GameObjectService.Objects.Add(new ProceduralObject(Services));
                GameObjectService.Objects.Add(new DynamicObject(Services, 7));
            }

            // To show the effect of the EnvironmentLight in isolation, disable all other light sources.
            //foreach (var light in _graphicsScreen.Scene.GetDescendants().OfType<LightNode>())
            //  light.IsEnabled = false;

            // Add the environment light.
            var environmentLight = new EnvironmentLight
            {
                Color             = new Vector3F(0.1f),
                DiffuseIntensity  = 0,
                SpecularIntensity = 1,
                EnvironmentMap    = ContentManager.Load <TextureCube>("Sky2"),
            };
            var environmentLightNode = new LightNode(environmentLight)
            {
                Name = "Environment",
            };

            _graphicsScreen.Scene.Children.Add(environmentLightNode);

            // The EnvironmentLight is a new light type. We have to register a light renderer
            // for this light in the LightRenderer of the DeferredGraphicsScreen.
            _graphicsScreen.LightBufferRenderer.LightRenderer.Renderers.Add(new EnvironmentLightRenderer(GraphicsService));

            // EnvironmentLight.fx uses the specular power of the materials to determine
            // which mip map level of the cube is reflected.
            // In reality, a high specular power is necessary to reflect the cube map
            // with all its detail. To reflect a cube map level with 512 texels size, we
            // need a specular power of ~200000.
            // To make the reflection effects more obvious, let's change some material properties
            // and make the more reflective.

            // ProceduralObject:
            var proceduralObjects = _graphicsScreen.Scene
                                    .GetDescendants()
                                    .OfType <MeshNode>()
                                    .Where(mn => mn.Mesh.Name == "ProceduralObject")
                                    .Select(mn => mn.Mesh);

            foreach (var mesh in proceduralObjects)
            {
                foreach (var material in mesh.Materials)
                {
                    material["GBuffer"].Set("SpecularPower", 10000f);
                    material["Material"].Set("DiffuseColor", new Vector3(0.01f));
                    material["Material"].Set("SpecularColor", new Vector3(1));
                }
            }

            // Frame of GlassBox:
            var glassBoxes = _graphicsScreen.Scene
                             .GetDescendants()
                             .OfType <ModelNode>()
                             .Where(mn => mn.Name == "GlassBox")
                             .Select(mn => ((MeshNode)mn.Children[0]).Mesh);

            foreach (var mesh in glassBoxes)
            {
                foreach (var material in mesh.Materials.Where(m => m.Contains("GBuffer")))
                {
                    material["GBuffer"].Set("SpecularPower", 100000f);
                    material["Material"].Set("DiffuseColor", new Vector3(0.0f));
                    material["Material"].Set("SpecularColor", new Vector3(1));
                }
            }

            // LavaBall:
            var lavaBalls = _graphicsScreen.Scene
                            .GetDescendants()
                            .OfType <ModelNode>()
                            .Where(mn => mn.Name == "LavaBall")
                            .Select(mn => ((MeshNode)mn.Children[0]).Mesh);

            foreach (var mesh in lavaBalls)
            {
                foreach (var material in mesh.Materials.Where(m => m.Contains("GBuffer")))
                {
                    material["GBuffer"].Set("SpecularPower", 10000f);
                    material["Material"].Set("DiffuseColor", new Vector3(0.0f));
                    material["Material"].Set("SpecularColor", new Vector3(10));
                    material["Material"].Set("EmissiveColor", new Vector3(0.0f));
                }
            }

            // Ground plane:
            var groundPlanes = _graphicsScreen.Scene
                               .GetDescendants()
                               .OfType <ModelNode>()
                               .Where(mn => mn.Name == "Ground")
                               .Select(mn => ((MeshNode)mn.Children[0]).Mesh);

            foreach (var mesh in groundPlanes)
            {
                foreach (var material in mesh.Materials.Where(m => m.Contains("GBuffer")))
                {
                    material["GBuffer"].Set("SpecularPower", 200000.0f);
                    material["Material"].Set("DiffuseColor", new Vector3(0.5f));
                    material["Material"].Set("SpecularColor", new Vector3(0.4f));
                }
            }

            // Please note, XNA does not filter cube maps over cube map borders. Therefore, reflections
            // of low resolution mip map levels might show obvious borders between the cube map
            // sides. In this case you can change the EnvironmentLight.fx effect to always reflect
            // the mip map level 0.
            // This is not a problem with MonoGame because DirectX automatically filters cube map borders.
        }
        public IKPhysicsSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            GraphicsScreen.DrawReticle = true;

            // Add game objects which allows to grab rigid bodies.
            _grabObject = new GrabObject(Services);
            GameObjectService.Objects.Add(_grabObject);

            // Add Dude model.
            var modelNode = ContentManager.Load <ModelNode>("Dude/Dude");

            _meshNode           = modelNode.GetSubtree().OfType <MeshNode>().First().Clone();
            _meshNode.PoseLocal = new Pose(new Vector3F(0, 0, 0));
            SampleHelper.EnablePerPixelLighting(_meshNode);
            GraphicsScreen.Scene.Children.Add(_meshNode);

            // Create a ragdoll for the Dude model.
            _ragdoll = new Ragdoll();
            DudeRagdollCreator.Create(_meshNode.SkeletonPose, _ragdoll, Simulation, 0.571f);

            // Set the initial world space pose of the whole ragdoll. And copy the bone poses of the
            // current skeleton pose.
            _ragdoll.Pose = _meshNode.PoseWorld;
            _ragdoll.UpdateBodiesFromSkeleton(_meshNode.SkeletonPose);

            // Enable constraints (joints and limits, no motors)
            _ragdoll.EnableJoints();
            _ragdoll.EnableLimits();
            _ragdoll.DisableMotors();

            foreach (var body in _ragdoll.Bodies)
            {
                if (body != null)
                {
                    // Disable rigid body sleeping. (If we leave it enabled, the simulation might
                    // disable slow bodies before they reach their IK goal.)
                    body.CanSleep = false;

                    // Disable collisions response.
                    body.CollisionResponseEnabled = false;
                }
            }

            // Add rigid bodies and the constraints of the ragdoll to the simulation.
            _ragdoll.AddToSimulation(Simulation);

            // Disable all force effects (default gravity and damping).
            Simulation.ForceEffects.Clear();

            // Create constraints which hold selected bodies at their current position
            // relative to the world.
            // To constrain the position + orientation, we use a FixedJoint.
            foreach (var boneName in new[] { "Pelvis" })
            {
                var ragdollBody = _ragdoll.Bodies[_meshNode.SkeletonPose.Skeleton.GetIndex(boneName)];
                var ikJoint     = new FixedJoint
                {
                    AnchorPoseALocal = ragdollBody.Pose,
                    BodyA            = Simulation.World,
                    AnchorPoseBLocal = Pose.Identity,
                    BodyB            = ragdollBody,
                    CollisionEnabled = false,
                    MaxForce         = 1000,
                };
                _ikJoints.Add(ikJoint);
                Simulation.Constraints.Add(ikJoint);
            }
            // To constrain only the position, we use a BallJoint.
            foreach (var boneName in new[] { "L_Hand", "R_Hand", "L_Ankle1", "R_Ankle" })
            {
                var ragdollBody = _ragdoll.Bodies[_meshNode.SkeletonPose.Skeleton.GetIndex(boneName)];
                var ikJoint     = new BallJoint
                {
                    AnchorPositionALocal = ragdollBody.Pose.Position,
                    BodyA = Simulation.World,
                    AnchorPositionBLocal = Vector3F.Zero,
                    BodyB            = ragdollBody,
                    CollisionEnabled = false,
                    MaxForce         = 1000,
                };
                _ikJoints.Add(ikJoint);
                Simulation.Constraints.Add(ikJoint);
            }
        }
Beispiel #58
0
        public KinematicRagdollSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            GraphicsScreen.DrawReticle = true;

            // Add game objects which allow to shoot balls and grab rigid bodies.
            _ballShooterObject = new BallShooterObject(Services)
            {
                Speed = 10
            };
            GameObjectService.Objects.Add(_ballShooterObject);
            _grabObject = new GrabObject(Services);
            GameObjectService.Objects.Add(_grabObject);

            var modelNode = ContentManager.Load <ModelNode>("Dude/Dude");

            _meshNode           = modelNode.GetSubtree().OfType <MeshNode>().First().Clone();
            _meshNode.PoseLocal = new Pose(new Vector3F(0, 0, 0), Matrix33F.CreateRotationY(ConstantsF.Pi));
            SampleHelper.EnablePerPixelLighting(_meshNode);
            GraphicsScreen.Scene.Children.Add(_meshNode);

            var animations       = _meshNode.Mesh.Animations;
            var loopingAnimation = new AnimationClip <SkeletonPose>(animations.Values.First())
            {
                LoopBehavior = LoopBehavior.Cycle,
                Duration     = TimeSpan.MaxValue,
            };
            var animationController = AnimationService.StartAnimation(loopingAnimation, (IAnimatableProperty)_meshNode.SkeletonPose);

            animationController.UpdateAndApply();

            // Create a ragdoll for the Dude model.
            _ragdoll = new Ragdoll();
            DudeRagdollCreator.Create(_meshNode.SkeletonPose, _ragdoll, Simulation, 0.571f);

            // Set the world space pose of the whole ragdoll. And copy the bone poses of the
            // current skeleton pose.
            _ragdoll.Pose = _meshNode.PoseWorld;
            _ragdoll.UpdateBodiesFromSkeleton(_meshNode.SkeletonPose);

            // Set all bodies to kinematic -  they should not be affected by forces.
            foreach (var body in _ragdoll.Bodies)
            {
                if (body != null)
                {
                    body.MotionType = MotionType.Kinematic;
                }
            }

            // Set all motors to velocity motors. Velocity motors change RigidBody.LinearVelocity
            // RigidBody.AngularVelocity to move the rigid bodies.
            foreach (RagdollMotor motor in _ragdoll.Motors)
            {
                if (motor != null)
                {
                    motor.Mode = RagdollMotorMode.Velocity;
                }
            }
            _ragdoll.EnableMotors();

            // In this sample, we do not need joints or limits.
            _ragdoll.DisableJoints();
            _ragdoll.DisableLimits();

            // Add ragdoll rigid bodies to the simulation.
            _ragdoll.AddToSimulation(Simulation);

            // Add a rigid body.
            var box = new RigidBody(new BoxShape(0.4f, 0.4f, 0.4f))
            {
                Name = "Box",
                Pose = new Pose(new Vector3F(0, 3, 0)),
            };

            Simulation.RigidBodies.Add(box);
        }
Beispiel #59
0
        public PerformanceSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            // ----- Multithreading
            // If the scene contains many active (= moving objects), using multithreading is
            // recommended. Multithreading does not improve very static scenes where most bodies
            // are not moving or scenes with very little bodies.
            // If multithreading is enabled in the collision domain, the narrow phase algorithms
            // (which determines contacts) are executed in parallel.
            Simulation.CollisionDomain.EnableMultithreading = true;
            // If multithreading is enabled in the simulation, the simulation islands are solved
            // in parallel and a few other things run in parallel.
            Simulation.Settings.EnableMultithreading = true;

            // The processor affinity and the number of threads can be controlled with these properties:
            //Parallel.ProcessorAffinity = new[] { 4, 3, 5 };    // Threads use the cores 3, 4, 5.
            //Parallel.Scheduler = new WorkStealingScheduler(3); // Use 3 worker threads.
            // The default settings should be ok for most scenarios.

            // ----- Collision Detection Settings
            // We disable the flag FullContactSetPerFrame. If the flag is disabled, the collision
            // detection is faster because in the narrow phase some algorithms will compute only
            // one new contact between two touching bodies.
            // If the flag is enabled, the simulation is more stable because the narrow phase computes
            // more contacts per pair of touching bodies.
            Simulation.CollisionDomain.CollisionDetection.FullContactSetPerFrame = false;

            // ----- Physics Settings
            // If SynchronizeCollisionDomain is false, the collision detection is run only at the
            // beginning of Simulation.Update(). If SynchronizeCollisionDomain is set, the collision
            // detection is also performed at the end. This is necessary in case you need to make manual
            // collision detection queries and need up-to-date collision detection info.
            // Disable this flag if you do not need it.
            Simulation.Settings.SynchronizeCollisionDomain = false;
            // The MinConstraintImpulse defines when the constraint solver will stop its iterative
            // process. A higher limit will make the solver stop earlier (=> faster, but less stable).
            Simulation.Settings.Constraints.MinConstraintImpulse = 0.0001f;
            // NumberOfConstraintIterations defines how many iterations the solver performs at max.
            // Values from 4 to 20 are normal. Use higher values if stable stacking is required.
            Simulation.Settings.Constraints.NumberOfConstraintIterations = 4;
            // Randomization of constraints takes a tiny bit of time and helps to make stacks and
            // complex scenes more stable. For simple scenes we can disable it.
            Simulation.Settings.Constraints.RandomizeConstraints = false;
            // Continuous collision detection cost a bit performance. We are faster if we disable it
            // but with disabled CCD balls (right mouse button) will fly through objects because of
            // their high speed.
            Simulation.Settings.Motion.CcdEnabled = false;
            // If RemoveBodiesOutsideWorld is set, the simulation automatically removes bodies that
            // leave the simulation (defined with Simulation.World). Disable it if not needed.
            Simulation.Settings.Motion.RemoveBodiesOutsideWorld = false;
            // TimeThreshold defines how fast bodies are deactivated. Normal values are 1 or 2 seconds.
            // We can set it to a low value, e.g. 0.5 s, for a very aggressive sleeping. The negative
            // effects of this are that bodies that are slowly falling over, can freeze in a tilted
            // position.
            // You can also try to disable sleeping by setting TimeThreshold to float.MaxValue. But the
            // simulation will run significantly slower. You can run the PhysicsSample and compare the
            // simulation times with enabled and disabled sleeping.
            Simulation.Settings.Sleeping.TimeThreshold = 0.5f;
            // FixedTimeStep defines the size of a single simulation step. Per default, the smallest
            // step is 1 / 60 s (60 fps). In some cases it is ok to use an even larger time step
            // like 1 / 30. But with large time steps stacks and walls will not be stable.
            Simulation.Settings.Timing.FixedTimeStep = 1.0f / 60.0f;
            // If the simulation gets complex the game will need more time to compute each frame.
            // If the game becomes very slow, Simulation.Update(elapsedTime) will be called with
            // a large elapsedTime. If our frame rate drops to 30 fps, Simulation.Update(1/30) will
            // internally make 2 sub-time steps (if FixedTimeStep = 1/60). This could make the problem
            // worse and if we expect such a situation we should limit the number of sub steps to 1.
            // Then, if the game is running slowly, the physics simulation will run in slow motion -
            // but at least it will not freeze the game.
            Simulation.Settings.Timing.MaxNumberOfSteps = 1;

            // ----- Force Effects.
            // Using a low gravity is common trick to make the simulation more stable:
            Simulation.ForceEffects.Add(new Gravity {
                Acceleration = new Vector3F(0, -5, 0)
            });
            // Using high damping coefficients helps to make your simulation faster and more stable
            // because objects will come the rest much quicker. - But too high values can create a
            // very unrealistic damped body movement.
            Simulation.ForceEffects.Add(new Damping {
                LinearDamping = 0.3f, AngularDamping = 0.3f
            });

            // ----- Rigid Body Prototypes
            // Here we create 3 rigid bodies that will serve as templates for the new random bodies
            // that are created in Update().
            // We use the same material instance for all rigid bodies to avoid the creation of several
            // material instances.
            var material = new UniformMaterial();

            _prototypes    = new RigidBody[3];
            _prototypes[0] = new RigidBody(new SphereShape(0.5f), null, material);
            _prototypes[1] = new RigidBody(new CylinderShape(0.4f, 0.9f), null, material);
            _prototypes[2] = new RigidBody(new BoxShape(0.9f, 0.9f, 0.9f), null, material);

            // ----- Height Field
            // Create a height field.
            var numberOfSamplesX = 30;
            var numberOfSamplesZ = 30;
            var samples          = new float[numberOfSamplesX * numberOfSamplesZ];

            for (int z = 0; z < numberOfSamplesZ; z++)
            {
                for (int x = 0; x < numberOfSamplesX; x++)
                {
                    samples[z * numberOfSamplesX + x] = (float)(Math.Cos(z / 2f) * Math.Sin(x / 2f) * 3f + 5f);
                }
            }
            var heightField = new HeightField(0, 0, 100, 100, samples, numberOfSamplesX, numberOfSamplesZ);

            // We can set following flag to get a significant performance gain - but the collision
            // detection will be less accurate. For smooth height fields this flag can be set.
            heightField.UseFastCollisionApproximation = true;

            // Create a static rigid body using the height field and add it to the simulation.
            // The mass of static rigid bodies is not relevant, therefore we use a default
            // mass frame instance as the second constructor parameter. If we do not specify
            // the mass frame, the physics library will try to compute a suitable mass frame
            // which can take some time for large meshes.
            RigidBody landscape = new RigidBody(heightField, new MassFrame(), material)
            {
                Pose       = new Pose(new Vector3F(-50, 0, -50f)),
                MotionType = MotionType.Static,
            };

            Simulation.RigidBodies.Add(landscape);
        }
Beispiel #60
0
        public PlanarReflectionSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            // Create a graphics screen. This screen has to call the PlanarReflectionRenderer
            // to handle the PlanarReflectionNodes!
            _graphicsScreen = new DeferredGraphicsScreen(Services)
            {
                DrawReticle = true
            };
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics Simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            // More standard objects.
            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new StaticSkyObject(Services));
            GameObjectService.Objects.Add(new GroundObject(Services));
            GameObjectService.Objects.Add(new DudeObject(Services));
            GameObjectService.Objects.Add(new DynamicObject(Services, 1));
            GameObjectService.Objects.Add(new DynamicObject(Services, 2));
            GameObjectService.Objects.Add(new DynamicObject(Services, 5));
            GameObjectService.Objects.Add(new DynamicObject(Services, 6));
            GameObjectService.Objects.Add(new DynamicObject(Services, 7));
            GameObjectService.Objects.Add(new FogObject(Services));
            GameObjectService.Objects.Add(new LavaBallsObject(Services));

            // Add a few palm trees.
            Random random = new Random(12345);

            for (int i = 0; i < 10; i++)
            {
                Vector3F  position    = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
                Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float     scale       = random.NextFloat(0.5f, 1.2f);
                GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }

#if MONOGAME
            // ----- Workaround for missing effect parameter semantics in MonoGame.
            // The effect used by the reflecting ground object defines some new effect
            // parameters and sets the EffectParameterHint to "PerInstance", e.g.:
            //   texture ReflectionTexture < string Hint = "PerInstance"; >;
            // "PerInstance" means that each mesh instance which uses the effect can
            // have an individual parameter value, i.e. if there are two instances
            // each instance needs a different ReflectionTexture.
            // MonoGame does not yet support effect parameter annotations in shader
            // code. But we can add the necessary effect parameter descriptions here:
            var effectInterpreter = GraphicsService.EffectInterpreters.OfType <DefaultEffectInterpreter>().First();
            if (!effectInterpreter.ParameterDescriptions.ContainsKey("ReflectionTexture"))
            {
                effectInterpreter.ParameterDescriptions.Add("ReflectionTexture", (parameter, index) => new EffectParameterDescription(parameter, "ReflectionTexture", index, EffectParameterHint.PerInstance));
                effectInterpreter.ParameterDescriptions.Add("ReflectionTextureSize", (parameter, index) => new EffectParameterDescription(parameter, "ReflectionTextureSize", index, EffectParameterHint.PerInstance));
                effectInterpreter.ParameterDescriptions.Add("ReflectionMatrix", (parameter, index) => new EffectParameterDescription(parameter, "ReflectionMatrix", index, EffectParameterHint.PerInstance));
                effectInterpreter.ParameterDescriptions.Add("ReflectionNormal", (parameter, index) => new EffectParameterDescription(parameter, "ReflectionNormal", index, EffectParameterHint.PerInstance));
            }
#endif

            // Get a ground model which can render a planar reflection. See
            // GroundReflective/MaterialReflective.fx.
            var groundModel = ContentManager.Load <ModelNode>("GroundReflective/Ground");

            // Use the reflective mesh as the ground.
            var groundMesh = groundModel.GetSubtree().OfType <MeshNode>().First().Clone();
            groundMesh.PoseWorld = new Pose(new Vector3F(0, 0.01f, 0)); // Small y offset to draw above the default ground model from GroundObject.
            _graphicsScreen.Scene.Children.Add(groundMesh);

            // Use another instance of the mesh as a wall.
            var wallMesh = groundMesh.Clone();
            wallMesh.ScaleLocal = new Vector3F(0.2f, 1, 0.1f);
            wallMesh.PoseWorld  = new Pose(new Vector3F(5, 2, -5), Matrix33F.CreateRotationY(-0.7f) * Matrix33F.CreateRotationX(ConstantsF.PiOver2));
            _graphicsScreen.Scene.Children.Add(wallMesh);

            // Create a PlanarReflectionNode and add it to the children of the first ground mesh.
            // The RenderToTexture class defines the render target for the reflection.
            var renderToTexture0 = new RenderToTexture
            {
                Texture = new RenderTarget2D(
                    GraphicsService.GraphicsDevice,
                    1024, 1024,
                    false, // No mipmaps. Mipmaps can reduce reflection quality.
                    SurfaceFormat.HdrBlendable, DepthFormat.Depth24Stencil8),
            };
            _planarReflectionNode0 = new PlanarReflectionNode(renderToTexture0)
            {
                // The reflection is limited to the bounding shape of the ground mesh.
                Shape = groundMesh.Shape,

                // The normal of the reflection plane.
                NormalLocal = new Vector3F(0, 1, 0),
            };
            groundMesh.Children = new SceneNodeCollection(1)
            {
                _planarReflectionNode0
            };

            // Add another PlanarReflectionNode to the wall.
            var renderToTexture1 = new RenderToTexture
            {
                Texture = new RenderTarget2D(
                    GraphicsService.GraphicsDevice,
                    1024, 1024, false,
                    SurfaceFormat.HdrBlendable, DepthFormat.Depth24Stencil8),
            };
            _planarReflectionNode1 = new PlanarReflectionNode(renderToTexture1)
            {
                Shape       = groundMesh.Shape,
                NormalLocal = new Vector3F(0, 1, 0),
            };
            wallMesh.Children = new SceneNodeCollection(1)
            {
                _planarReflectionNode1
            };

            // Now we have to use the texture that contains the reflection.
            // We use effect parameter bindings to use the reflection texture in the shader of the meshes.
            SetReflectionEffectParameters(groundMesh, _planarReflectionNode0);
            SetReflectionEffectParameters(wallMesh, _planarReflectionNode1);
        }