public RenderTargetBinding(RenderTargetCube renderTarget, CubeMapFace cubeMapFace) { if (renderTarget == null) throw new ArgumentNullException("renderTarget"); if (cubeMapFace < CubeMapFace.PositiveX || cubeMapFace > CubeMapFace.NegativeZ) throw new ArgumentOutOfRangeException("cubeMapFace"); this._renderTarget = (Texture) renderTarget; this._cubeMapFace = cubeMapFace; }
public RenderTargetBinding(RenderTargetCube renderTarget, CubeMapFace cubeMapFace) { if (renderTarget == null) throw new ArgumentNullException("renderTarget"); if (cubeMapFace < CubeMapFace.PositiveX || cubeMapFace > CubeMapFace.NegativeZ) throw new ArgumentOutOfRangeException("cubeMapFace"); _renderTarget = renderTarget; _arraySlice = (int)cubeMapFace; }
public PointLight(GraphicsDevice GraphicsDevice, Vector3 position, float radius, Vector4 color, float intensity, bool isWithShadows, int shadowMapResolution) { Position = position; Radius = radius; Color = color; Intensity = intensity; IsWithShadows = isWithShadows; this.shadowMapResolution = shadowMapResolution; shadowMap = new RenderTargetCube(GraphicsDevice, shadowMapResolution, false, SurfaceFormat.Single, DepthFormat.Depth24Stencil8); }
public void SetRenderTarget(RenderTargetCube renderTarget, CubeMapFace cubeMapFace) { if (renderTarget == null) { SetRenderTargets(null); } else { SetRenderTargets(new RenderTargetBinding(renderTarget, cubeMapFace)); } }
public void SetRenderTarget(RenderTargetCube renderTarget, CubeMapFace cubeMapFace) { if (renderTarget == null) { SetRenderTargets(null); } else { singleTargetCache[0] = new RenderTargetBinding(renderTarget, cubeMapFace); SetRenderTargets(singleTargetCache); } }
public void SetRenderTarget(RenderTargetCube renderTarget, CubeMapFace cubeMapFace) { if (renderTarget == null) { SetRenderTargets(null); } else { _tempRenderTargetBinding[0] = new RenderTargetBinding(renderTarget, cubeMapFace); SetRenderTargets(_tempRenderTargetBinding); } }
public PointLight(Vector3 position, Color color, float lightRadius, float intensity, bool withShadows, int shadowMapResolution) { this.position = position; this.color = color; this.radius = lightRadius; this.intensity = intensity; this.withShadows = withShadows; this.shadowMapResoultion = shadowMapResolution; if(withShadows) shadowMap = new RenderTargetCube(device, shadowMapResolution, false, SurfaceFormat.Single, DepthFormat.Depth24Stencil8); this.depthBias = 1.0f / (20 * radius); }
public RenderTargetBinding(RenderTargetCube renderTarget, CubeMapFace cubeMapFace) { if (renderTarget == null) { throw new ArgumentNullException("renderTarget"); } if (cubeMapFace < CubeMapFace.PositiveX || cubeMapFace > CubeMapFace.NegativeZ) { throw new ArgumentOutOfRangeException("cubeMapFace"); } this._renderTarget = (Texture)renderTarget; this._cubeMapFace = cubeMapFace; }
public RenderTargetBinding(RenderTargetCube renderTarget, CubeMapFace cubeMapFace) { if (renderTarget == null) { throw new ArgumentNullException(nameof(renderTarget)); } if (cubeMapFace < CubeMapFace.PositiveX || cubeMapFace > CubeMapFace.NegativeZ) { throw new ArgumentOutOfRangeException(nameof(cubeMapFace)); } this.renderTarget = renderTarget; this.cubeMapFace = cubeMapFace; }
public void SetRenderTarget(RenderTargetCube renderTarget, CubeMapFace cubeMapFace) { if (renderTarget == null) { this.SetRenderTarget((RenderTarget2D)null); } else { this.SetRenderTargets(new RenderTargetBinding[1] { new RenderTargetBinding(renderTarget, cubeMapFace) }); } }
public RenderTargetBinding(RenderTargetCube renderTarget, CubeMapFace cubeMapFace) { if (renderTarget == null) { throw new ArgumentNullException("renderTarget"); } if (cubeMapFace < CubeMapFace.PositiveX || cubeMapFace > CubeMapFace.NegativeZ) { throw new ArgumentOutOfRangeException("cubeMapFace"); } _renderTarget = renderTarget; _arraySlice = (int)cubeMapFace; }
} // RenderTarget #endregion #region Create /// <summary> /// Creates render target. /// </summary> private void Create() { try { // Create render target of specified size. // On Xbox 360, the render target will discard contents. On PC, the render target will discard if multisampling is enabled, and preserve the contents if not. // I use RenderTargetUsage.PlatformContents to be little more performance friendly with PC. // But I assume that the system works in DiscardContents mode so that an XBOX 360 implementation works. // What I lose, mostly nothing, because I made my own ZBuffer texture and the stencil buffer is deleted no matter what I do. renderTarget = new Microsoft.Xna.Framework.Graphics.RenderTargetCube(EngineManager.Device, Size, MipMap, SurfaceFormat, DepthFormat, RenderTarget.CalculateMultiSampleQuality(Antialiasing), RenderTargetUsage.PlatformContents); alreadyResolved = true; } catch (Exception e) { throw new InvalidOperationException("Render target creation failed", e); } } // Create
/// <summary> /// There is a pool of render targets to avoid wasting unnecessary graphic memory. /// The idea is that a render target has also a flag that tell us if the content is still need or not. /// So, when a shader needs a render target it search in the pool for an unused render target with the right characteristics (size, surface format, etc.) /// The problem if someone has to turn the flag false when the render target’s content is unnecessary and this could be somehow ugly. /// But the graphic pipeline performance is critical, it’s not an area for the user and its complexity was diminished thanks to the new code’s restructuring. /// The pool should be used in the filters, shadow maps and similar shaders. Not everything. /// Use the Release method to return a render target to the pool. /// </summary> public static RenderTargetCube Fetch(int size, SurfaceFormat surfaceFormat, DepthFormat depthFormat, RenderTarget.AntialiasingType antialiasingType, bool mipMap = false) { RenderTargetCube renderTarget; for (int i = 0; i < renderTargets.Count; i++) { renderTarget = renderTargets[i]; if (renderTarget.Size == size && renderTarget.SurfaceFormat == surfaceFormat && renderTarget.DepthFormat == depthFormat && renderTarget.Antialiasing == antialiasingType && renderTarget.MipMap == mipMap && !renderTarget.looked) { renderTarget.looked = true; return renderTarget; } } // If there is not one unlook or present we create one. AssetContentManager userContentManager = AssetContentManager.CurrentContentManager; AssetContentManager.CurrentContentManager = AssetContentManager.SystemContentManager; renderTarget = new RenderTargetCube(size, surfaceFormat, depthFormat, antialiasingType, mipMap); AssetContentManager.CurrentContentManager = userContentManager; renderTargets.Add(renderTarget); renderTarget.looked = true; return renderTarget; } // Fetch
void InitializeTextures() { int width = GFX.Device.PresentationParameters.BackBufferWidth; int height = GFX.Device.PresentationParameters.BackBufferHeight; TexGen = GFX.Inst.ComputeTextureMatrix(new Vector2(width, height)); ColorMap = new RenderTarget2D(GFX.Device, width, height, 1, SurfaceFormat.Color); DepthMap = new RenderTarget2D(GFX.Device, width, height, 1, SurfaceFormat.Single); NormalMap = new RenderTarget2D(GFX.Device, width, height, 1, SurfaceFormat.HalfVector2); DataMap = new RenderTarget2D(GFX.Device, width, height, 1, SurfaceFormat.Color); LightMap = new RenderTarget2D(GFX.Device, width, height, 1, SurfaceFormat.Color); depthStencilScene = new DepthStencilBuffer(GFX.Device, width, height, GFX.Device.DepthStencilBuffer.Format); EmissiveMap = new RenderTarget2D(GFX.Device, width / 4, height / 4, 1, SurfaceFormat.Color); ParticleBuffer = new RenderTarget2D(GFX.Device, width / 8, height / 8, 1, SurfaceFormat.Color); BackBufferTexture = new ResolveTexture2D(GFX.Device, width, height, 1, SurfaceFormat.Color); CubeMap = new RenderTargetCube(GFX.Device, CubeMapSize, 1, SurfaceFormat.Color); }
public void Render(RenderTargetCube activeRT, CubeMapFace activeFace) { targetToRenderToCube = activeRT; faceToRenderOn = activeFace; this.Render(); }
public Lights(Game game, int resolution) : base(game) { this.LightCube = new RenderTargetCube(game.GraphicsDevice, resolution, 1, SurfaceFormat.Single); }
void IContentOwner.LoadContent(ContentState state) { if (IsDisposed) return; GraphicsDevice device = state; if (texture != null && texture.GraphicsDevice != device) { if (cloneOf == null) { texture.Dispose(); } texture = null; } Warm(state); }
/// <summary> /// Dispose the draw target and all resources used. If this render target is a clone, the shared resources are NOT disposed /// </summary> public void Dispose() { isDisposed = true; if (cloneOf == null) { if (texture != null) texture.Dispose(); } this.texture = null; }
/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { basicEffect = new BasicEffect(graphics.GraphicsDevice); // Setting the projection matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver2, graphics.GraphicsDevice.Viewport.AspectRatio, 0.1f, 100.0f); // Setting the sphere position and world matrix spherePos = Vector3.Zero; sphereWorld = Matrix.CreateScale(3f) * Matrix.CreateTranslation(spherePos); // Setting the post render target PresentationParameters pp = graphics.GraphicsDevice.PresentationParameters; postRenderTarget = new RenderTarget2D(graphics.GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, graphics.GraphicsDevice.DisplayMode.Format, DepthFormat.Depth24); // Setting the environment render target and texture environmentRenderTarget = new RenderTargetCube(graphics.GraphicsDevice, 256, true, graphics.GraphicsDevice.DisplayMode.Format, DepthFormat.Depth24); environmentRenderTexture = new TextureCube(graphics.GraphicsDevice, 256, true, graphics.GraphicsDevice.DisplayMode.Format); base.Initialize(); }
private void DrawCubeFace(Light light, RenderTargetCube cube, CubeMapFace cubeMapFace, GameTime gameTime) { Vector3 position = lightService.Position + light.Position; Vector3 forward = Vector3.Zero; Vector3 up = Vector3.Up; // Rendertarget auf eine Seite des Shadow Cubes setzen GraphicsDevice.SetRenderTarget(cube, cubeMapFace); GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.White, 1.0f, 0); switch (cubeMapFace) { case CubeMapFace.PositiveX: forward = Vector3.Right; break; case CubeMapFace.NegativeX: forward = Vector3.Left; break; case CubeMapFace.PositiveY: forward = Vector3.Up; up = Vector3.Backward; break; case CubeMapFace.NegativeY: forward = Vector3.Down; up = Vector3.Forward; break; case CubeMapFace.PositiveZ: forward = Vector3.Forward; break; case CubeMapFace.NegativeZ: forward = Vector3.Backward; break; } shadowEffect.LightPosition = position; shadowEffect.View = Matrix.CreateLookAt(position, position + forward, up); shadowEffect.CurrentTechnique.Passes[0].Apply(); // Objekt auf den Shadow Cube rendern shape.Draw(gameTime); }
/// <summary> /// Renders the environment maps for the image-based lights. /// </summary> /// <remarks> /// This method uses the current DeferredGraphicsScreen to render new environment maps at /// runtime. The DeferredGraphicsScreen has a SceneCaptureRenderer which we can use to /// capture environment maps of the current scene. /// To capture new environment maps the flag _updateEnvironmentMaps must be set to true. /// When this flag is set, SceneCaptureNodes are added to the scene. When the graphics /// screen calls the SceneCaptureRenderer the next time, the new environment maps will be /// captured. /// The flag _updateEnvironmentMaps remains true until the new environment maps are available. /// This method checks the SceneCaptureNode.LastFrame property to check if new environment maps /// have been computed. Usually, the environment maps will be available in the next frame. /// (However, the XNA Game class can skip graphics rendering if the game is running slowly. /// Then we would have to wait more than 1 frame.) /// When environment maps are being rendered, the image-based lights are disabled to capture /// only the scene with ambient and directional lights. Dynamic objects are also disabled /// to capture only the static scene. /// </remarks> private void UpdateEnvironmentMaps() { if (!_updateEnvironmentMaps) return; // One-time initializations: if (_sceneCaptureNodes[0] == null) { // Create cube maps and scene capture nodes. // (Note: A cube map size of 256 is enough for surfaces with a specular power // in the range [0, 200000].) for (int i = 0; i < _sceneCaptureNodes.Length; i++) { var renderTargetCube = new RenderTargetCube( GraphicsService.GraphicsDevice, 256, true, SurfaceFormat.Color, DepthFormat.None); var renderToTexture = new RenderToTexture { Texture = renderTargetCube }; var projection = new PerspectiveProjection(); projection.SetFieldOfView(ConstantsF.PiOver2, 1, 1, 100); _sceneCaptureNodes[i] = new SceneCaptureNode(renderToTexture) { CameraNode = new CameraNode(new Camera(projection)) { PoseWorld = _lightNodes[i].PoseWorld, }, }; _imageBasedLights[i].Texture = renderTargetCube; } // We use a ColorEncoder to encode a HDR image in a normal Color texture. _colorEncoder = new ColorEncoder(GraphicsService) { SourceEncoding = ColorEncoding.Rgb, TargetEncoding = ColorEncoding.Rgbm, }; // The SceneCaptureRenderer has a render callback which defines what is rendered // into the scene capture render targets. _graphicsScreen.SceneCaptureRenderer.RenderCallback = context => { var graphicsDevice = GraphicsService.GraphicsDevice; var renderTargetPool = GraphicsService.RenderTargetPool; // Get scene nodes which are visible by the current camera. CustomSceneQuery sceneQuery = context.Scene.Query<CustomSceneQuery>(context.CameraNode, context); // The final image has to be rendered into this render target. var ldrTarget = context.RenderTarget; // Use an intermediate HDR render target with the same resolution as the final target. var format = new RenderTargetFormat(ldrTarget) { SurfaceFormat = SurfaceFormat.HdrBlendable, DepthStencilFormat = DepthFormat.Depth24Stencil8 }; var hdrTarget = renderTargetPool.Obtain2D(format); graphicsDevice.SetRenderTarget(hdrTarget); context.RenderTarget = hdrTarget; // Render scene (without post-processing, without lens flares, no debug rendering, no reticle). _graphicsScreen.RenderScene(sceneQuery, context, false, false, false, false); // Convert the HDR image to RGBM image. context.SourceTexture = hdrTarget; context.RenderTarget = ldrTarget; _colorEncoder.Process(context); context.SourceTexture = null; // Clean up. renderTargetPool.Recycle(hdrTarget); context.RenderTarget = ldrTarget; }; } if (_sceneCaptureNodes[0].Parent == null) { // Add the scene capture nodes to the scene. for (int i = 0; i < _sceneCaptureNodes.Length; i++) _graphicsScreen.Scene.Children.Add(_sceneCaptureNodes[i]); // Remember the old time stamp of the nodes. _oldEnvironmentMapTimeStamp = _sceneCaptureNodes[0].LastFrame; // Disable all lights except ambient and directional lights. // We do not capture the image-based lights or any other lights (e.g. point lights) // in the cube map. foreach (var lightNode in _graphicsScreen.Scene.GetDescendants().OfType<LightNode>()) lightNode.IsEnabled = (lightNode.Light is AmbientLight) || (lightNode.Light is DirectionalLight); // Disable dynamic objects. foreach (var node in _graphicsScreen.Scene.GetDescendants()) if (node is MeshNode || node is LodGroupNode) if (!node.IsStatic) node.IsEnabled = false; } else { // The scene capture nodes are part of the scene. Check if they have been // updated. if (_sceneCaptureNodes[0].LastFrame != _oldEnvironmentMapTimeStamp) { // We have new environment maps. Restore the normal scene. for (int i = 0; i < _sceneCaptureNodes.Length; i++) _graphicsScreen.Scene.Children.Remove(_sceneCaptureNodes[i]); _updateEnvironmentMaps = false; foreach (var lightNode in _graphicsScreen.Scene.GetDescendants().OfType<LightNode>()) lightNode.IsEnabled = true; foreach (var node in _graphicsScreen.Scene.GetDescendants()) if (node is MeshNode || node is LodGroupNode) if (!node.IsStatic) node.IsEnabled = true; } } }
public RenderTargetBinding(RenderTargetCube renderTarget, CubeMapFace cubeMapFace) { this.RenderTarget = null; this.CubeMapFace = cubeMapFace; }
public unsafe void SetRenderTarget(RenderTargetCube renderTarget, CubeMapFace cubeMapFace) { }
public MainScene(WarGame game) : base(game) { // creating post render target with 24-bit depth PresentationParameters pp = game.Graphics.GraphicsDevice.PresentationParameters; postTarget = new RenderTarget2D(game.Graphics.GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, game.Graphics.GraphicsDevice.DisplayMode.Format, DepthFormat.Depth24); // creating objects used by environment shader alienBaseEnvironmentRenTarget = new RenderTargetCube(game.Graphics.GraphicsDevice, 256, false, game.Graphics.GraphicsDevice.DisplayMode.Format, DepthFormat.Depth24); alienBaseEnvironmentTextureCube = new TextureCube(game.Graphics.GraphicsDevice, 256, false, game.Graphics.GraphicsDevice.DisplayMode.Format); // creating selection rectangle and adding it to the Scene SelectionRectangle = new SelectionRectangle(game, this); SceneComponents.Add(SelectionRectangle); // the game is initially not in the debug mode IsInDebugMode = false; // adding ground element to the Scene groundElement = new GroundElement(game, new Vector3(0, groundYAxisPosition, 0), this); SceneComponents.Add(groundElement); sceneObjects.Add(groundElement); // setting the position of the alien base alienBasePosition = new Vector3(170, groundYAxisPosition, 170); //adding alien's base to the Scene AlienBase = new AlienBuilding(game, alienBasePosition, this); SceneComponents.Add(AlienBase); sceneObjects.Add(AlienBase); // adding alien crafts to the Scene for (int i = 0; i < numberOfAliens; i++) { AlienCraft a; // placing new craft in the first random and free place do { Vector3 randomPosition = new Vector3(AlienBase.Position.X + (float)WarGame.RandomGenerator.NextDouble() * 50.0f - 25.0f, GroundYAxisPosition + 1.0f, AlienBase.Position.Z + (float)WarGame.RandomGenerator.NextDouble() * 50.0f - 25.0f); a = new AlienCraft(game, this, randomPosition); } while (a.CheckForCollisions() != null); SceneComponents.Add(a); sceneObjects.Add(a); alienCrafts.Add(a); } // adding skybox to the Scene SceneComponents.Add(new Skybox(game)); }
/// <summary> /// Create a draw target cubemap directly from an XNA render target (not recommended) /// </summary> /// <param name="camera"></param> /// <param name="renderTexture"></param> /// <returns></returns> public static DrawTargetTextureCube CreateFromRenderTargetCube(ICamera camera, RenderTargetCube renderTexture) { return new DrawTargetTextureCube(camera, renderTexture); }
private DrawTargetTextureCube(ICamera camera, RenderTargetCube texture) : base(camera) { if (texture == null) throw new ArgumentNullException(); this.texture = texture; this.resolution = texture.Size; this.sizeAsVector = new Vector4((float)this.resolution, (float)this.resolution,0,0); SetHasDepth(); }
protected override void Initialize() { base.Initialize(); // Größe und Position des Raums festlegen room.Size = new Vector3(1000.0f, 500.0f, 1000.0f); room.Position = new Vector3(0.0f, 250.0f, 0.0f); float sin = (float)Math.Sin(MathHelper.ToRadians(30.0f)); float cos = (float)Math.Cos(MathHelper.ToRadians(30.0f)); // Lichter hinzufügen lightService.Size = Vector3.One * 10.0f; lightService.Position = Vector3.Up * 100.0f; lightService.AddLight(new Vector3(0.0f, 0.0f, 1.0f) * 60.0f, Color.Red.ToVector3()); lightService.AddLight(new Vector3(+cos, 0.0f, -sin) * 60.0f, Color.Green.ToVector3()); lightService.AddLight(new Vector3(-cos, 0.0f, -sin) * 60.0f, Color.Blue.ToVector3()); // Kamera-Position festlegen camera.Position = new Vector3(0.0f, 80.0f, 200.0f); // Shadow Cube erstellen shadowCube = new RenderTargetCube(GraphicsDevice, 1024, false, SurfaceFormat.Single, DepthFormat.Depth24); int width = GraphicsDevice.PresentationParameters.BackBufferWidth; int height = GraphicsDevice.PresentationParameters.BackBufferHeight; // Blur Map erstellen blurMap = new RenderTarget2D(GraphicsDevice, width, height, false, SurfaceFormat.Single, DepthFormat.Depth24); spriteBatch = new SpriteBatch(GraphicsDevice); // Quad für Lightmap Blurring erstellen quadVertices = new VertexPositionTexture[4]; quadVertices[0] = new VertexPositionTexture(new Vector3(-1, -1, 0), new Vector2(0, 1)); quadVertices[1] = new VertexPositionTexture(new Vector3(-1, 1, 0), new Vector2(0, 0)); quadVertices[2] = new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 0)); quadVertices[3] = new VertexPositionTexture(new Vector3(1, -1, 0), new Vector2(1, 1)); quadIndices = new int[] { 0, 1, 2, 2, 3, 0 }; }
internal override void Warm(Application application,GraphicsDevice device) { if (cloneOf != null) { CloneRoot.Warm(application); this.texture = CloneRoot.texture; return; } if (!ownerRegistered) { ownerRegistered = true; application.Content.AddHighPriority(this); } if (texture == null) { this.texture = new RenderTargetCube(device, resolution, mipmap, format, depthFormat, (int)multisample, usage); } }
public void SetRenderTarget(int renderTargetIndex, RenderTargetCube renderTarget, CubeMapFace faceType) { throw new NotImplementedException(); }
protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // Overlay component, used to draw the pause menu and game over menu overlayComponent = new OverlayComponent(Game, spriteBatch); Game.Components.Add(overlayComponent); projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.1f, 50000); directionalLight = new DirectionalLight( new Vector3(-1.25f, -2f, 5.0f), // Direction new Vector3(.1f, .1f, .1f),//new Vector3(.15f, .14f, .29f), // Ambient new Vector3(.46f, .33f, .75f)); // Diffuse Game.AddService(typeof(DirectionalLight), directionalLight); #region Level terrain generation int heightMapSize = terrainSegmentsCount * terrainSegmentSize + 1; float halfHeightMapSize = heightMapSize / 2f; HeightMap heightmapGenerator = new HeightMap(heightMapSize); var heightMap = heightmapGenerator.Generate(); var roadMap = new float[heightMapSize, heightMapSize]; raceTrack = new RaceTrack(heightMapSize, terrainScale); navMesh = new NavMesh(GraphicsDevice, raceTrack.Curve, //1500, roadWidth, terrainScale); 750, roadWidth, terrainScale); Vector3 lastPosition = raceTrack.Curve.GetPoint(.01f) / terrainScale; for (float t = 0; t < 1; t += .0002f) { var e = raceTrack.Curve.GetPoint(t) / terrainScale; for (float j = -roadFalloff; j <= roadFalloff; j++) { var pos = e + j * Vector3.Normalize(Vector3.Cross(lastPosition - e, Vector3.Up)); // Indices int x = (int)(pos.X + halfHeightMapSize), z = (int)(pos.Z + halfHeightMapSize); float height = e.Y; if (Math.Abs(j) <= roadWidth) { heightMap[x, z] = height; roadMap[x, z] = 1; } else { float amount = (Math.Abs(j) - roadWidth) / (roadFalloff - roadWidth); heightMap[x, z] = MathHelper.Lerp(height, heightMap[x, z], amount); roadMap[x, z] = amount / 10f; } } lastPosition = e; } heightmapGenerator.Smoothen(); heightmapGenerator.Perturb(30f); for (int i = 0; i < 5; i++) { heightmapGenerator.Smoothen(); } terrainEffect = content.Load<Effect>(@"Effects\TerrainShading"); //terrainEffect.Parameters["TextureMap0"].SetValue(content.Load<Texture2D>(@"Terrain\sand")); #region TEXTURE RENDERING //var unprocessedGrassTexture = content.Load<Texture2D>(@"Terrain\grass"); //var grassTexture = new RenderTarget2D(GraphicsDevice, unprocessedGrassTexture.Width, unprocessedGrassTexture.Height); //GraphicsDevice.SetRenderTarget(grassTexture); //spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); //spriteBatch.Draw(unprocessedGrassTexture, new Rectangle(0, 0, unprocessedGrassTexture.Width, unprocessedGrassTexture.Height), Color.White); //spriteBatch.Draw(content.Load<Texture2D>(@"Particles\fire"), new Rectangle(0, 0, unprocessedGrassTexture.Width, unprocessedGrassTexture.Height), Color.White); //spriteBatch.End(); //GraphicsDevice.SetRenderTarget(null); //terrainEffect.Parameters["TextureMap1"].SetValue(grassTexture); #endregion terrainEffect.Parameters["TextureMap0"].SetValue(content.Load<Texture2D>(@"Terrain\road")); terrainEffect.Parameters["TextureMap1"].SetValue(content.Load<Texture2D>(@"Terrain\grass")); terrainEffect.Parameters["TextureMap2"].SetValue(content.Load<Texture2D>(@"Terrain\rock")); terrainEffect.Parameters["TextureMap3"].SetValue(content.Load<Texture2D>(@"Terrain\snow")); terrainEffect.Parameters["RoadNormalMap"].SetValue(content.Load<Texture2D>(@"Terrain\road_n")); terrainEffect.Parameters["Projection"].SetValue(projectionMatrix); // Creates a terrainmodel around Vector3.Zero terrainSegments = new TerrainModel[terrainSegmentsCount, terrainSegmentsCount]; float terrainStart = -.5f * heightMapSize; for (int z = 0; z < terrainSegmentsCount; z++) { for (int x = 0; x < terrainSegmentsCount; x++) { terrainSegments[x, z] = new TerrainModel(GraphicsDevice, terrainSegmentSize, terrainSegmentsCount, terrainStart, x * terrainSegmentSize, z * terrainSegmentSize, terrainScale, heightMap, roadMap, terrainEffect, directionalLight); } } #endregion #region Car Car = MakeCar(); gameInstance.AddService(typeof(Car), Car); Player localPlayer = gameInstance.GetService<ServerClient>().LocalPlayer; gameInstance.GetService<CarControlComponent>().Cars[localPlayer] = Car; gameInstance.AddService(typeof(Player), localPlayer); #endregion #region Lights // Load model to represent our lightsources var pointLightModel = content.Load<Model>(@"Models\light"); //spotLightModel = content.Load<Model>(@"Models\Cone"); Vector3 pointLightOffset = new Vector3(0, 250, 0); var cr = new CurveRasterization(raceTrack.Curve, 50); float colorOffset = 0f; foreach (var point in cr.Points) { Random r = UniversalRandom.GetInstance(); Vector3 color = new Vector3(0f,0f,0f); PointLight pl = new PointLight(point.Position + pointLightOffset + Vector3.Transform(50 * Vector3.Up, Matrix.CreateRotationZ(MathHelper.TwoPi * (float)UniversalRandom.GetInstance().NextDouble())), color, 450) { Model = pointLightModel, ColorTimeOffset = colorOffset }; pointLights.Add(pl); GraphicalObjects.Add(pl); colorOffset += 100 / cr.Points.Count; } #endregion dustEmitter = new ParticleEmitter(dustSystem, 150, Car.Position); #region SkySphere skyBoxModel = content.Load<Model>(@"Models/skybox"); skyBoxEffect = content.Load<Effect>(@"Effects/SkyBox"); skyMap = new TextureCube(GraphicsDevice, 2048, false, SurfaceFormat.Color); string[] cubemapfaces = { @"SkyBoxes/PurpleSky/skybox_right1", @"SkyBoxes/PurpleSky/skybox_left2", @"SkyBoxes/PurpleSky/skybox_top3", @"SkyBoxes/PurpleSky/skybox_bottom4", @"SkyBoxes/PurpleSky/skybox_front5", @"SkyBoxes/PurpleSky/skybox_back6_2" }; //cubeMap = new TextureCube(GraphicsDevice, 1024, false, SurfaceFormat.Color); //string[] cubemapfaces = { // @"SkyBoxes/StormyDays/stormydays_ft", // @"SkyBoxes/StormyDays/stormydays_bk", // @"SkyBoxes/StormyDays/stormydays_up", // @"SkyBoxes/StormyDays/stormydays_dn", // @"SkyBoxes/StormyDays/stormydays_rt", // @"SkyBoxes/StormyDays/stormydays_lf" //}; //cubeMap = new TextureCube(GraphicsDevice, 1024, false, SurfaceFormat.Color); //string[] cubemapfaces = { // @"SkyBoxes/Miramar/miramar_ft", // @"SkyBoxes/Miramar/miramar_bk", // @"SkyBoxes/Miramar/miramar_up", // @"SkyBoxes/Miramar/miramar_dn", // @"SkyBoxes/Miramar/miramar_rt", // @"SkyBoxes/Miramar/miramar_lf" //}; for (int i = 0; i < cubemapfaces.Length; i++) LoadCubemapFace(skyMap, cubemapfaces[i], (CubeMapFace)i); skyBoxEffect.Parameters["SkyboxTexture"].SetValue(skyMap); foreach (var mesh in skyBoxModel.Meshes) foreach (var part in mesh.MeshParts) part.Effect = skyBoxEffect; #endregion #region Weather thunderBoltGenerator = new ThunderBoltGenerator(gameInstance, thunderParticleSystem); gameInstance.Components.Add(thunderBoltGenerator); #endregion #region GameObjects OakTree.LoadMaterial(content); BirchTree.LoadMaterial(content); Stone.LoadMaterial(content); int numObjects = 75; for (int i = 0; i < numObjects; i++) { var t = navMesh.triangles[UniversalRandom.GetInstance().Next(navMesh.triangles.Length)]; float v = (float)UniversalRandom.GetInstance().NextDouble(); //float u = (float) (UniversalRandom.GetInstance().NextDouble() - 1/2f); //if (u < 0) // u -= .5f; //else // u += 1.5f; float u = 0; if (UniversalRandom.GetInstance().NextDouble() <= .5) u = -.5f - .3f * (float)(-UniversalRandom.GetInstance().NextDouble()); else u = (float)(1.5f + .3f * UniversalRandom.GetInstance().NextDouble()); var pos = (t.vertices[0] + u * t.ab + v * t.ac) / terrainScale; //var treePos = new Vector3(-halfHeightMapSize + (float)UniversalRandom.GetInstance().NextDouble() * (heightMapSize-50), 0, // -halfHeightMapSize + (float)UniversalRandom.GetInstance().NextDouble() * (heightMapSize-50)); float X = pos.X + heightMapSize / 2f, Z = pos.Z +heightMapSize / 2f; float Xlerp = X % 1f, Zlerp = Z % 1f; int x0 = (int)X, z0 = (int)Z, x1 = x0 + 1, z1 = z0 + 1; float height; float k; if (Xlerp + Zlerp > 1) { float h1 = MathHelper.Lerp(heightMap[x0, z1], heightMap[x1, z1], Xlerp); float h2 = MathHelper.Lerp(heightMap[x1, z0], heightMap[x1, z1], Zlerp); k = h2 / h1; height = MathHelper.Lerp(h1, h2, .5f); } else { float h1 = MathHelper.Lerp(heightMap[x0, z0], heightMap[x1, z0], Xlerp), h2 = MathHelper.Lerp(heightMap[x0, z0], heightMap[x0, z1], Zlerp); k = h2 / h1; height = MathHelper.Lerp(h1, h2, .5f); } pos.Y = height - 0.002f; if (k > 1.02 ) continue; GameObject obj; switch(UniversalRandom.GetInstance().Next(0, 3)) { case 0: obj = new OakTree(gameInstance); obj.Scale = 3 + 3 * (float)UniversalRandom.GetInstance().NextDouble(); FireflyCandidates.Add(obj); break; case 1: obj = new BirchTree(gameInstance); obj.Scale = 3 + 3 * (float)UniversalRandom.GetInstance().NextDouble(); FireflyCandidates.Add(obj); break; default: obj = new Stone(gameInstance); obj.Scale = 0.5f + (float)(.25 * UniversalRandom.GetInstance().NextDouble()); break; } obj.Position = terrainScale * pos; obj.Rotation = new Vector3(0, MathHelper.Lerp(0, MathHelper.Pi * 2, (float)UniversalRandom.GetInstance().NextDouble()), 0); GraphicalObjects.Add(obj); ShadowCasterObjects.Add(obj); } for (int i = 0; i < FireflyCandidates.Count; i+=5) { ParticleEmitter emitter = new ParticleEmitter(fireflySystem, 80, FireflyCandidates[i].Position); emitter.Origin = FireflyCandidates[i].Position + Vector3.Up * 500; fireflyEmitter.Add(emitter); } #endregion //foreach (GameObject obj in GraphicalObjects) //{ // pointLights.Add(new PointLight(obj.Position + Vector3.Up * 500, new Vector3(0.7f, 0.7f, 0.7f), 450) // { // Model = pointLightModel // }); //} //GraphicalObjects.AddRange(pointLights); //List<FireObject> list = new List<FireObject>(); //foreach (PointLight p in pointLights) //{ // FireObject obj = new FireObject(gameInstance, content, p.Position, p.Position + Vector3.Up * 10); // list.Add(obj); //} //pointLights.AddRange(list); //GraphicalObjects.AddRange(list); #region Cameras var input = gameInstance.GetService<InputComponent>(); gameInstance.GetService<CameraComponent>().AddCamera(new DebugCamera(new Vector3(-11800, 3000, -8200), input)); Camera c; gameInstance.GetService<CameraComponent>().AddCamera(c = new ThirdPersonCamera(Car, input)); gameInstance.GetService<CameraComponent>().CurrentCamera = c; #endregion #region DynamicEnvironment // TODO: CARMOVE environmentCubeMap = new RenderTargetCube(this.GraphicsDevice, 256, true, SurfaceFormat.Color, DepthFormat.Depth16); Car.EnvironmentMap = skyMap; #endregion #region PostProcess postProcessingComponent = new PostProcessingComponent(Game); Game.Components.Add(postProcessingComponent); postProcessTexture = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, true, SurfaceFormat.Color, DepthFormat.Depth24); #endregion // Adding a prelighingrenderer as a service prelightingRenderer = new PrelightingRenderer(GraphicsDevice, content); Game.AddService(typeof(PrelightingRenderer), prelightingRenderer); #region ShadowMapEffect shadowMapEffect = content.Load<Effect>(@"Effects\ShadowMap"); #endregion #region Gameplay Trigger Manager (with sample) /// <summary> /// Gets the triggermanager /// Add new PositionTrigger /// Hook up to listener => when hit, use the thunderBoltGenerator and spawn a flash /// Adds it to triggers. /// </summary> //var triggerManager = gameInstance.GetService<TriggerManager>(); //int noOfCheckpoints = 10; //for (int i = 0; i < noOfCheckpoints; i++) //{ // var trigger = new PositionTrigger(raceTrack.CurveRasterization, (int)(((float)i / noOfCheckpoints) * raceTrack.CurveRasterization.Points.Count), true, true); // string cp = "Checkpoint " + i; // trigger.Triggered += (sender, e) => // { // Console.WriteLine(cp); // }; // triggerManager.Triggers.Add("checkpoint"+i, trigger); //} #endregion #region Game Mode if (gameInstance.GetService<ServerClient>().connected) { foreach (var player in gameInstance.GetService<ServerClient>().Players.Values) { gameInstance.GetService<CarControlComponent>().AddCar(player, null, this); } var carList = gameInstance.GetService<CarControlComponent>().Cars.OrderBy(pc => pc.Key.ID).Select(pc => pc.Value).ToList(); SetCarsAtStart(carList); } int cp = 6; if (gameModeChoice == GameModeChoice.SimpleRace) this.mode = new SimpleRaceMode(gameInstance, 3, cp, raceTrack, Car); else if (gameModeChoice == GameModeChoice.Multiplayer) this.mode = new MultiplayerRaceMode(gameInstance, 3, cp, raceTrack, Car); else throw new Exception("Stop choosing weird game modes"); gameInstance.AddService(typeof(GameplayMode), mode); #endregion #region Checkpoint lights for (int i=0; i<cp; i++) { var point = raceTrack.GetCurveRasterization(cp).Points[i]; var pl = new CheckpointLight(point.Position + 500 * Vector3.Up) { Model = pointLightModel }; pointLights.Add(pl); GraphicalObjects.Add(pl); #region Fire int halfnumberoffire = 5; for (int o = -halfnumberoffire + 1; o < halfnumberoffire; o++) { Vector3 side = Vector3.Cross(Vector3.Normalize(raceTrack.Curve.GetPoint((i) / (float)cp + .001f) - point.Position), Vector3.Up); var fire = new FireObject(content, fireSystem, fireSmokeSystem, point.Position + side * 100 * o - Vector3.Up * 400 + Vector3.Up * 650 * (float)Math.Cos(o/(float)halfnumberoffire), Vector3.Up * 10); pointLights.Add(fire); GraphicalObjects.Add(fire); } #endregion } #endregion #region BackgroundSound loopSoundManager.AddNewSound("forestambient"); #endregion prelightingRenderer.GameObjects = GraphicalObjects; init = true; }
/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { RasterizerState rs = new RasterizerState(); rs.CullMode = CullMode.None; graphics.GraphicsDevice.RasterizerState = rs; camera = new Camera(GraphicsDevice); fcamera = new FlyingCamera(); InputHandler ip = new InputHandler(this); Components.Add(ip); Services.AddService(typeof(IInputHandler), ip); renderManager = new RenderManager(this); sceneManager = new SceneManager(this); // Reflection //RefCubeMap = new RenderTargetCube(GraphicsDevice, 256, false, SurfaceFormat.Color, DepthFormat.Depth16, 1, RenderTargetUsage.PreserveContents); RefCubeMap = new RenderTargetCube(this.GraphicsDevice, 256, false, SurfaceFormat.Color, DepthFormat.None); base.Initialize(); }
public void SetCubeMapTarget(RenderTargetCube cubemap, CubeMapFace faceMode) { this.cubeMapRef = cubemap; this.cubeMapFace = faceMode; this.ReflectionMap.Dispose(); this.ReflectionMap = null; }
private TextureCube RenderCubeMap(Vector3 position) { TextureCube debug; //RenderTargetCube RefCubeMap = new RenderTargetCube(device, 256, 1, SurfaceFormat.Color); RenderTargetCube RefCubeMap = new RenderTargetCube(graphicsDevice, graphicsDevice.Viewport.Width, true, SurfaceFormat.Color, DepthFormat.Depth24); Matrix viewMatrix = Matrix.Identity; TargetCamera camera; // Render our cube map, once for each cube face( 6 times ). for (int i = 0; i < 6; i++) { // render the scene to all cubemap faces CubeMapFace cubeMapFace = (CubeMapFace)i; switch (cubeMapFace) { case CubeMapFace.NegativeX: { //Vector3 target = new Vector3 viewMatrix = Matrix.CreateLookAt(position, position + Vector3.Left, Vector3.Up); break; } case CubeMapFace.NegativeY: { viewMatrix = Matrix.CreateLookAt(position, position + Vector3.Down, Vector3.Forward); break; } case CubeMapFace.NegativeZ: { viewMatrix = Matrix.CreateLookAt(position, position + Vector3.Backward, Vector3.Up); break; } case CubeMapFace.PositiveX: { viewMatrix = Matrix.CreateLookAt(position, position + Vector3.Right, Vector3.Up); break; } case CubeMapFace.PositiveY: { viewMatrix = Matrix.CreateLookAt(position, position + Vector3.Up, Vector3.Backward); break; } case CubeMapFace.PositiveZ: { viewMatrix = Matrix.CreateLookAt(position, position + Vector3.Forward, Vector3.Up); break; } } //effect.Parameters["matWorldViewProj"].SetValue(worldMatrix * viewMatrix * projMatrix); camera = new TargetCamera(position, Vector3.Zero, graphicsDevice); camera.View = viewMatrix; camera.Projection = this.camera.Projection; // Set the cubemap render target, using the selected face //device.SetRenderTarget(RefCubeMap, cubeMapFace); graphicsDevice.SetRenderTarget(RefCubeMap, cubeMapFace); graphicsDevice.Clear(Color.White); this.DrawScene(camera); graphicsDevice.SetRenderTarget(null); } graphicsDevice.SetRenderTarget(null); /*if (!hasSaved) { debug = RefCubeMap;// null!? DDSLib.DDSToFile("cubeMapFace_debug.dds", true, debug, false); }*/ return RefCubeMap; }