void IDrawableAlphaComponent.DrawAlpha(GameTime time, RenderParameters parameters) { if (this.Alpha > 0.0f) { base.Draw(time, parameters); } }
void IDrawablePreFrameComponent.DrawPreFrame(GameTime time, RenderParameters p) { if (!this.EnableReflection || !this.isVisible(p.Camera)) { return; } if (this.needResize) { this.resize(); } float waterHeight = this.Position.Value.Y; if (p.Camera.Position.Value.Y > waterHeight) { this.parameters.ClipPlanes = new[] { new Plane(Vector3.Up, -waterHeight) }; Matrix reflect = Matrix.CreateTranslation(0.0f, -waterHeight, 0.0f) * Matrix.CreateScale(1.0f, -1.0f, 1.0f) * Matrix.CreateTranslation(0.0f, waterHeight, 0.0f); this.camera.Position.Value = Vector3.Transform(p.Camera.Position, reflect); this.camera.View.Value = reflect * p.Camera.View; this.camera.SetProjectionFromCamera(p.Camera); this.renderer.SetRenderTargets(this.parameters); this.main.DrawScene(this.parameters); this.renderer.PostProcess(this.buffer, this.parameters); } }
void INonPostProcessedDrawableComponent.DrawNonPostProcessed(GameTime time, RenderParameters parameters) { if (this.Alpha > 0.0f) { base.Draw(time, parameters); } }
public void SetMaterials(RenderParameters p) { foreach (KeyValuePair <Model.Material, int> pair in this.materials) { p.MaterialData[pair.Value] = new Vector2(pair.Key.SpecularPower, pair.Key.SpecularIntensity); } }
void INonPostProcessedDrawableComponent.DrawNonPostProcessed(GameTime time, RenderParameters parameters) { if (this.RenderTarget.Value == null) { Viewport vp = this.main.GraphicsDevice.Viewport; this.draw(time, new Point(vp.Width, vp.Height)); } }
/// <summary> /// Draws the full screen quad /// </summary> /// <param name="graphicsDevice">The GraphicsDevice to use for rendering</param> public virtual void DrawAlpha(GameTime time, RenderParameters p) { // Set the vertex buffer and declaration this.main.GraphicsDevice.SetVertexBuffer(this.vertexBuffer); // Draw primitives this.main.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); }
void INonPostProcessedDrawableComponent.DrawNonPostProcessed(GameTime time, RenderParameters parameters) { RasterizerState originalState = this.main.GraphicsDevice.RasterizerState; Point screenSize = this.main.ScreenSize; this.Batch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, this.RasterizerState, null, Matrix.Identity); this.Root.Draw(time, Matrix.Identity, new Rectangle(0, 0, screenSize.X, screenSize.Y)); this.Batch.End(); this.main.GraphicsDevice.RasterizerState = originalState; }
protected override bool setParameters(Matrix transform, RenderParameters parameters) { bool result = base.setParameters(transform, parameters); if (result) { this.effect.Parameters["DepthBuffer"].SetValue(parameters.DepthBuffer); } return(result); }
protected override bool setParameters(Matrix transform, RenderParameters parameters) { bool result = base.setParameters(transform, parameters); if (result) { this.effect.Parameters["Bones"].SetValue(this.skinTransforms); } return(result); }
public override void DrawAlpha(GameTime time, RenderParameters p) { if (p.IsMainRender) { this.effect.CurrentTechnique.Passes[0].Apply(); p.Camera.SetParameters(this.effect); this.effect.Parameters["Depth" + Model.SamplerPostfix].SetValue(p.DepthBuffer); base.DrawAlpha(time, p); } }
protected override void drawInstances(RenderParameters parameters, Matrix transform) { if (parameters.IsMainRender) { for (int i = 0; i < this.instances.Length; i++) { this.instances.Changed(i, this.instances[i]); } } base.drawInstances(parameters, transform); }
protected override bool setParameters(Matrix transform, RenderParameters parameters) { bool result = base.setParameters(transform, parameters); if (result) { if (this.Distortion) { this.effect.Parameters["Frame" + Model.SamplerPostfix].SetValue(parameters.FrameBuffer); } } return(result); }
public virtual void Draw(GameTime time, RenderParameters parameters) { Matrix transform = Matrix.CreateScale(this.Scale) * this.Transform; if (!this.IsInstanced) { this.draw(parameters, transform); } else { this.drawInstances(parameters, transform); } }
void IDrawablePreFrameComponent.DrawPreFrame(GameTime time, RenderParameters parameters) { if (this.needResize) { this.resize(); } if (this.RenderTarget.Value != null) { this.main.GraphicsDevice.SetRenderTarget(this.RenderTarget); this.main.GraphicsDevice.Clear(this.RenderTargetBackground); this.draw(time, this.RenderTargetSize); } }
/// <summary> /// Draws a single mesh using the given world matrix. /// </summary> /// <param name="camera"></param> /// <param name="transform"></param> protected virtual void draw(RenderParameters parameters, Matrix transform) { if (this.model != null) { if (this.setParameters(transform, parameters)) { this.main.LightingManager.SetRenderParameters(this.effect, parameters); RasterizerState originalState = this.main.GraphicsDevice.RasterizerState; RasterizerState noCullState = null; if (this.DisableCulling) { noCullState = new RasterizerState { CullMode = CullMode.None }; this.main.GraphicsDevice.RasterizerState = noCullState; } for (int i = 0; i < this.model.Meshes.Count; i++) { ModelMesh mesh = this.model.Meshes[i]; for (int j = 0; j < mesh.MeshParts.Count; j++) { ModelMeshPart part = mesh.MeshParts[j]; if (part.NumVertices > 0) { // Draw all the instance copies in a single call. this.effect.CurrentTechnique.Passes[0].Apply(); this.main.GraphicsDevice.SetVertexBuffer(part.VertexBuffer, part.VertexOffset); this.main.GraphicsDevice.Indices = part.IndexBuffer; this.main.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, part.NumVertices, part.StartIndex, part.PrimitiveCount); Model.DrawCallCounter++; Model.TriangleCounter += part.PrimitiveCount; } } } if (noCullState != null) { this.main.GraphicsDevice.RasterizerState = originalState; } if (parameters.IsMainRender) { this.lastTransform = transform; this.lastWorldViewProjection = transform * parameters.Camera.ViewProjection; } } } }
protected override void drawInstances(RenderParameters parameters, Matrix transform) { if (parameters.IsMainRender) { foreach (IPropertyBinding binding in this.modifiedParameters) { binding.OnChanged(null); } this.modifiedParameters.Clear(); for (int i = 0; i < this.instances.Length; i++) { this.instances.Changed(i, this.instances[i]); } } base.drawInstances(parameters, transform); }
/// <summary> /// Draws the full screen quad /// </summary> /// <param name="graphicsDevice">The GraphicsDevice to use for rendering</param> public virtual void DrawAlpha(GameTime time, RenderParameters p) { // Set the vertex buffer and declaration if (this.vertexBuffer.IsDisposed) { this.LoadContent(true); } else { this.main.GraphicsDevice.SetVertexBuffer(this.vertexBuffer); // Draw primitives this.main.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); Model.DrawCallCounter++; Model.TriangleCounter += 2; } }
void IDrawableAlphaComponent.DrawAlpha(Microsoft.Xna.Framework.GameTime time, RenderParameters p) { if (this.Lines.Count == 0 || LineDrawer.unsupportedTechniques.Contains(p.Technique)) return; if (this.vertexBuffer == null || this.vertexBuffer.IsContentLost || this.Lines.Count * 2 > this.vertexBuffer.VertexCount || this.changed) { this.changed = false; if (this.vertexBuffer != null) this.vertexBuffer.Dispose(); this.vertexBuffer = new DynamicVertexBuffer(this.main.GraphicsDevice, VertexPositionColor.VertexDeclaration, (this.Lines.Count * 2) + 8, BufferUsage.WriteOnly); VertexPositionColor[] data = new VertexPositionColor[this.vertexBuffer.VertexCount]; int i = 0; foreach (Line line in this.Lines) { data[i] = line.A; data[i + 1] = line.B; i += 2; } this.vertexBuffer.SetData<VertexPositionColor>(data, 0, this.Lines.Count * 2, SetDataOptions.Discard); } p.Camera.SetParameters(this.effect); this.effect.Parameters["Depth" + Model.SamplerPostfix].SetValue(p.DepthBuffer); // Draw lines try { this.effect.CurrentTechnique = this.effect.Techniques[p.Technique.ToString()]; } catch (Exception) { LineDrawer.unsupportedTechniques.Add(p.Technique); return; } this.effect.CurrentTechnique.Passes[0].Apply(); this.main.GraphicsDevice.SetVertexBuffer(this.vertexBuffer); this.main.GraphicsDevice.DrawPrimitives(PrimitiveType.LineList, 0, this.Lines.Count); }
void IDrawableAlphaComponent.DrawAlpha(Microsoft.Xna.Framework.GameTime time, RenderParameters p) { if (!p.IsMainRender) return; RasterizerState originalState = this.main.GraphicsDevice.RasterizerState; this.main.GraphicsDevice.RasterizerState = new RasterizerState { CullMode = CullMode.None }; float oldFarPlane = p.Camera.FarPlaneDistance; p.Camera.FarPlaneDistance.Value = 1000.0f; p.Camera.SetParameters(this.effect); this.effect.Parameters["ActualFarPlaneDistance"].SetValue(oldFarPlane); this.effect.Parameters["Reflection" + Model.SamplerPostfix].SetValue(this.buffer); this.effect.Parameters["Position"].SetValue(this.Position); this.effect.Parameters["Time"].SetValue(this.main.TotalTime); this.effect.Parameters["Depth" + Model.SamplerPostfix].SetValue(p.DepthBuffer); this.effect.Parameters["Frame" + Model.SamplerPostfix].SetValue(p.FrameBuffer); bool underwater = p.Camera.Position.Value.Y < this.Position.Value.Y; // Draw surface this.effect.CurrentTechnique = this.effect.Techniques[underwater || !this.EnableReflection ? "Surface" : "SurfaceReflection"]; this.effect.CurrentTechnique.Passes[0].Apply(); this.main.GraphicsDevice.SetVertexBuffer(this.surfaceVertexBuffer); this.main.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); this.main.GraphicsDevice.RasterizerState = originalState; p.Camera.FarPlaneDistance.Value = oldFarPlane; if (underwater) { // Draw underwater stuff this.effect.CurrentTechnique = this.effect.Techniques["Underwater"]; this.effect.CurrentTechnique.Passes[0].Apply(); this.main.GraphicsDevice.SetVertexBuffer(this.underwaterVertexBuffer); this.main.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); } }
public void SetRenderTargets(RenderParameters p) { if (this.needBufferReallocation()) { this.ReallocateBuffers(this.screenSize); } p.Camera.ViewportSize.Value = this.screenSize; this.main.GraphicsDevice.SetRenderTargets(this.colorBuffer1, this.depthBuffer, this.normalBuffer); p.Camera.SetParameters(this.clearEffect); this.destinations1[0] = this.colorBuffer1; this.setTargetParameters(this.sources0, this.destinations1, this.clearEffect); Color color = this.lightingManager.BackgroundColor; this.clearEffect.Parameters["BackgroundColor"].SetValue(new Vector3((float)color.R / 255.0f, (float)color.G / 255.0f, (float)color.B / 255.0f)); this.main.GraphicsDevice.SamplerStates[1] = SamplerState.PointClamp; this.main.GraphicsDevice.SamplerStates[2] = SamplerState.PointClamp; this.main.GraphicsDevice.SamplerStates[3] = SamplerState.PointClamp; this.main.GraphicsDevice.SamplerStates[4] = SamplerState.PointClamp; this.applyEffect(this.clearEffect); Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); }
protected override void LoadContent() { this.MapContent = new ContentManager(this.Services); this.MapContent.RootDirectory = this.Content.RootDirectory; GeeUIMain.Font = this.Content.Load<SpriteFont>(this.Font); if (this.firstLoadContentCall) { this.firstLoadContentCall = false; if (!Directory.Exists(this.MapDirectory)) Directory.CreateDirectory(this.MapDirectory); string challengeDirectory = Path.Combine(this.MapDirectory, "Challenge"); if (!Directory.Exists(challengeDirectory)) Directory.CreateDirectory(challengeDirectory); #if VR if (this.VR) { this.vrLeftMesh.Load(this, Ovr.Eye.Left, this.vrLeftFov); this.vrRightMesh.Load(this, Ovr.Eye.Right, this.vrRightFov); new CommandBinding(this.ReloadedContent, (Action)this.vrLeftMesh.Reload); new CommandBinding(this.ReloadedContent, (Action)this.vrRightMesh.Reload); this.reallocateVrTargets(); this.vrCamera = new Camera(); this.AddComponent(this.vrCamera); } #endif this.GraphicsDevice.PresentationParameters.PresentationInterval = PresentInterval.Immediate; this.GeeUI = new GeeUIMain(); this.AddComponent(GeeUI); this.ConsoleUI = new ConsoleUI(); this.AddComponent(ConsoleUI); this.Console = new Console.Console(); this.AddComponent(Console); Lemma.Console.Console.BindType(null, this); Lemma.Console.Console.BindType(null, Console); // Initialize Wwise AkGlobalSoundEngineInitializer initializer = new AkGlobalSoundEngineInitializer(Path.Combine(this.Content.RootDirectory, "Wwise")); this.AddComponent(initializer); this.Listener = new AkListener(); this.Listener.Add(new Binding<Vector3>(this.Listener.Position, this.Camera.Position)); this.Listener.Add(new Binding<Vector3>(this.Listener.Forward, this.Camera.Forward)); this.Listener.Add(new Binding<Vector3>(this.Listener.Up, this.Camera.Up)); this.AddComponent(this.Listener); // Create the renderer. this.LightingManager = new LightingManager(); this.AddComponent(this.LightingManager); this.Renderer = new Renderer(this, true, true, true, true, true); this.AddComponent(this.Renderer); this.Renderer.ReallocateBuffers(this.ScreenSize); this.renderParameters = new RenderParameters { Camera = this.Camera, IsMainRender = true }; // Load strings this.Strings.Load(Path.Combine(this.Content.RootDirectory, "Strings.xlsx")); this.UI = new UIRenderer(); this.UI.GeeUI = this.GeeUI; this.AddComponent(this.UI); PCInput input = new PCInput(); this.AddComponent(input); Lemma.Console.Console.BindType(null, input); Lemma.Console.Console.BindType(null, UI); Lemma.Console.Console.BindType(null, Renderer); Lemma.Console.Console.BindType(null, LightingManager); input.Add(new CommandBinding(input.GetChord(new PCInput.Chord { Modifier = Keys.LeftAlt, Key = Keys.S }), delegate() { // High-resolution screenshot bool originalModelsVisible = Editor.EditorModelsVisible; Editor.EditorModelsVisible.Value = false; Screenshot s = new Screenshot(); this.AddComponent(s); s.Take(new Point(4096, 2304), delegate() { string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string path; int i = 0; do { path = Path.Combine(desktop, string.Format("lemma-screen{0}.png", i)); i++; } while (File.Exists(path)); Screenshot.SavePng(s.Buffer, path); Editor.EditorModelsVisible.Value = originalModelsVisible; s.Delete.Execute(); }); })); this.performanceMonitor = new ListContainer(); this.performanceMonitor.Add(new Binding<Vector2, Point>(performanceMonitor.Position, x => new Vector2(x.X, 0), this.ScreenSize)); this.performanceMonitor.AnchorPoint.Value = new Vector2(1, 0); this.performanceMonitor.Visible.Value = false; this.performanceMonitor.Name.Value = "PerformanceMonitor"; this.UI.Root.Children.Add(this.performanceMonitor); Action<string, Property<double>> addTimer = delegate(string label, Property<double> property) { TextElement text = new TextElement(); text.FontFile.Value = this.Font; text.Add(new Binding<string, double>(text.Text, x => label + ": " + (x * 1000.0).ToString("F") + "ms", property)); this.performanceMonitor.Children.Add(text); }; Action<string, Property<int>> addCounter = delegate(string label, Property<int> property) { TextElement text = new TextElement(); text.FontFile.Value = this.Font; text.Add(new Binding<string, int>(text.Text, x => label + ": " + x.ToString(), property)); this.performanceMonitor.Children.Add(text); }; TextElement frameRateText = new TextElement(); frameRateText.FontFile.Value = this.Font; frameRateText.Add(new Binding<string, float>(frameRateText.Text, x => "FPS: " + x.ToString("0"), this.frameRate)); this.performanceMonitor.Children.Add(frameRateText); addTimer("Physics", this.physicsTime); addTimer("Update", this.updateTime); addTimer("Render", this.renderTime); addCounter("Draw calls", this.drawCalls); addCounter("Triangles", this.triangles); addCounter("Working set", this.workingSet); Lemma.Console.Console.AddConCommand(new ConCommand("perf", "Toggle the performance monitor", delegate(ConCommand.ArgCollection args) { this.performanceMonitor.Visible.Value = !this.performanceMonitor.Visible; })); try { IEnumerable<string> globalStaticScripts = Directory.GetFiles(Path.Combine(this.Content.RootDirectory, "GlobalStaticScripts"), "*", SearchOption.AllDirectories).Select(x => Path.Combine("..\\GlobalStaticScripts", Path.GetFileNameWithoutExtension(x))); foreach (string scriptName in globalStaticScripts) this.executeStaticScript(scriptName); } catch (IOException) { } this.UIFactory = new UIFactory(); this.AddComponent(this.UIFactory); this.AddComponent(this.Menu); // Have to do this here so the menu's Awake can use all our loaded stuff this.Spawner = new Spawner(); this.AddComponent(this.Spawner); this.UI.IsMouseVisible.Value = true; AKRESULT akresult = AkBankLoader.LoadBank("SFX_Bank_01.bnk"); if (akresult != AKRESULT.AK_Success) Log.d(string.Format("Failed to load main sound bank: {0}", akresult)); #if ANALYTICS this.SessionRecorder = new Session.Recorder(this); this.SessionRecorder.Add("Position", delegate() { Entity p = PlayerFactory.Instance; if (p != null && p.Active) return p.Get<Transform>().Position; else return Vector3.Zero; }); this.SessionRecorder.Add("Health", delegate() { Entity p = PlayerFactory.Instance; if (p != null && p.Active) return p.Get<Player>().Health; else return 0.0f; }); this.SessionRecorder.Add("Framerate", delegate() { return this.frameRate; }); this.SessionRecorder.Add("WorkingSet", delegate() { return this.workingSet; }); this.AddComponent(this.SessionRecorder); this.SessionRecorder.Add(new Binding<bool, Config.RecordAnalytics>(this.SessionRecorder.EnableUpload, x => x == Config.RecordAnalytics.On, this.Settings.Analytics)); #endif this.DefaultLighting(); new SetBinding<float>(this.Settings.SoundEffectVolume, delegate(float value) { AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.VOLUME_SFX, MathHelper.Clamp(value, 0.0f, 1.0f)); }); new SetBinding<float>(this.Settings.MusicVolume, delegate(float value) { AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.VOLUME_MUSIC, MathHelper.Clamp(value, 0.0f, 1.0f)); }); new TwoWayBinding<LightingManager.DynamicShadowSetting>(this.Settings.DynamicShadows, this.LightingManager.DynamicShadows); new TwoWayBinding<float>(this.Settings.MotionBlurAmount, this.Renderer.MotionBlurAmount); new TwoWayBinding<float>(this.Settings.Gamma, this.Renderer.Gamma); new TwoWayBinding<bool>(this.Settings.Bloom, this.Renderer.EnableBloom); new TwoWayBinding<bool>(this.Settings.SSAO, this.Renderer.EnableSSAO); new Binding<float>(this.Camera.FieldOfView, this.Settings.FieldOfView); foreach (string file in Directory.GetFiles(this.MapDirectory, "*.xlsx", SearchOption.TopDirectoryOnly)) this.Strings.Load(file); new Binding<string, Config.Lang>(this.Strings.Language, x => x.ToString(), this.Settings.Language); new NotifyBinding(this.SaveSettings, this.Settings.Language); new CommandBinding(this.MapLoaded, delegate() { this.Renderer.BlurAmount.Value = 0.0f; this.Renderer.Tint.Value = new Vector3(1.0f); }); #if VR if (this.VR) { Action loadVrEffect = delegate() { this.vrEffect = this.Content.Load<Effect>("Effects\\Oculus"); }; loadVrEffect(); new CommandBinding(this.ReloadedContent, loadVrEffect); this.UI.Add(new Binding<Point>(this.UI.RenderTargetSize, this.ScreenSize)); this.VRUI = new Lemma.Components.ModelNonPostProcessed(); this.VRUI.MapContent = false; this.VRUI.DrawOrder.Value = 100000; // On top of everything this.VRUI.Filename.Value = "Models\\plane"; this.VRUI.EffectFile.Value = "Effects\\VirtualUI"; this.VRUI.Add(new Binding<Microsoft.Xna.Framework.Graphics.RenderTarget2D>(this.VRUI.GetRenderTarget2DParameter("Diffuse" + Lemma.Components.Model.SamplerPostfix), this.UI.RenderTarget)); this.VRUI.Add(new Binding<Matrix>(this.VRUI.Transform, delegate() { Matrix rot = this.Camera.RotationMatrix; Matrix mat = Matrix.Identity; mat.Forward = rot.Right; mat.Right = rot.Forward; mat.Up = rot.Up; mat *= Matrix.CreateScale(7); mat.Translation = this.Camera.Position + rot.Forward * 4.0f; return mat; }, this.Camera.Position, this.Camera.RotationMatrix)); this.AddComponent(this.VRUI); this.UI.Setup3D(this.VRUI.Transform); } #endif #if ANALYTICS bool editorLastEnabled = this.EditorEnabled; new CommandBinding<string>(this.LoadingMap, delegate(string newMap) { if (this.MapFile.Value != null && !editorLastEnabled) { this.SessionRecorder.RecordEvent("ChangedMap", newMap); if (!this.IsChallengeMap(this.MapFile) && this.MapFile.Value != Main.MenuMap) this.SaveAnalytics(); } this.SessionRecorder.Reset(); editorLastEnabled = this.EditorEnabled; }); #endif new CommandBinding<string>(this.LoadingMap, delegate(string newMap) { this.CancelScheduledSave(); }); #if !DEVELOPMENT IO.MapLoader.Load(this, MenuMap); this.Menu.Show(initial: true); #endif #if ANALYTICS if (this.Settings.Analytics.Value == Config.RecordAnalytics.Ask) { this.Menu.ShowDialog("\\analytics prompt", "\\enable analytics", delegate() { this.Settings.Analytics.Value = Config.RecordAnalytics.On; }, "\\disable analytics", delegate() { this.Settings.Analytics.Value = Config.RecordAnalytics.Off; }); } #endif #if VR if (this.oculusNotFound) this.Menu.HideMessage(null, this.Menu.ShowMessage(null, "Error: no Oculus found."), 6.0f); if (this.VR) { this.Menu.EnableInput(false); Container vrMsg = this.Menu.BuildMessage("\\vr message", 300.0f); vrMsg.AnchorPoint.Value = new Vector2(0.5f, 0.5f); vrMsg.Add(new Binding<Vector2, Point>(vrMsg.Position, x => new Vector2(x.X * 0.5f, x.Y * 0.5f), this.ScreenSize)); this.UI.Root.Children.Add(vrMsg); input.Bind(this.Settings.RecenterVRPose, PCInput.InputState.Down, this.VRHmd.RecenterPose); input.Bind(this.Settings.RecenterVRPose, PCInput.InputState.Down, delegate() { if (vrMsg != null) { vrMsg.Delete.Execute(); vrMsg = null; } this.Menu.EnableInput(true); }); } else #endif { input.Bind(this.Settings.ToggleFullscreen, PCInput.InputState.Down, delegate() { if (this.Settings.Fullscreen) // Already fullscreen. Go to windowed mode. this.ExitFullscreen(); else // In windowed mode. Go to fullscreen. this.EnterFullscreen(); }); } input.Bind(this.Settings.QuickSave, PCInput.InputState.Down, delegate() { this.SaveWithNotification(true); }); } else { this.ReloadingContent.Execute(); foreach (IGraphicsComponent c in this.graphicsComponents) c.LoadContent(true); this.ReloadedContent.Execute(); } this.GraphicsDevice.RasterizerState = new RasterizerState { MultiSampleAntiAlias = false }; if (this.spriteBatch != null) this.spriteBatch.Dispose(); this.spriteBatch = new SpriteBatch(this.GraphicsDevice); }
public void DrawScene(RenderParameters parameters) { if (parameters.Technique != Technique.Shadow) this.LightingManager.ClearMaterials(); RasterizerState originalState = this.GraphicsDevice.RasterizerState; RasterizerState reverseCullState = null; if (parameters.ReverseCullOrder) { reverseCullState = new RasterizerState { CullMode = CullMode.CullClockwiseFace }; this.GraphicsDevice.RasterizerState = reverseCullState; } Vector3 cameraPos = parameters.Camera.Position; BoundingFrustum frustum = parameters.Camera.BoundingFrustum; for (int i = 0; i < this.drawables.Count; i++) { IDrawableComponent c = this.drawables[i]; if (this.componentEnabled(c) && c.IsVisible(frustum)) c.Draw(this.GameTime, parameters); } if (reverseCullState != null) this.GraphicsDevice.RasterizerState = originalState; if (parameters.Technique != Technique.Shadow) this.LightingManager.SetMaterials(parameters); }
protected override void drawInstances(RenderParameters parameters, Matrix transform) { // Animated instancing not supported }
protected override void drawInstances(RenderParameters parameters, Matrix transform) { // Animated instancing not supported }
/// <summary> /// Draws the particle system if it is an opaque particle system. /// </summary> void IDrawableComponent.Draw(GameTime gameTime, RenderParameters parameters) { if (this.settings.BlendState == BlendState.Opaque) this.draw(parameters); }
protected void draw(RenderParameters parameters) { if (this.settings.UnsupportedTechniques.Contains(parameters.Technique)) return; GraphicsDevice device = this.main.GraphicsDevice; // Restore the vertex buffer contents if the graphics device was lost. if (this.vertexBuffer.IsContentLost) this.vertexBuffer.SetData(particles); // If there are any particles waiting in the newly added queue, // we'd better upload them to the GPU ready for drawing. if (this.firstNewParticle != this.firstFreeParticle) this.addNewParticlesToVertexBuffer(); // If there are any active particles, draw them now! if (this.firstActiveParticle != this.firstFreeParticle) { string techniqueName; if (settings.BlendState == BlendState.Additive) techniqueName = "AdditiveParticles"; else if (settings.BlendState == BlendState.Opaque) { techniqueName = "OpaqueParticles"; this.main.LightingManager.SetRenderParameters(this.particleEffect, parameters); } else techniqueName = "AlphaParticles"; if (parameters.Technique == Technique.Clip) this.particleEffect.Parameters["ClipPlanes"].SetValue(parameters.ClipPlaneData); techniqueName = parameters.Technique.ToString() + techniqueName; EffectTechnique techniqueInstance = this.particleEffect.Techniques[techniqueName]; if (techniqueInstance == null) { this.settings.UnsupportedTechniques.Add(parameters.Technique); return; } else this.particleEffect.CurrentTechnique = techniqueInstance; device.DepthStencilState = DepthStencilState.DepthRead; // Set an effect parameter describing the viewport size. This is // needed to convert particle sizes into screen space point sizes. if (this.effectViewportScaleParameter != null) this.effectViewportScaleParameter.SetValue(new Vector2(0.5f / device.Viewport.AspectRatio, -0.5f)); // Set an effect parameter describing the current time. All the vertex // shader particle animation is keyed off this value. this.effectTimeParameter.SetValue(this.currentTime); // Update view/projection matrix if (this.effectViewParameter != null) this.effectViewParameter.SetValue(parameters.Camera.View); if (this.effectInverseViewParameter != null) this.effectInverseViewParameter.SetValue(parameters.Camera.InverseView); if (this.effectCameraPositionParameter != null) this.effectCameraPositionParameter.SetValue(parameters.Camera.Position); if (this.effectProjectionParameter != null) this.effectProjectionParameter.SetValue(parameters.Camera.Projection); if (this.effectDepthBufferParameter != null) this.effectDepthBufferParameter.SetValue(parameters.DepthBuffer); if (this.effectFrameBufferParameter != null) this.effectFrameBufferParameter.SetValue(parameters.FrameBuffer); // Set the particle vertex and index buffer. device.SetVertexBuffer(this.vertexBuffer); device.Indices = this.indexBuffer; RasterizerState originalState = this.main.GraphicsDevice.RasterizerState; this.main.GraphicsDevice.RasterizerState = this.noCullRasterizerState; // Activate the particle effect. foreach (EffectPass pass in this.particleEffect.CurrentTechnique.Passes) { pass.Apply(); if (this.firstActiveParticle < this.firstFreeParticle) { // If the active particles are all in one consecutive range, // we can draw them all in a single call. device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, this.firstActiveParticle * 4, (this.firstFreeParticle - this.firstActiveParticle) * 4, this.firstActiveParticle * 6, (this.firstFreeParticle - this.firstActiveParticle) * 2); } else { // If the active particle range wraps past the end of the queue // back to the start, we must split them over two draw calls. device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, this.firstActiveParticle * 4, (this.settings.MaxParticles - this.firstActiveParticle) * 4, this.firstActiveParticle * 6, (this.settings.MaxParticles - this.firstActiveParticle) * 2); if (this.firstFreeParticle > 0) { device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, this.firstFreeParticle * 4, 0, this.firstFreeParticle * 2); } } } this.main.GraphicsDevice.RasterizerState = originalState; // Reset some of the renderstates that we changed, // so as not to mess up any other subsequent drawing. device.DepthStencilState = DepthStencilState.Default; } this.drawCounter++; }
protected override bool setParameters(Matrix transform, RenderParameters parameters) { bool result = base.setParameters(transform, parameters); if (result) this.effect.Parameters["Depth" + Model.SamplerPostfix].SetValue(parameters.DepthBuffer); return result; }
protected virtual bool setParameters(Matrix transform, RenderParameters parameters) { if (this.UnsupportedTechniques.Contains(parameters.Technique)) return false; EffectTechnique technique = this.effect.Techniques[parameters.Technique.ToString() + this.TechniquePostfix]; if (technique == null) { this.UnsupportedTechniques.Add(parameters.Technique); return false; } else this.effect.CurrentTechnique = technique; if (parameters.Technique == Technique.Clip) this.effect.Parameters["ClipPlanes"].SetValue(parameters.ClipPlaneData); EffectParameter parameter = this.effect.Parameters["LastFrameWorldMatrix"]; if (parameter != null) parameter.SetValue(this.lastTransform); parameter = this.effect.Parameters["LastFrameWorldViewProjectionMatrix"]; if (parameter != null) parameter.SetValue(this.lastWorldViewProjection); parameter = this.effect.Parameters["WorldMatrix"]; if (parameter != null) parameter.SetValue(transform); parameter = this.effect.Parameters["Time"]; if (parameter != null) parameter.SetValue(this.main.TotalTime); parameters.Camera.SetParameters(this.effect); return true; }
public void PostProcess(RenderTarget2D result, RenderParameters parameters) { if (this.needBufferReallocation()) { return; } Vector3 originalCameraPosition = parameters.Camera.Position; Matrix originalViewMatrix = parameters.Camera.View; BoundingFrustum originalBoundingFrustum = parameters.Camera.BoundingFrustum; parameters.Camera.Position.Value = Vector3.Zero; Matrix newViewMatrix = originalViewMatrix; newViewMatrix.Translation = Vector3.Zero; parameters.Camera.View.Value = newViewMatrix; RasterizerState originalState = this.main.GraphicsDevice.RasterizerState; bool enableSSAO = this.allowSSAO && this.EnableSSAO; if (enableSSAO) { // Down-sample depth buffer this.downsampleEffect.CurrentTechnique = this.downsampleEffect.Techniques["DownsampleDepth"]; this.sources2[0] = this.depthBuffer; this.sources2[1] = this.normalBuffer; this.destinations2[0] = this.halfDepthBuffer; this.destinations2[1] = this.halfBuffer1; if (!this.preparePostProcess(this.sources2, this.destinations2, this.downsampleEffect)) { return; } Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); // Compute SSAO parameters.Camera.SetParameters(this.ssaoEffect); this.ssaoEffect.CurrentTechnique = this.ssaoEffect.Techniques["SSAO"]; this.sources2[0] = this.halfDepthBuffer; this.sources2[1] = this.halfBuffer1; this.destinations1[0] = this.halfBuffer2; if (!this.preparePostProcess(this.sources2, this.destinations1, this.ssaoEffect)) { return; } Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); // Blur this.ssaoEffect.CurrentTechnique = this.ssaoEffect.Techniques["BlurHorizontal"]; this.sources2[0] = this.halfBuffer2; this.sources2[1] = this.halfDepthBuffer; this.destinations1[0] = this.halfBuffer1; if (!this.preparePostProcess(this.sources2, this.destinations1, this.ssaoEffect)) { return; } Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); this.ssaoEffect.CurrentTechnique = this.ssaoEffect.Techniques["Composite"]; this.sources2[0] = this.halfBuffer1; this.sources2[1] = this.halfDepthBuffer; this.destinations1[0] = this.halfBuffer2; if (!this.preparePostProcess(this.sources2, this.destinations1, this.ssaoEffect)) { return; } Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); } // Global lighting this.destinations2[0] = this.lightingBuffer; this.destinations2[1] = this.specularBuffer; if (!this.setTargets(this.destinations2)) { return; } string globalLightTechnique = "GlobalLight"; if (this.lightingManager.EnableGlobalShadowMap && this.lightingManager.HasGlobalShadowLight) { if (parameters.IsMainRender) { if (this.lightingManager.HasGlobalShadowLightClouds) { if (this.lightingManager.EnableDetailGlobalShadowMap) { globalLightTechnique = "GlobalLightDetailShadowClouds"; } else { globalLightTechnique = "GlobalLightShadowClouds"; } } else { if (this.lightingManager.EnableDetailGlobalShadowMap) { globalLightTechnique = "GlobalLightDetailShadow"; } else { globalLightTechnique = "GlobalLightShadow"; } } } else { globalLightTechnique = "GlobalLightShadow"; } } Renderer.globalLightEffect.CurrentTechnique = Renderer.globalLightEffect.Techniques[globalLightTechnique]; parameters.Camera.SetParameters(Renderer.globalLightEffect); this.lightingManager.SetGlobalLightParameters(Renderer.globalLightEffect, parameters.Camera, originalCameraPosition); Renderer.globalLightEffect.Parameters["Materials"].SetValue(parameters.MaterialData); this.sources3[0] = this.depthBuffer; this.sources3[1] = this.normalBuffer; this.sources3[2] = this.colorBuffer1; this.destinations2[0] = this.lightingBuffer; this.destinations2[1] = this.specularBuffer; this.setTargetParameters(this.sources3, this.destinations2, Renderer.globalLightEffect); this.applyEffect(Renderer.globalLightEffect); Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); // Spot and point lights if (!parameters.ReverseCullOrder) { this.main.GraphicsDevice.RasterizerState = this.reverseCullState; } // HACK // Increase the far plane to prevent clipping back faces of huge lights float originalFarPlane = parameters.Camera.FarPlaneDistance; parameters.Camera.FarPlaneDistance.Value *= 4.0f; parameters.Camera.SetParameters(Renderer.pointLightEffect); parameters.Camera.SetParameters(Renderer.spotLightEffect); parameters.Camera.FarPlaneDistance.Value = originalFarPlane; // Spot lights Renderer.spotLightEffect.Parameters["Materials"].SetValue(parameters.MaterialData); this.setTargetParameters(this.sources3, this.destinations2, Renderer.spotLightEffect); for (int i = 0; i < SpotLight.All.Count; i++) { SpotLight light = SpotLight.All[i]; if (!light.Enabled || light.Suspended || light.Attenuation == 0.0f || light.Color.Value.LengthSquared() == 0.0f || !originalBoundingFrustum.Intersects(light.BoundingFrustum)) { continue; } this.lightingManager.SetSpotLightParameters(light, Renderer.spotLightEffect, originalCameraPosition); this.applyEffect(Renderer.spotLightEffect); this.drawModel(Renderer.spotLightModel); } // Point lights Renderer.pointLightEffect.Parameters["Materials"].SetValue(parameters.MaterialData); this.setTargetParameters(this.sources3, this.destinations2, Renderer.pointLightEffect); for (int i = 0; i < PointLight.All.Count; i++) { PointLight light = PointLight.All[i]; if (!light.Enabled || light.Suspended || light.Attenuation == 0.0f || light.Color.Value.LengthSquared() == 0.0f || !originalBoundingFrustum.Intersects(light.BoundingSphere)) { continue; } this.lightingManager.SetPointLightParameters(light, Renderer.pointLightEffect, originalCameraPosition); this.applyEffect(Renderer.pointLightEffect); this.drawModel(Renderer.pointLightModel); } if (!parameters.ReverseCullOrder) { this.main.GraphicsDevice.RasterizerState = originalState; } RenderTarget2D colorSource = this.colorBuffer1; RenderTarget2D colorDestination = this.hdrBuffer2; RenderTarget2D colorTemp = null; // Compositing this.compositeEffect.CurrentTechnique = this.compositeEffect.Techniques[enableSSAO ? "CompositeSSAO" : "Composite"]; this.lightingManager.SetCompositeParameters(this.compositeEffect); parameters.Camera.SetParameters(this.compositeEffect); this.compositeEffect.Parameters["Materials"].SetValue(parameters.MaterialData); RenderTarget2D[] compositeSources; if (enableSSAO) { compositeSources = this.sources4; compositeSources[3] = this.halfBuffer2; } else { compositeSources = this.sources3; } compositeSources[0] = colorSource; compositeSources[1] = this.lightingBuffer; compositeSources[2] = this.specularBuffer; this.destinations1[0] = colorDestination; if (!this.preparePostProcess(compositeSources, this.destinations1, this.compositeEffect)) { return; } Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); bool enableBloom = this.allowBloom && this.EnableBloom; bool enableMotionBlur = this.MotionBlurAmount > 0.0f; #if VR if (this.main.VR) { enableMotionBlur = false; } #endif bool enableBlur = this.BlurAmount > 0.0f; // Swap the color buffers colorSource = this.hdrBuffer2; colorDestination = enableBloom || this.allowToneMapping || enableBlur || enableMotionBlur ? this.hdrBuffer1 : result; parameters.DepthBuffer = this.depthBuffer; parameters.FrameBuffer = colorSource; // Alpha components // Drawing to the color destination this.destinations1[0] = colorDestination; if (!this.setTargets(this.destinations1)) { return; } // Copy the color source to the destination this.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, SamplerState.PointClamp, DepthStencilState.None, originalState); this.spriteBatch.Draw(colorSource, Vector2.Zero, Color.White); this.spriteBatch.End(); parameters.Camera.Position.Value = originalCameraPosition; parameters.Camera.View.Value = originalViewMatrix; this.main.DrawAlphaComponents(parameters); this.main.DrawPostAlphaComponents(parameters); // Swap the color buffers colorTemp = colorDestination; colorDestination = colorSource; parameters.FrameBuffer = colorSource = colorTemp; // Bloom if (enableBloom) { this.bloomEffect.CurrentTechnique = this.bloomEffect.Techniques["Downsample"]; this.sources1[0] = colorSource; this.destinations1[0] = this.halfBuffer1; if (!this.preparePostProcess(this.sources1, this.destinations1, this.bloomEffect)) { return; } Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); this.bloomEffect.CurrentTechnique = this.bloomEffect.Techniques["BlurHorizontal"]; this.sources1[0] = this.halfBuffer1; this.destinations1[0] = this.halfBuffer2; if (!this.preparePostProcess(this.sources1, this.destinations1, this.bloomEffect)) { return; } Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); this.bloomEffect.CurrentTechnique = this.bloomEffect.Techniques["BlurVertical"]; this.sources1[0] = this.halfBuffer2; this.destinations1[0] = this.halfBuffer1; if (!this.preparePostProcess(this.sources1, this.destinations1, this.bloomEffect)) { return; } Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); this.bloomEffect.CurrentTechnique = this.bloomEffect.Techniques["Composite"]; this.sources2[0] = colorSource; this.sources2[1] = this.halfBuffer1; this.destinations1[0] = enableBlur || enableMotionBlur ? this.colorBuffer2 : result; if (!this.preparePostProcess(this.sources2, this.destinations1, this.bloomEffect)) { return; } Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); // Swap the color buffers colorDestination = this.colorBuffer1; colorSource = this.colorBuffer2; } else if (this.allowToneMapping) { this.bloomEffect.CurrentTechnique = this.bloomEffect.Techniques["ToneMapOnly"]; this.sources1[0] = colorSource; this.destinations1[0] = enableBlur || enableMotionBlur ? this.colorBuffer2 : result; if (!this.preparePostProcess(this.sources1, this.destinations1, this.bloomEffect)) { return; } Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); // Swap the color buffers colorDestination = this.colorBuffer1; colorSource = this.colorBuffer2; } // Motion blur if (enableMotionBlur) { this.motionBlurEffect.CurrentTechnique = this.motionBlurEffect.Techniques["MotionBlur"]; parameters.Camera.SetParameters(this.motionBlurEffect); // If we just reallocated our buffers, don't use the velocity buffer from the last frame because it will be empty this.sources3[0] = colorSource; this.sources3[1] = this.normalBuffer; this.sources3[2] = this.justReallocatedBuffers ? this.normalBuffer : this.normalBufferLastFrame; this.destinations1[0] = enableBlur ? colorDestination : result; if (!this.preparePostProcess(this.sources3, this.destinations1, this.motionBlurEffect)) { return; } Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); // Swap the velocity buffers RenderTarget2D temp = this.normalBufferLastFrame; this.normalBufferLastFrame = this.normalBuffer; this.normalBuffer = temp; // Swap the color buffers colorTemp = colorDestination; colorDestination = colorSource; colorSource = colorTemp; } if (enableBlur) { // Blur this.blurEffect.CurrentTechnique = this.blurEffect.Techniques["BlurHorizontal"]; parameters.Camera.SetParameters(this.blurEffect); this.sources1[0] = colorSource; this.destinations1[0] = colorDestination; if (!this.preparePostProcess(this.sources1, this.destinations1, this.blurEffect)) { return; } Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); this.blurEffect.CurrentTechnique = this.blurEffect.Techniques["Composite"]; // Swap the color buffers colorTemp = colorDestination; colorDestination = colorSource; colorSource = colorTemp; this.sources1[0] = colorSource; this.destinations1[0] = result; if (!this.preparePostProcess(this.sources1, this.destinations1, this.blurEffect)) { return; } Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); } parameters.DepthBuffer = null; parameters.FrameBuffer = null; this.justReallocatedBuffers = false; }
/// <summary> /// Draws a collection of instances. Requires an HLSL effect designed for hardware instancing. /// </summary> /// <param name="device"></param> /// <param name="camera"></param> /// <param name="instances"></param> protected virtual void drawInstances(RenderParameters parameters, Matrix transform) { if (this.Instances.Length == 0) { return; } bool recalculate = this.instanceVertexBuffer == null || this.instanceVertexBuffer.IsContentLost || (parameters.IsMainRender && (this.instancesChanged || this.lastInstancesChanged)); if (recalculate) { // If we have more instances than room in our vertex buffer, grow it to the neccessary size. if (this.instanceVertexBuffer == null || this.instanceVertexBuffer.IsContentLost || this.Instances.Length > this.instanceVertexBuffer.VertexCount) { if (this.instanceVertexBuffer != null) { this.instanceVertexBuffer.Dispose(); } int bufferSize = (int)Math.Pow(2.0, Math.Ceiling(Math.Log(this.Instances.Length, 2.0))); this.instanceVertexBuffer = new DynamicVertexBuffer ( this.main.GraphicsDevice, Model.instanceVertexDeclaration, bufferSize, BufferUsage.WriteOnly ); InstanceVertex[] newData = new InstanceVertex[bufferSize]; if (this.instanceVertexData != null) { Array.Copy(this.instanceVertexData, newData, Math.Min(bufferSize, this.instanceVertexData.Length)); for (int i = this.instanceVertexData.Length; i < this.Instances.Length; i++) { newData[i].LastTransform = this.Instances[i].Transform; } } this.instanceVertexData = newData; } for (int i = 0; i < this.Instances.Length; i++) { this.instanceVertexData[i].LastTransform = this.instanceVertexData[i].Transform; Instance instance = this.Instances[i]; this.instanceVertexData[i].Transform = instance.Transform; this.instanceVertexData[i].Param = instance.Param; } // Transfer the latest instance transform matrices into the instanceVertexBuffer. this.instanceVertexBuffer.SetData <InstanceVertex>(this.instanceVertexData, 0, this.Instances.Length, SetDataOptions.Discard); this.lastInstancesChanged = this.instancesChanged; this.instancesChanged = false; } #if !MONOGAME // TODO: enable hardware instancing for MonoGame // Set up the instance rendering effect. if (this.setParameters(transform, parameters)) { this.main.LightingManager.SetRenderParameters(this.effect, parameters); RasterizerState originalState = this.main.GraphicsDevice.RasterizerState; RasterizerState noCullState = null; if (recalculate && this.DisableCulling) { noCullState = new RasterizerState { CullMode = CullMode.None }; this.main.GraphicsDevice.RasterizerState = noCullState; } for (int i = 0; i < this.model.Meshes.Count; i++) { ModelMesh mesh = this.model.Meshes[i]; for (int j = 0; j < mesh.MeshParts.Count; j++) { ModelMeshPart meshPart = mesh.MeshParts[j]; // Tell the GPU to read from both the model vertex buffer plus our instanceVertexBuffer. // TODO: Monogame support for GraphicsDevice.SetVertexBuffers() this.main.GraphicsDevice.SetVertexBuffers ( new VertexBufferBinding(meshPart.VertexBuffer, meshPart.VertexOffset, 0), new VertexBufferBinding(instanceVertexBuffer, 0, 1) ); this.main.GraphicsDevice.Indices = meshPart.IndexBuffer; // Draw all the instance copies in a single call. this.effect.CurrentTechnique.Passes[0].Apply(); // TODO: Monogame support for GraphicsDevice.DrawInstancedPrimitives() this.main.GraphicsDevice.DrawInstancedPrimitives ( PrimitiveType.TriangleList, 0, 0, meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount, this.Instances.Length ); Model.DrawCallCounter++; Model.TriangleCounter += meshPart.PrimitiveCount * this.Instances.Length; } } if (noCullState != null) { this.main.GraphicsDevice.RasterizerState = originalState; } } #endif if (parameters.IsMainRender) { this.lastTransform = transform; this.lastWorldViewProjection = transform * parameters.Camera.ViewProjection; } }
public override void Draw(GameTime time, RenderParameters parameters) { }
void IDrawableAlphaComponent.DrawAlpha(GameTime time, RenderParameters parameters) { if (this.Alpha > 0.0f) base.Draw(time, parameters); }
protected virtual bool setParameters(Matrix transform, RenderParameters parameters) { if (this.effect == null || this.UnsupportedTechniques.Contains(parameters.Technique)) { return(false); } EffectTechnique technique = this.effect.Techniques[parameters.TechniqueString + this.TechniquePostfix]; if (technique == null) { this.UnsupportedTechniques.Add(parameters.Technique); return(false); } else { this.effect.CurrentTechnique = technique; } if (parameters.Technique == Technique.Clip) { this.effect.Parameters["ClipPlanes"].SetValue(parameters.ClipPlaneData); } EffectParameter parameter = this.effect.Parameters["LastFrameWorldMatrix"]; if (parameter != null) { parameter.SetValue(this.lastTransform); } parameter = this.effect.Parameters["LastFrameWorldViewProjectionMatrix"]; if (parameter != null) { parameter.SetValue(this.lastWorldViewProjection); } parameter = this.effect.Parameters["WorldMatrix"]; if (parameter != null) { parameter.SetValue(transform); } parameter = this.effect.Parameters["WorldViewMatrix"]; if (parameter != null) { parameter.SetValue(transform * parameters.Camera.View); } parameter = this.effect.Parameters["Time"]; if (parameter != null) { parameter.SetValue(this.main.TotalTime); } parameters.Camera.SetParameters(this.effect); if (this.materialIds.Length < this.Materials.Length) { this.materialIds = new int[this.Materials.Length]; } for (int i = 0; i < this.Materials.Length; i++) { this.materialIds[i] = this.main.LightingManager.GetMaterialIndex(this.Materials[i]); } this.effect.Parameters["Materials"].SetValue(this.materialIds); return(true); }
/// <summary> /// Draws a single mesh using the given world matrix. /// </summary> /// <param name="camera"></param> /// <param name="transform"></param> protected override void draw(RenderParameters parameters, Matrix transform) { bool needNewVertexBuffer = this.vertexBuffer == null || this.vertexBuffer.IsContentLost; if (this.vertexCount == 0) { this.verticesChanged = false; this.lockedVertexCount = 0; } else if (needNewVertexBuffer || this.verticesChanged) { bool locked; if (this.Lock == null) { locked = true; } else { locked = Monitor.TryEnter(this.Lock); } if (locked) { if (needNewVertexBuffer || this.vertexBuffer.VertexCount < this.vertexCount) { if (this.vertexBuffer != null && !this.vertexBuffer.IsDisposed) { this.vertexBuffer.Dispose(); } this.vertexBuffer = new DynamicVertexBuffer ( this.main.GraphicsDevice, this.declaration, (int)Math.Pow(DynamicModel <Vertex> .growthFactor, Math.Ceiling(Math.Log(this.vertexCount, DynamicModel <Vertex> .growthFactor))), BufferUsage.WriteOnly ); this.verticesChanged = true; } if (DynamicModel <Vertex> .indexBuffer == null || DynamicModel <Vertex> .indexBuffer.IndexCount < this.indexCount) { if (DynamicModel <Vertex> .indexBuffer != null) { DynamicModel <Vertex> .indexBuffer.Dispose(); } lock (DynamicModel <Vertex> .indicesLock) { uint[] indices = DynamicModel <Vertex> .GetIndices(this.indexCount); DynamicModel <Vertex> .indexBuffer = new IndexBuffer(this.main.GraphicsDevice, typeof(uint), indices.Length, BufferUsage.WriteOnly); DynamicModel <Vertex> .indexBuffer.SetData(indices, 0, indices.Length); } } this.vertexBuffer.SetData(0, this.vertices, 0, this.vertexCount, this.declaration.VertexStride, SetDataOptions.Discard); this.verticesChanged = false; this.lockedVertexCount = this.vertexCount; if (this.Lock != null) { Monitor.Exit(this.Lock); } } } if (this.lockedVertexCount > 0 && this.vertexBuffer != null && !this.vertexBuffer.IsContentLost && this.setParameters(transform, parameters)) { this.main.LightingManager.SetRenderParameters(this.effect, parameters); RasterizerState originalState = this.main.GraphicsDevice.RasterizerState; RasterizerState noCullState = null; if (parameters.IsMainRender && this.DisableCulling) { noCullState = new RasterizerState { CullMode = CullMode.None }; this.main.GraphicsDevice.RasterizerState = noCullState; } this.main.GraphicsDevice.SetVertexBuffer(this.vertexBuffer); this.main.GraphicsDevice.Indices = DynamicModel <Vertex> .indexBuffer; this.effect.CurrentTechnique.Passes[0].Apply(); this.main.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, this.lockedVertexCount, 0, this.lockedVertexCount / 2); Model.DrawCallCounter++; Model.TriangleCounter += this.lockedVertexCount / 2; if (noCullState != null) { this.main.GraphicsDevice.RasterizerState = originalState; } } if (parameters.IsMainRender) { this.lastTransform = transform; this.lastWorldViewProjection = transform * parameters.Camera.ViewProjection; } }
void IDrawableAlphaComponent.DrawAlpha(Microsoft.Xna.Framework.GameTime time, RenderParameters p) { if (!p.IsMainRender || !this.isVisible(p.Camera)) { return; } Vector3 cameraPos = p.Camera.Position; Vector3 pos = this.Position; RasterizerState originalState = this.main.GraphicsDevice.RasterizerState; this.main.GraphicsDevice.RasterizerState = new RasterizerState { CullMode = CullMode.None }; float oldFarPlane = p.Camera.FarPlaneDistance; p.Camera.FarPlaneDistance.Value = 1000.0f; p.Camera.SetParameters(this.effect); this.effect.Parameters["ActualFarPlaneDistance"].SetValue(oldFarPlane); this.effect.Parameters["Reflection" + Model.SamplerPostfix].SetValue(this.buffer); this.effect.Parameters["Time"].SetValue(this.main.TotalTime); this.effect.Parameters["Depth" + Model.SamplerPostfix].SetValue(p.DepthBuffer); this.effect.Parameters["Frame" + Model.SamplerPostfix].SetValue(p.FrameBuffer); // Draw surface this.effect.Parameters["Clearness"].SetValue(this.underwater ? 1.0f : this.Clearness); this.effect.CurrentTechnique = this.effect.Techniques[this.underwater || !this.EnableReflection ? "Surface" : "SurfaceReflection"]; this.effect.CurrentTechnique.Passes[0].Apply(); if (this.surfaceVertexBuffer.IsDisposed) { this.loadEffectAndVertexBuffers(); } this.main.GraphicsDevice.SetVertexBuffer(this.surfaceVertexBuffer); this.main.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); Model.DrawCallCounter++; Model.TriangleCounter += 2; this.main.GraphicsDevice.RasterizerState = originalState; p.Camera.FarPlaneDistance.Value = oldFarPlane; if (this.underwater) { // Draw underwater stuff this.effect.Parameters["Clearness"].SetValue(this.Clearness); this.effect.CurrentTechnique = this.effect.Techniques["Underwater"]; // Ugh p.Camera.Position.Value = Vector3.Zero; p.Camera.SetParameters(this.effect); p.Camera.Position.Value = cameraPos; this.effect.Parameters["CameraPosition"].SetValue(cameraPos); this.effect.CurrentTechnique.Passes[0].Apply(); if (this.surfaceVertexBuffer.IsDisposed) { this.loadEffectAndVertexBuffers(); } this.main.GraphicsDevice.SetVertexBuffer(this.underwaterVertexBuffer); this.main.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); Model.DrawCallCounter++; Model.TriangleCounter += 2; } }
public override void InitializeProperties() { this.EnabledWhenPaused.Value = true; this.Add(new NotifyBinding(delegate() { this.needResize = true; }, this.main.ScreenSize)); this.Add(new Binding<bool>(this.EnableReflection, ((GameMain)this.main).Settings.EnableReflections)); Action removeFluid = delegate() { if (this.fluid.Space != null) this.main.Space.Remove(this.fluid); }; Action addFluid = delegate() { if (this.fluid.Space == null && this.Enabled && !this.Suspended) this.main.Space.Add(this.fluid); }; this.Add(new CommandBinding(this.OnSuspended, removeFluid)); this.Add(new CommandBinding(this.OnDisabled, removeFluid)); this.Add(new CommandBinding(this.OnResumed, addFluid)); this.Add(new CommandBinding(this.OnEnabled, addFluid)); this.DrawOrder = new Property<int> { Editable = false, Value = 10 }; this.camera = new Camera(); this.main.AddComponent(this.camera); this.parameters = new RenderParameters { Camera = this.camera, Technique = Technique.Clip, ReverseCullOrder = true, }; this.Color.Set = delegate(Vector3 value) { this.Color.InternalValue = value; this.effect.Parameters["Color"].SetValue(value); }; this.UnderwaterColor.Set = delegate(Vector3 value) { this.UnderwaterColor.InternalValue = value; this.effect.Parameters["UnderwaterColor"].SetValue(value); }; this.Fresnel.Set = delegate(float value) { this.Fresnel.InternalValue = value; this.effect.Parameters["Fresnel"].SetValue(value); }; this.Speed.Set = delegate(float value) { this.Speed.InternalValue = value; this.effect.Parameters["Speed"].SetValue(value); }; this.RippleDensity.Set = delegate(float value) { this.RippleDensity.InternalValue = value; this.effect.Parameters["RippleDensity"].SetValue(value); }; this.Distortion.Set = delegate(float value) { this.Distortion.InternalValue = value; this.effect.Parameters["Distortion"].SetValue(value); }; this.Brightness.Set = delegate(float value) { this.Brightness.InternalValue = value; this.effect.Parameters["Brightness"].SetValue(value); }; this.Clearness.Set = delegate(float value) { this.Clearness.InternalValue = value; this.effect.Parameters["Clearness"].SetValue(value); }; List<Vector3[]> tris = new List<Vector3[]>(); const float basinWidth = 2500.0f; const float basinLength = 2500.0f; float waterHeight = this.Position.Value.Y; tris.Add(new[] { new Vector3(-basinWidth / 2, waterHeight, -basinLength / 2), new Vector3(basinWidth / 2, waterHeight, -basinLength / 2), new Vector3(-basinWidth / 2, waterHeight, basinLength / 2) }); tris.Add(new[] { new Vector3(-basinWidth / 2, waterHeight, basinLength / 2), new Vector3(basinWidth / 2, waterHeight, -basinLength / 2), new Vector3(basinWidth / 2, waterHeight, basinLength / 2) }); this.fluid = new Util.CustomFluidVolume(Vector3.Up, this.main.Space.ForceUpdater.Gravity.Y, tris, 1000.0f, 1.25f, 0.997f, 0.2f, this.main.Space.BroadPhase.QueryAccelerator, this.main.Space.ThreadManager); this.main.Space.Add(this.fluid); instances.Add(this); }
/// <summary> /// Draws a collection of instances. Requires an HLSL effect designed for hardware instancing. /// </summary> /// <param name="device"></param> /// <param name="camera"></param> /// <param name="instances"></param> protected virtual void drawInstances(RenderParameters parameters, Matrix transform) { if (this.Instances.Count == 0) return; bool recalculate = this.instanceVertexBuffer == null || this.instanceVertexBuffer.IsContentLost || (parameters.IsMainRender && (this.instancesChanged || this.lastInstancesChanged)); if (recalculate) { // If we have more instances than room in our vertex buffer, grow it to the neccessary size. if (this.instanceVertexBuffer == null || this.instanceVertexBuffer.IsContentLost || this.Instances.Count > this.instanceVertexBuffer.VertexCount) { if (this.instanceVertexBuffer != null) this.instanceVertexBuffer.Dispose(); int bufferSize = (int)Math.Pow(2.0, Math.Ceiling(Math.Log(this.Instances.Count, 2.0))); this.instanceVertexBuffer = new DynamicVertexBuffer ( this.main.GraphicsDevice, Model.instanceVertexDeclaration, bufferSize, BufferUsage.WriteOnly ); InstanceVertex[] newData = new InstanceVertex[bufferSize]; if (this.instanceVertexData != null) { Array.Copy(this.instanceVertexData, newData, Math.Min(bufferSize, this.instanceVertexData.Length)); for (int i = this.instanceVertexData.Length; i < this.Instances.Count; i++) newData[i].LastTransform = this.Instances[i]; } this.instanceVertexData = newData; } for (int i = 0; i < this.Instances.Count; i++) { this.instanceVertexData[i].LastTransform = this.instanceVertexData[i].Transform; this.instanceVertexData[i].Transform = this.Instances[i]; this.instanceVertexData[i].InstanceIndex = i; } // Transfer the latest instance transform matrices into the instanceVertexBuffer. this.instanceVertexBuffer.SetData<InstanceVertex>(this.instanceVertexData, 0, this.Instances.Count, SetDataOptions.Discard); this.lastInstancesChanged = this.instancesChanged; this.instancesChanged = false; } #if !MONOGAME // TODO: enable hardware instancing for MonoGame // Set up the instance rendering effect. if (this.setParameters(transform, parameters)) { this.main.LightingManager.SetRenderParameters(this.effect, parameters); RasterizerState originalState = this.main.GraphicsDevice.RasterizerState; RasterizerState noCullState = null; if (recalculate && this.DisableCulling) { noCullState = new RasterizerState { CullMode = CullMode.None }; this.main.GraphicsDevice.RasterizerState = noCullState; } foreach (ModelMesh mesh in this.model.Meshes) { foreach (ModelMeshPart meshPart in mesh.MeshParts) { // Tell the GPU to read from both the model vertex buffer plus our instanceVertexBuffer. // TODO: Monogame support for GraphicsDevice.SetVertexBuffers() this.main.GraphicsDevice.SetVertexBuffers ( new VertexBufferBinding(meshPart.VertexBuffer, meshPart.VertexOffset, 0), new VertexBufferBinding(instanceVertexBuffer, 0, 1) ); this.main.GraphicsDevice.Indices = meshPart.IndexBuffer; // Draw all the instance copies in a single call. foreach (EffectPass pass in this.effect.CurrentTechnique.Passes) { pass.Apply(); // TODO: Monogame support for GraphicsDevice.DrawInstancedPrimitives() this.main.GraphicsDevice.DrawInstancedPrimitives ( PrimitiveType.TriangleList, 0, 0, meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount, this.Instances.Count ); } } } if (noCullState != null) this.main.GraphicsDevice.RasterizerState = originalState; } #endif if (parameters.IsMainRender) { this.lastTransform = transform; this.lastWorldViewProjection = transform * parameters.Camera.ViewProjection; } }
public override void Awake() { base.Awake(); this.Add(new ChangeBinding <string>(this.EnvironmentMap, delegate(string old, string file) { if (old != file) { this.loadEnvironmentMap(file); } })); this.shadowCamera = new Camera(); this.main.AddComponent(this.shadowCamera); this.Add(new SetBinding <DynamicShadowSetting>(this.DynamicShadows, delegate(DynamicShadowSetting value) { this.shadowMapIndices.Clear(); switch (value) { case DynamicShadowSetting.Off: this.EnableGlobalShadowMap = false; this.maxShadowedSpotLights = 0; break; case DynamicShadowSetting.Low: this.EnableGlobalShadowMap = true; this.globalShadowMapSize = 1024; this.detailGlobalShadowMapSize = 512; this.maxShadowedSpotLights = 0; break; case DynamicShadowSetting.Medium: this.EnableGlobalShadowMap = true; this.globalShadowMapSize = 1024; this.detailGlobalShadowMapSize = 1024; this.spotShadowMapSize = 256; this.maxShadowedSpotLights = 1; break; case DynamicShadowSetting.High: this.EnableGlobalShadowMap = true; this.globalShadowMapSize = 1024; this.detailGlobalShadowMapSize = 1024; this.spotShadowMapSize = 512; this.maxShadowedSpotLights = 1; break; case DynamicShadowSetting.Ultra: this.EnableGlobalShadowMap = true; this.globalShadowMapSize = 1024; this.detailGlobalShadowMapSize = 2048; this.spotShadowMapSize = 1024; this.maxShadowedSpotLights = 1; break; } if (this.GlobalShadowMap.Value != null) { this.GlobalShadowMap.Value.Dispose(); foreach (Microsoft.Xna.Framework.Graphics.RenderTarget2D target in this.spotShadowMaps) { target.Dispose(); } this.DetailGlobalShadowMap.Value.Dispose(); } if (this.EnableGlobalShadowMap) { this.GlobalShadowMap.Value = new Microsoft.Xna.Framework.Graphics.RenderTarget2D ( this.main.GraphicsDevice, this.globalShadowMapSize, this.globalShadowMapSize, false, Microsoft.Xna.Framework.Graphics.SurfaceFormat.Single, Microsoft.Xna.Framework.Graphics.DepthFormat.Depth24, 0, Microsoft.Xna.Framework.Graphics.RenderTargetUsage.DiscardContents ); this.DetailGlobalShadowMap.Value = new Microsoft.Xna.Framework.Graphics.RenderTarget2D ( this.main.GraphicsDevice, this.detailGlobalShadowMapSize, this.detailGlobalShadowMapSize, false, Microsoft.Xna.Framework.Graphics.SurfaceFormat.Single, Microsoft.Xna.Framework.Graphics.DepthFormat.Depth24, 0, Microsoft.Xna.Framework.Graphics.RenderTargetUsage.DiscardContents ); } this.spotShadowMaps = new Microsoft.Xna.Framework.Graphics.RenderTarget2D[this.maxShadowedSpotLights]; for (int i = 0; i < this.maxShadowedSpotLights; i++) { this.spotShadowMaps[i] = new Microsoft.Xna.Framework.Graphics.RenderTarget2D(this.main.GraphicsDevice, this.spotShadowMapSize, this.spotShadowMapSize, false, Microsoft.Xna.Framework.Graphics.SurfaceFormat.Single, Microsoft.Xna.Framework.Graphics.DepthFormat.Depth24, 0, Microsoft.Xna.Framework.Graphics.RenderTargetUsage.DiscardContents); } })); this.Add(new CommandBinding(this.main.ReloadedContent, delegate() { this.DynamicShadows.Reset(); this.loadEnvironmentMap(this.EnvironmentMap); })); this.shadowRenderParameters = new RenderParameters { Camera = this.shadowCamera, Technique = Technique.Shadow }; }
public void DrawAlphaComponents(RenderParameters parameters) { foreach (IDrawableAlphaComponent c in this.alphaDrawables) { if (this.componentEnabled(c)) c.DrawAlpha(this.GameTime, parameters); } }
public override void Draw(GameTime time, RenderParameters parameters) { }
public void DrawScene(RenderParameters parameters) { RasterizerState originalState = this.GraphicsDevice.RasterizerState; RasterizerState reverseCullState = null; if (parameters.ReverseCullOrder) { reverseCullState = new RasterizerState { CullMode = CullMode.CullClockwiseFace }; this.GraphicsDevice.RasterizerState = reverseCullState; } foreach (IDrawableComponent c in this.drawables) { if (this.componentEnabled(c)) c.Draw(this.GameTime, parameters); } if (reverseCullState != null) this.GraphicsDevice.RasterizerState = originalState; }
public void DrawScene(RenderParameters parameters) { RasterizerState originalState = this.GraphicsDevice.RasterizerState; RasterizerState reverseCullState = null; if (parameters.ReverseCullOrder) { reverseCullState = new RasterizerState { CullMode = CullMode.CullClockwiseFace }; this.GraphicsDevice.RasterizerState = reverseCullState; } Vector3 cameraPos = parameters.Camera.Position; BoundingFrustum frustum = parameters.Camera.BoundingFrustum; List<IDrawableComponent> drawables = this.drawables.Where(c => this.componentEnabled(c) && c.IsVisible(frustum)).ToList(); drawables.Sort(delegate(IDrawableComponent a, IDrawableComponent b) { return a.GetDistance(cameraPos).CompareTo(b.GetDistance(cameraPos)); }); foreach (IDrawableComponent c in drawables) c.Draw(this.GameTime, parameters); if (reverseCullState != null) this.GraphicsDevice.RasterizerState = originalState; }
protected override void LoadContent() { if (this.firstLoadContentCall) { // First time loading content. Create the renderer. this.LightingManager = new LightingManager(); this.AddComponent(this.LightingManager); this.Renderer = new Renderer(this, this.ScreenSize, true, true, false); this.AddComponent(this.Renderer); this.renderParameters = new RenderParameters { Camera = this.Camera, IsMainRender = true }; this.firstLoadContentCall = false; this.UI = new UIRenderer(); this.AddComponent(this.UI); #if PERFORMANCE_MONITOR ListContainer performanceMonitor = new ListContainer(); performanceMonitor.Add(new Binding<Vector2, Point>(performanceMonitor.Position, x => new Vector2(0, x.Y), this.ScreenSize)); performanceMonitor.AnchorPoint.Value = new Vector2(0, 1); performanceMonitor.Visible.Value = false; performanceMonitor.Name.Value = "PerformanceMonitor"; this.UI.Root.Children.Add(performanceMonitor); Action<string, Property<double>> addLabel = delegate(string label, Property<double> property) { TextElement text = new TextElement(); text.FontFile.Value = "Font"; text.Add(new Binding<string, double>(text.Text, x => label + ": " + (x * 1000.0).ToString("F") + "ms", property)); performanceMonitor.Children.Add(text); }; TextElement frameRateText = new TextElement(); frameRateText.FontFile.Value = "Font"; frameRateText.Add(new Binding<string, float>(frameRateText.Text, x => "FPS: " + x.ToString("0"), this.frameRate)); performanceMonitor.Children.Add(frameRateText); addLabel("Physics", this.physicsTime); addLabel("Update", this.updateTime); addLabel("Pre-frame", this.preframeTime); addLabel("Raw render", this.rawRenderTime); addLabel("Shadow render", this.shadowRenderTime); addLabel("Post-process", this.postProcessTime); PCInput input = new PCInput(); input.Add(new CommandBinding(input.GetChord(new PCInput.Chord { Modifier = Keys.LeftAlt, Key = Keys.P }), delegate() { performanceMonitor.Visible.Value = !performanceMonitor.Visible; })); this.AddComponent(input); #endif IEnumerable<string> globalStaticScripts = Directory.GetFiles(Path.Combine(this.Content.RootDirectory, "Maps", "GlobalStaticScripts"), "*", SearchOption.AllDirectories).Select(x => Path.Combine("Maps", "GlobalStaticScripts", Path.GetFileNameWithoutExtension(x))); foreach (string scriptName in globalStaticScripts) this.executeStaticScript(scriptName); } else { foreach (IComponent c in this.components) c.LoadContent(true); this.ReloadedContent.Execute(); } }
protected override bool setParameters(Matrix transform, RenderParameters parameters) { bool result = base.setParameters(transform, parameters); if (result) this.effect.Parameters["Bones"].SetValue(this.skinTransforms); return result; }
public void PostProcess(RenderTarget2D result, RenderParameters parameters, DrawStageDelegate alphaStageDelegate) { RasterizerState originalState = this.main.GraphicsDevice.RasterizerState; RasterizerState reverseCullState = new RasterizerState { CullMode = CullMode.CullClockwiseFace }; bool enableSSAO = this.allowSSAO && this.EnableSSAO; if (enableSSAO) { // Down-sample depth buffer this.preparePostProcess(new[] { this.depthBuffer }, new[] { this.halfDepthBuffer }, this.depthDownsampleEffect); Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); } // Global lighting this.setTargets(this.lightingBuffer, this.specularBuffer); Renderer.globalLightEffect.CurrentTechnique = Renderer.globalLightEffect.Techniques["GlobalLight" + (this.lightingManager.EnableGlobalShadowMap && this.lightingManager.HasGlobalShadowLight ? "Shadow" : "")]; parameters.Camera.SetParameters(Renderer.globalLightEffect); this.lightingManager.SetGlobalLightParameters(Renderer.globalLightEffect); this.setTargetParameters(new RenderTarget2D[] { this.depthBuffer, this.normalBuffer, this.colorBuffer1 }, new RenderTarget2D[] { this.lightingBuffer, this.specularBuffer }, Renderer.globalLightEffect); this.applyEffect(Renderer.globalLightEffect); Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); // Point lights if (!parameters.ReverseCullOrder) this.main.GraphicsDevice.RasterizerState = reverseCullState; parameters.Camera.FarPlaneDistance.Value *= 1.5f; parameters.Camera.SetParameters(Renderer.pointLightEffect); parameters.Camera.FarPlaneDistance.Value /= 1.5f; this.setTargetParameters(new RenderTarget2D[] { this.depthBuffer, this.normalBuffer, this.colorBuffer1 }, new RenderTarget2D[] { this.lightingBuffer, this.specularBuffer }, Renderer.pointLightEffect); foreach (PointLight light in PointLight.All) { if (!light.Enabled || light.Suspended || light.Attenuation == 0.0f || !parameters.Camera.BoundingFrustum.Value.Intersects(light.BoundingSphere)) continue; this.lightingManager.SetPointLightParameters(light, Renderer.pointLightEffect); this.applyEffect(Renderer.pointLightEffect); this.drawModel(Renderer.pointLightModel); } // Spot lights // HACK parameters.Camera.FarPlaneDistance.Value *= 1.5f; parameters.Camera.SetParameters(Renderer.spotLightEffect); parameters.Camera.FarPlaneDistance.Value /= 1.5f; this.setTargetParameters(new RenderTarget2D[] { this.depthBuffer, this.normalBuffer, this.colorBuffer1 }, new RenderTarget2D[] { this.lightingBuffer, this.specularBuffer }, Renderer.spotLightEffect); foreach (SpotLight light in SpotLight.All) { if (!light.Enabled || light.Suspended || light.Attenuation == 0.0f || !parameters.Camera.BoundingFrustum.Value.Intersects(light.BoundingFrustum)) continue; this.lightingManager.SetSpotLightParameters(light, Renderer.spotLightEffect); this.applyEffect(Renderer.spotLightEffect); this.drawModel(Renderer.spotLightModel); } if (!parameters.ReverseCullOrder) this.main.GraphicsDevice.RasterizerState = originalState; // SSAO if (enableSSAO) { // Compute SSAO parameters.Camera.SetParameters(this.ssaoEffect); this.preparePostProcess(new[] { this.halfDepthBuffer, this.normalBuffer }, new[] { this.halfBuffer1 }, this.ssaoEffect); this.main.GraphicsDevice.Clear(Color.Black); Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); // Blur /*this.blurEffect.CurrentTechnique = this.blurEffect.Techniques["BlurHorizontal"]; parameters.Camera.SetParameters(this.blurEffect); this.preparePostProcess(new RenderTarget2D[] { this.halfBuffer1 }, new RenderTarget2D[] { this.halfBuffer2 }, this.blurEffect); Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); this.blurEffect.CurrentTechnique = this.blurEffect.Techniques["Composite"]; this.preparePostProcess(new RenderTarget2D[] { this.halfBuffer2 }, new RenderTarget2D[] { this.halfBuffer1 }, this.blurEffect); Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default);*/ } RenderTarget2D colorSource = this.colorBuffer1; RenderTarget2D colorDestination = this.colorBuffer2; RenderTarget2D colorTemp = null; // Compositing this.compositeEffect.CurrentTechnique = this.compositeEffect.Techniques["Composite" + (enableSSAO ? "SSAO" : "")]; parameters.Camera.SetParameters(this.compositeEffect); this.preparePostProcess ( enableSSAO ? new RenderTarget2D[] { colorSource, this.lightingBuffer, this.specularBuffer, this.halfBuffer1 } : new RenderTarget2D[] { colorSource, this.lightingBuffer, this.specularBuffer }, new RenderTarget2D[] { colorDestination }, this.compositeEffect ); Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); // Swap the color buffers colorTemp = colorDestination; colorDestination = colorSource; colorSource = colorTemp; parameters.DepthBuffer = this.depthBuffer; parameters.FrameBuffer = colorSource; // Alpha components // Drawing to the color destination this.setTargets(colorDestination); // Copy the color source to the destination this.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied); this.spriteBatch.Draw(colorSource, Vector2.Zero, Color.White); this.spriteBatch.End(); if (alphaStageDelegate != null) alphaStageDelegate(parameters); // Swap the color buffers colorTemp = colorDestination; colorDestination = colorSource; colorSource = colorTemp; // Motion blur if (this.allowMotionBlur && this.MotionBlurAmount > 0.0f) { this.motionBlurEffect.CurrentTechnique = this.motionBlurEffect.Techniques["MotionBlur"]; parameters.Camera.SetParameters(this.motionBlurEffect); this.preparePostProcess(new RenderTarget2D[] { colorSource, this.velocityBuffer, this.velocityBufferLastFrame }, new RenderTarget2D[] { colorDestination }, this.motionBlurEffect); Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); // Swap the velocity buffers RenderTarget2D temp = this.velocityBufferLastFrame; this.velocityBufferLastFrame = this.velocityBuffer; this.velocityBuffer = temp; // Swap the color buffers colorTemp = colorDestination; colorDestination = colorSource; colorSource = colorTemp; } bool enableBloom = this.allowBloom && this.EnableBloom && this.BloomThreshold < 1.0f; bool enableBlur = this.BlurAmount > 0.0f; // Tone mapping this.toneMapEffect.CurrentTechnique = this.toneMapEffect.Techniques[enableBloom ? "ToneMap" : "ToneMapDecode"]; parameters.Camera.SetParameters(this.toneMapEffect); this.preparePostProcess(new RenderTarget2D[] { colorSource }, new RenderTarget2D[] { enableBloom || enableBlur ? colorDestination : result }, this.toneMapEffect); Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); // Swap the color buffers colorTemp = colorDestination; colorDestination = colorSource; colorSource = colorTemp; // Bloom if (enableBloom) { this.bloomEffect.CurrentTechnique = this.bloomEffect.Techniques["BlurHorizontal"]; parameters.Camera.SetParameters(this.bloomEffect); this.preparePostProcess(new RenderTarget2D[] { colorSource }, new RenderTarget2D[] { this.bloomBuffer }, this.bloomEffect); Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); this.bloomEffect.CurrentTechnique = this.bloomEffect.Techniques["Composite"]; this.preparePostProcess(new RenderTarget2D[] { colorSource, this.bloomBuffer }, new RenderTarget2D[] { enableBlur ? colorDestination : result }, this.bloomEffect); Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); // Swap the color buffers colorTemp = colorDestination; colorDestination = colorSource; colorSource = colorTemp; } if (enableBlur) { // Blur this.blurEffect.CurrentTechnique = this.blurEffect.Techniques["BlurHorizontal"]; parameters.Camera.SetParameters(this.blurEffect); this.preparePostProcess(new RenderTarget2D[] { colorSource }, new RenderTarget2D[] { colorDestination }, this.blurEffect); Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); this.blurEffect.CurrentTechnique = this.blurEffect.Techniques["Composite"]; // Swap the color buffers colorTemp = colorDestination; colorDestination = colorSource; colorSource = colorTemp; this.preparePostProcess(new RenderTarget2D[] { colorSource }, new RenderTarget2D[] { result }, this.blurEffect); Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); } }
protected override void LoadContent() { if (this.firstLoadContentCall) { // Initialize Wwise AkGlobalSoundEngineInitializer initializer = new AkGlobalSoundEngineInitializer(Path.Combine(this.Content.RootDirectory, "Wwise")); this.AddComponent(initializer); this.Listener = new AkListener(); this.Listener.Add(new Binding<Vector3>(this.Listener.Position, this.Camera.Position)); this.Listener.Add(new Binding<Vector3>(this.Listener.Forward, this.Camera.Forward)); this.Listener.Add(new Binding<Vector3>(this.Listener.Up, this.Camera.Up)); this.AddComponent(this.Listener); // Create the renderer. this.LightingManager = new LightingManager(); this.AddComponent(this.LightingManager); this.Renderer = new Renderer(this, this.ScreenSize, true, true, true, true); this.AddComponent(this.Renderer); this.renderParameters = new RenderParameters { Camera = this.Camera, IsMainRender = true }; this.firstLoadContentCall = false; this.UI = new UIRenderer(); this.AddComponent(this.UI); GeeUI.GeeUI.Initialize(this); this.ConsoleUI = new ConsoleUI(); this.AddComponent(ConsoleUI); this.Console = new Console.Console(); this.AddComponent(Console); PCInput input = new PCInput(); this.AddComponent(input); #if DEVELOPMENT input.Add(new CommandBinding(input.GetChord(new PCInput.Chord { Modifier = Keys.LeftAlt, Key = Keys.S }), delegate() { // High-resolution screenshot Screenshot s = new Screenshot(); this.AddComponent(s); s.Take(new Point(4096, 2304), delegate() { string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string path; int i = 0; do { path = Path.Combine(desktop, "lemma-screen" + i.ToString() + ".png"); i++; } while (File.Exists(path)); using (Stream stream = File.OpenWrite(path)) s.Buffer.SaveAsPng(stream, s.Size.X, s.Size.Y); s.Delete.Execute(); }); })); #endif #if PERFORMANCE_MONITOR this.performanceMonitor = new ListContainer(); this.performanceMonitor.Add(new Binding<Vector2, Point>(performanceMonitor.Position, x => new Vector2(0, x.Y), this.ScreenSize)); this.performanceMonitor.AnchorPoint.Value = new Vector2(0, 1); this.performanceMonitor.Visible.Value = false; this.performanceMonitor.Name.Value = "PerformanceMonitor"; this.UI.Root.Children.Add(this.performanceMonitor); Action<string, Property<double>> addTimer = delegate(string label, Property<double> property) { TextElement text = new TextElement(); text.FontFile.Value = "Font"; text.Add(new Binding<string, double>(text.Text, x => label + ": " + (x * 1000.0).ToString("F") + "ms", property)); this.performanceMonitor.Children.Add(text); }; Action<string, Property<int>> addCounter = delegate(string label, Property<int> property) { TextElement text = new TextElement(); text.FontFile.Value = "Font"; text.Add(new Binding<string, int>(text.Text, x => label + ": " + x.ToString(), property)); this.performanceMonitor.Children.Add(text); }; TextElement frameRateText = new TextElement(); frameRateText.FontFile.Value = "Font"; frameRateText.Add(new Binding<string, float>(frameRateText.Text, x => "FPS: " + x.ToString("0"), this.frameRate)); this.performanceMonitor.Children.Add(frameRateText); addTimer("Physics", this.physicsTime); addTimer("Update", this.updateTime); addTimer("Pre-frame", this.preframeTime); addTimer("Raw render", this.rawRenderTime); addTimer("Shadow render", this.shadowRenderTime); addTimer("Post-process", this.postProcessTime); addTimer("Non-post-processed", this.unPostProcessedTime); addCounter("Draw calls", this.drawCalls); addCounter("Triangles", this.triangles); input.Add(new CommandBinding(input.GetChord(new PCInput.Chord { Modifier = Keys.LeftAlt, Key = Keys.P }), delegate() { this.performanceMonitor.Visible.Value = !this.performanceMonitor.Visible; })); #endif try { IEnumerable<string> globalStaticScripts = Directory.GetFiles(Path.Combine(this.Content.RootDirectory, "GlobalStaticScripts"), "*", SearchOption.AllDirectories).Select(x => Path.Combine("..\\GlobalStaticScripts", Path.GetFileNameWithoutExtension(x))); foreach (string scriptName in globalStaticScripts) this.executeStaticScript(scriptName); } catch (IOException) { } } else { foreach (IDrawableComponent c in this.drawables) c.LoadContent(true); foreach (IDrawableAlphaComponent c in this.alphaDrawables) c.LoadContent(true); foreach (IDrawablePostAlphaComponent c in this.postAlphaDrawables) c.LoadContent(true); foreach (IDrawablePreFrameComponent c in this.preframeDrawables) c.LoadContent(true); foreach (INonPostProcessedDrawableComponent c in this.nonPostProcessedDrawables) c.LoadContent(true); this.ReloadedContent.Execute(); } this.GraphicsDevice.RasterizerState = new RasterizerState { MultiSampleAntiAlias = false }; }
public void SetRenderTargets(RenderParameters p) { bool motionBlur = this.allowMotionBlur && !this.main.Paused; if (motionBlur) this.main.GraphicsDevice.SetRenderTargets(this.colorBuffer1, this.depthBuffer, this.normalBuffer, this.velocityBuffer); else this.main.GraphicsDevice.SetRenderTargets(this.colorBuffer1, this.depthBuffer, this.normalBuffer); this.clearEffect.CurrentTechnique = this.clearEffect.Techniques[motionBlur ? "ClearMotionBlur" : "Clear"]; Color color = this.BackgroundColor; p.Camera.SetParameters(this.clearEffect); this.setTargetParameters(new RenderTarget2D[] { }, new RenderTarget2D[] { this.colorBuffer1 }, this.clearEffect); this.clearEffect.Parameters["BackgroundColor"].SetValue(new Vector3((float)color.R / 255.0f, (float)color.G / 255.0f, (float)color.B / 255.0f)); this.applyEffect(this.clearEffect); Renderer.quad.DrawAlpha(this.main.GameTime, RenderParameters.Default); }
public void DrawPostAlphaComponents(RenderParameters parameters) { for (int i = 0; i < this.postAlphaDrawables.Count; i++) { IDrawablePostAlphaComponent c = this.postAlphaDrawables[i]; if (this.componentEnabled(c)) c.DrawPostAlpha(this.GameTime, parameters); } }
/// <summary> /// Draws a single mesh using the given world matrix. /// </summary> /// <param name="camera"></param> /// <param name="transform"></param> protected virtual void draw(RenderParameters parameters, Matrix transform) { if (this.model != null) { if (this.setParameters(transform, parameters)) { this.main.LightingManager.SetRenderParameters(this.effect, parameters); RasterizerState originalState = this.main.GraphicsDevice.RasterizerState; RasterizerState noCullState = null; if (parameters.IsMainRender && this.DisableCulling) { noCullState = new RasterizerState { CullMode = CullMode.None }; this.main.GraphicsDevice.RasterizerState = noCullState; } foreach (ModelMesh mesh in this.model.Meshes) { foreach (ModelMeshPart part in mesh.MeshParts) { if (part.NumVertices > 0) { // Draw all the instance copies in a single call. foreach (EffectPass pass in this.effect.CurrentTechnique.Passes) { pass.Apply(); this.main.GraphicsDevice.SetVertexBuffer(part.VertexBuffer, part.VertexOffset); this.main.GraphicsDevice.Indices = part.IndexBuffer; this.main.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, part.NumVertices, part.StartIndex, part.PrimitiveCount); } } } } if (noCullState != null) this.main.GraphicsDevice.RasterizerState = originalState; if (parameters.IsMainRender) { this.lastTransform = transform; this.lastWorldViewProjection = transform * parameters.Camera.ViewProjection; } } } }
/// <summary> /// Draws a collection of instances. Requires an HLSL effect designed for hardware instancing. /// </summary> /// <param name="device"></param> /// <param name="camera"></param> /// <param name="instances"></param> protected override void drawInstances(RenderParameters parameters, Matrix transform) { throw new NotSupportedException("Instancing not supported for dynamic models."); }
public virtual void Draw(GameTime time, RenderParameters parameters) { Matrix transform = Matrix.CreateScale(this.Scale) * this.Transform; if (this.boundingBoxValid && this.CullBoundingBox) { if (!parameters.IsMainRender) { // For the main render, we calculate the culling every other frame // We don't cache the culling data for other cameras. if (!parameters.Camera.BoundingFrustum.Value.Intersects(this.BoundingBox.Value.Transform(transform))) return; } else if (this.lastFrameCullUpdated) { this.lastFrameCullUpdated = false; if (this.lastFrameCulled) return; } else { this.lastFrameCullUpdated = true; this.lastFrameCulled = !parameters.Camera.BoundingFrustum.Value.Intersects(this.BoundingBox.Value.Transform(transform)); if (this.lastFrameCulled) return; } } if (!this.IsInstanced) this.draw(parameters, transform); else this.drawInstances(parameters, transform); }
void IDrawablePreFrameComponent.DrawPreFrame(GameTime time, RenderParameters p) { if (!this.EnableReflection) return; if (this.needResize) this.resize(); float waterHeight = this.Position.Value.Y; if (p.Camera.Position.Value.Y > waterHeight) { this.parameters.ClipPlanes = new[] { new Plane(Vector3.Up, -waterHeight) }; this.renderer.SetRenderTargets(this.parameters); this.camera.Position.Value = p.Camera.Position; Matrix reflect = Matrix.CreateTranslation(0.0f, -waterHeight, 0.0f) * Matrix.CreateScale(1.0f, -1.0f, 1.0f) * Matrix.CreateTranslation(0.0f, waterHeight, 0.0f); this.camera.Position.Value = Vector3.Transform(this.camera.Position, reflect); this.camera.View.Value = reflect * p.Camera.View; this.camera.SetPerspectiveProjection(p.Camera.FieldOfView, new Point(this.buffer.Width, this.buffer.Height), p.Camera.NearPlaneDistance, p.Camera.FarPlaneDistance); this.main.DrawScene(this.parameters); this.renderer.PostProcess(this.buffer, this.parameters, this.main.DrawAlphaComponents); } }
public void SetRenderParameters(Microsoft.Xna.Framework.Graphics.Effect effect, RenderParameters parameters) { }
public override void Awake() { base.Awake(); this.EnabledWhenPaused = true; this.Add(new NotifyBinding(main.AlphaDrawablesModified, this.DrawOrder)); this.Add(new SetBinding <bool>(this.CannotSuspendByDistance, delegate(bool value) { this.Entity.CannotSuspendByDistance = value; })); this.Add(new NotifyBinding(delegate() { this.needResize = true; }, this.main.ScreenSize)); this.Add(new Binding <bool>(this.EnableReflection, this.main.Settings.Reflections)); Action removeFluid = delegate() { if (this.Fluid.Space != null) { this.main.Space.Remove(this.Fluid); } AkSoundEngine.PostEvent(AK.EVENTS.STOP_WATER_LOOP, this.Entity); }; Action addFluid = delegate() { if (this.Fluid.Space == null && this.Enabled && !this.Suspended) { this.main.Space.Add(this.Fluid); if (!this.main.EditorEnabled) { AkSoundEngine.PostEvent(AK.EVENTS.PLAY_WATER_LOOP, this.Entity); } } }; this.Add(new CommandBinding(this.OnSuspended, removeFluid)); this.Add(new CommandBinding(this.Disable, removeFluid)); this.Add(new CommandBinding(this.OnResumed, addFluid)); this.Add(new CommandBinding(this.Enable, addFluid)); this.camera = new Camera(); this.main.AddComponent(this.camera); this.parameters = new RenderParameters { Camera = this.camera, Technique = Technique.Clip, ReverseCullOrder = true, }; this.Add(new SetBinding <Vector3>(this.Color, delegate(Vector3 value) { this.effect.Parameters["Color"].SetValue(value); })); this.Add(new SetBinding <Vector2>(this.Scale, delegate(Vector2 value) { this.effect.Parameters["Scale"].SetValue(value); this.updatePhysics(); })); this.Add(new SetBinding <Vector3>(this.UnderwaterColor, delegate(Vector3 value) { this.effect.Parameters["UnderwaterColor"].SetValue(value); })); this.Add(new SetBinding <float>(this.Fresnel, delegate(float value) { this.effect.Parameters["Fresnel"].SetValue(value); })); this.Add(new SetBinding <float>(this.Speed, delegate(float value) { this.effect.Parameters["Speed"].SetValue(value); })); this.Add(new SetBinding <float>(this.RippleDensity, delegate(float value) { this.effect.Parameters["RippleDensity"].SetValue(value); })); this.Add(new SetBinding <float>(this.Distortion, delegate(float value) { this.effect.Parameters["Distortion"].SetValue(value); })); this.Add(new SetBinding <float>(this.Brightness, delegate(float value) { this.effect.Parameters["Brightness"].SetValue(value); })); this.Add(new SetBinding <float>(this.Refraction, delegate(float value) { this.effect.Parameters["Refraction"].SetValue(value); })); this.Add(new SetBinding <Vector3>(this.Position, delegate(Vector3 value) { this.effect.Parameters["Position"].SetValue(this.Position); if (this.CannotSuspendByDistance) { Water.BigWaterHeight.Value = value.Y; } this.updatePhysics(); })); this.Add(new SetBinding <float>(this.Depth, delegate(float value) { this.updatePhysics(); })); instances.Add(this); this.Add(new Binding <Vector3>(this.soundPosition, delegate(Vector3 pos) { BoundingBox box = this.Fluid.BoundingBox; pos.X = Math.Max(box.Min.X, Math.Min(pos.X, box.Max.X)); pos.Y = this.Position.Value.Y; pos.Z = Math.Max(box.Min.Z, Math.Min(pos.Z, box.Max.Z)); return(pos); }, this.main.Camera.Position)); AkGameObjectTracker.Attach(this.Entity, this.soundPosition); if (!this.main.EditorEnabled && this.Enabled && !this.Suspended) { AkSoundEngine.PostEvent(AK.EVENTS.PLAY_WATER_LOOP, this.Entity); } }
void IDrawableAlphaComponent.DrawAlpha(Microsoft.Xna.Framework.GameTime time, RenderParameters p) { if (this.Lines.Length == 0 || LineDrawer.unsupportedTechniques.Contains(p.Technique)) { return; } if (this.vertexBuffer == null || this.vertexBuffer.IsContentLost || this.Lines.Length * 2 > this.vertexBuffer.VertexCount || this.changed) { this.changed = false; if (this.vertexBuffer != null) { this.vertexBuffer.Dispose(); } this.vertexBuffer = new DynamicVertexBuffer(this.main.GraphicsDevice, VertexPositionColor.VertexDeclaration, (this.Lines.Length * 2) + 8, BufferUsage.WriteOnly); VertexPositionColor[] data = new VertexPositionColor[this.vertexBuffer.VertexCount]; for (int i = 0; i < this.Lines.Count; i++) { Line line = this.Lines[i]; data[i * 2] = line.A; data[i * 2 + 1] = line.B; } this.vertexBuffer.SetData <VertexPositionColor>(data, 0, this.Lines.Length * 2, SetDataOptions.Discard); } p.Camera.SetParameters(this.effect); this.effect.Parameters["Depth" + Model.SamplerPostfix].SetValue(p.DepthBuffer); // Draw lines try { this.effect.CurrentTechnique = this.effect.Techniques[p.TechniqueString]; } catch (Exception) { LineDrawer.unsupportedTechniques.Add(p.Technique); return; } this.effect.CurrentTechnique.Passes[0].Apply(); this.main.GraphicsDevice.SetVertexBuffer(this.vertexBuffer); this.main.GraphicsDevice.DrawPrimitives(PrimitiveType.LineList, 0, this.Lines.Length); Model.DrawCallCounter++; Model.TriangleCounter += this.Lines.Length; }