Kav/Renderer.cs

124 lines
4.7 KiB
C#

using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Kav
{
public class Renderer
{
private GraphicsDevice GraphicsDevice { get; }
private int RenderDimensionsX { get; }
private int RenderDimensionsY { get; }
private RenderTarget2D DepthRenderTarget { get; }
private SimpleDepthEffect SimpleDepthEffect { get; }
public Renderer(GraphicsDevice graphicsDevice, int renderDimensionsX, int renderDimensionsY)
{
GraphicsDevice = graphicsDevice;
RenderDimensionsX = renderDimensionsX;
RenderDimensionsY = renderDimensionsY;
DepthRenderTarget = new RenderTarget2D(
GraphicsDevice,
renderDimensionsX,
renderDimensionsY,
false,
SurfaceFormat.Color,
DepthFormat.Depth24
);
SimpleDepthEffect = new SimpleDepthEffect(GraphicsDevice);
}
public void Render(Camera camera, IEnumerable<Model> models, IEnumerable<PointLight> pointLights)
{
Render(camera.View, camera.Projection, models, pointLights);
}
// for shadow mapping
public void DepthRender(Matrix view, Matrix projection, IEnumerable<(Model, Matrix)> modelTransforms, IEnumerable<PointLight> pointLights)
{
GraphicsDevice.SetRenderTarget(DepthRenderTarget);
GraphicsDevice.Clear(ClearOptions.DepthBuffer, Color.Black, 1, 0);
SimpleDepthEffect.View = view;
SimpleDepthEffect.Projection = projection;
foreach (var (model, transform) in modelTransforms)
{
foreach (var modelMesh in model.Meshes)
{
foreach (var meshPart in modelMesh.MeshParts)
{
GraphicsDevice.SetVertexBuffer(meshPart.VertexBuffer);
GraphicsDevice.Indices = meshPart.IndexBuffer;
SimpleDepthEffect.Model = transform;
foreach (var pass in SimpleDepthEffect.CurrentTechnique.Passes)
{
pass.Apply();
GraphicsDevice.DrawIndexedPrimitives(
PrimitiveType.TriangleList,
0,
0,
meshPart.VertexBuffer.VertexCount,
0,
meshPart.Triangles.Length
);
}
}
}
}
}
private void Render(Matrix view, Matrix projection, IEnumerable<Model> models, IEnumerable<PointLight> pointLights)
{
foreach (var model in models)
{
foreach (var modelMesh in model.Meshes)
{
foreach (var meshPart in modelMesh.MeshParts)
{
GraphicsDevice.SetVertexBuffer(meshPart.VertexBuffer);
GraphicsDevice.Indices = meshPart.IndexBuffer;
if (meshPart.Effect is TransformEffect transformEffect)
{
transformEffect.View = view;
transformEffect.Projection = projection;
}
if (meshPart.Effect is PointLightEffect pointLightEffect)
{
int i = 0;
foreach (var pointLight in pointLights)
{
if (i > pointLightEffect.MaxPointLights) { break; }
pointLightEffect.PointLights[i] = pointLight;
i++;
}
}
foreach (var pass in meshPart.Effect.CurrentTechnique.Passes)
{
pass.Apply();
GraphicsDevice.DrawIndexedPrimitives(
PrimitiveType.TriangleList,
0,
0,
meshPart.VertexBuffer.VertexCount,
0,
meshPart.Triangles.Length
);
}
}
}
}
}
}
}