internal unsafe void RecordCommands(MyRenderableProxy proxy, VertexBufferId stream, int voxelMatId) { if (stream == VertexBufferId.NULL) { return; } var foliageType = MyVoxelMaterials1.Table[voxelMatId].FoliageType; MyMapping mapping = MyMapping.MapDiscard(RC.DeviceContext, proxy.ObjectBuffer); mapping.WriteAndPosition(ref proxy.NonVoxelObjectData); mapping.WriteAndPosition(ref proxy.CommonObjectData); mapping.Unmap(); RC.SetCB(MyCommon.OBJECT_SLOT, proxy.ObjectBuffer); RC.SetGS(m_GS[foliageType]); RC.SetPS(m_PS[foliageType]); if (MyVoxelMaterials1.Table[voxelMatId].FoliageColorTextureArray != null) { RC.BindRawSRV(0, MyVoxelMaterials1.Table[voxelMatId].FoliageColorTextureArray.ShaderView); RC.BindRawSRV(1, MyVoxelMaterials1.Table[voxelMatId].FoliageNormalTextureArray.ShaderView); } else { RC.BindRawSRV(0, MyTextures.GetView(MyTextures.GetTexture(MyVoxelMaterials1.Table[voxelMatId].FoliageArray_Texture, MyTextureEnum.COLOR_METAL, true))); RC.BindRawSRV(1, MyTextures.GetView(MyTextures.GetTexture(MyVoxelMaterials1.Table[voxelMatId].FoliageArray_NormalTexture, MyTextureEnum.NORMALMAP_GLOSS, true))); } RC.SetVB(0, stream.Buffer, stream.Stride); Context.DrawAuto(); RC.Stats.DrawAuto++; }
internal MyTextureArray(TexId[] mergeList) { var srcDesc = MyTextures.GetView(mergeList[0]).Description; Size = MyTextures.GetSize(mergeList[0]); ArrayLen = mergeList.Length; Texture2DDescription desc = new Texture2DDescription(); desc.ArraySize = ArrayLen; desc.BindFlags = BindFlags.ShaderResource; desc.CpuAccessFlags = CpuAccessFlags.None; desc.Format = srcDesc.Format; desc.Height = (int)Size.Y; desc.Width = (int)Size.X; desc.MipLevels = 0; desc.SampleDescription.Count = 1; desc.SampleDescription.Quality = 0; desc.Usage = ResourceUsage.Default; m_resource = new Texture2D(MyRender11.Device, desc); // foreach mip var mipmaps = (int)Math.Log(Size.X, 2) + 1; for (int a = 0; a < ArrayLen; a++) { for (int m = 0; m < mipmaps; m++) { MyRender11.Context.CopySubresourceRegion(MyTextures.Textures.Data[mergeList[a].Index].Resource, Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource, Resource.CalculateSubResourceIndex(m, a, mipmaps)); } } ShaderView = new ShaderResourceView(MyRender11.Device, Resource); }
internal unsafe void RecordCommands(MyRenderableProxy proxy, VertexBufferId stream, int voxelMatId) { //var worldMat = proxy.WorldMatrix; //worldMat.Translation -= MyEnvironment.CameraPosition; //proxy.ObjectData.LocalMatrix = worldMat; //var worldMatrix = Matrix.CreateTranslation(-MyEnvironment.CameraPosition); MyObjectData objectData = proxy.ObjectData; //objectData.LocalMatrix = worldMat; MyMapping mapping; mapping = MyMapping.MapDiscard(RC.Context, proxy.objectBuffer); void *ptr = &objectData; mapping.stream.Write(new IntPtr(ptr), 0, sizeof(MyObjectData)); mapping.Unmap(); RC.SetCB(MyCommon.OBJECT_SLOT, proxy.objectBuffer); RC.BindRawSRV(0, MyTextures.GetView(MyTextures.GetTexture(MyVoxelMaterials1.Table[voxelMatId].FoliageArray_Texture, MyTextureEnum.COLOR_METAL, true))); RC.SetVB(0, stream.Buffer, stream.Stride); Context.DrawAuto(); RC.Stats.DrawAuto++; }
internal unsafe void RecordCommands(MyRenderableProxy proxy, VertexBufferId stream, int voxelMatId) { MyObjectData objectData = proxy.ObjectData; var foliageType = MyVoxelMaterials1.Table[voxelMatId].FoliageType; MyMapping mapping; mapping = MyMapping.MapDiscard(RC.Context, proxy.ObjectBuffer); void *ptr = &objectData; mapping.stream.Write(new IntPtr(ptr), 0, sizeof(MyObjectData)); mapping.Unmap(); RC.SetCB(MyCommon.OBJECT_SLOT, proxy.ObjectBuffer); RC.SetGS(m_GS[foliageType]); RC.SetPS(m_PS[foliageType]); if (MyVoxelMaterials1.Table[voxelMatId].FoliageColorTextureArray != null) { RC.BindRawSRV(0, MyVoxelMaterials1.Table[voxelMatId].FoliageColorTextureArray.ShaderView); RC.BindRawSRV(1, MyVoxelMaterials1.Table[voxelMatId].FoliageNormalTextureArray.ShaderView); } else { RC.BindRawSRV(0, MyTextures.GetView(MyTextures.GetTexture(MyVoxelMaterials1.Table[voxelMatId].FoliageArray_Texture, MyTextureEnum.COLOR_METAL, true))); RC.BindRawSRV(1, MyTextures.GetView(MyTextures.GetTexture(MyVoxelMaterials1.Table[voxelMatId].FoliageArray_NormalTexture, MyTextureEnum.NORMALMAP_GLOSS, true))); } RC.SetVB(0, stream.Buffer, stream.Stride); Context.DrawAuto(); RC.Stats.DrawAuto++; }
static void BindResourcesCommon() { RC.SetRS(MyRender11.m_nocullRasterizerState); RC.BindRawSRV(104, m_SB); RC.SetCB(2, m_cbCustomProjections); if (MyStereoRender.Enable && MyStereoRender.EnableUsingStencilMask) { RC.SetDS(MyDepthStencilState.StereoDefaultDepthState); } else { RC.SetDS(MyDepthStencilState.DefaultDepthState); } RC.SetCB(4, MyRender11.DynamicShadows.ShadowCascades.CascadeConstantBuffer); RC.DeviceContext.VertexShader.SetSampler(MyCommon.SHADOW_SAMPLER_SLOT, SamplerStates.m_shadowmap); RC.DeviceContext.VertexShader.SetShaderResource(MyCommon.CASCADES_SM_SLOT, MyRender11.DynamicShadows.ShadowCascades.CascadeShadowmapArray.SRV); RC.DeviceContext.VertexShader.SetSamplers(0, SamplerStates.StandardSamplers); RC.DeviceContext.VertexShader.SetShaderResource(MyCommon.SKYBOX_IBL_SLOT, MyRender11.IsIntelBrokenCubemapsWorkaround ? MyTextures.GetView(MyTextures.IntelFallbackCubeTexId) : MyEnvironmentProbe.Instance.cubemapPrefiltered.SRV); RC.DeviceContext.VertexShader.SetShaderResource(MyCommon.SKYBOX2_IBL_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyRender11.Environment.NightSkyboxPrefiltered, MyTextureEnum.CUBEMAP, true))); RC.SetVB(0, m_VB.Buffer, m_VB.Stride); RC.SetIB(m_IB.Buffer, m_IB.Format); RC.SetIL(m_inputLayout); }
internal unsafe static void RenderSpotlights() { var coneMesh = MyMeshes.GetMeshId(X.TEXT("Models/Debug/Cone.mwm")); var buffers = MyMeshes.GetLodMesh(coneMesh, 0).Buffers; RC.SetVB(0, buffers.VB0.Buffer, buffers.VB0.Stride); RC.SetIB(buffers.IB.Buffer, buffers.IB.Format); RC.SetVS(SpotlightProxyVs); RC.SetIL(SpotlightProxyIL); RC.SetRS(MyRender11.m_nocullRasterizerState); var cb = MyCommon.GetObjectCB(sizeof(SpotlightConstants)); RC.SetCB(1, cb); RC.Context.PixelShader.SetSampler(MyCommon.SHADOW_SAMPLER_SLOT, MyRender11.m_shadowmapSamplerState); int index = 0; int casterIndex = 0; foreach (var id in VisibleSpotlights) { var mapping = MyMapping.MapDiscard(cb); mapping.stream.Write(MyLightRendering.Spotlights[index]); mapping.Unmap(); RC.Context.PixelShader.SetShaderResource(13, MyTextures.GetView(MyLights.Spotlights[id.Index].ReflectorTexture)); if (id.CastsShadows) { RC.Context.PixelShader.SetShaderResource(14, MyShadows.ShadowmapsPool[casterIndex].ShaderView); casterIndex++; } RC.SetPS(SpotlightPs_Pixel); if (MyRender11.MultisamplingEnabled) { RC.SetDS(MyDepthStencilState.TestEdgeStencil, 0); } RC.Context.DrawIndexed(MyMeshes.GetLodMesh(coneMesh, 0).Info.IndicesNum, 0, 0); if (MyRender11.MultisamplingEnabled) { RC.SetPS(SpotlightPs_Sample); RC.SetDS(MyDepthStencilState.TestEdgeStencil, 0x80); RC.Context.DrawIndexed(MyMeshes.GetLodMesh(coneMesh, 0).Info.IndicesNum, 0, 0); } index++; } if (MyRender11.MultisamplingEnabled) { RC.SetDS(MyDepthStencilState.DefaultDepthState); } RC.SetRS(null); }
static void RenderDirectionalEnvironmentLight() { PixelShaderId directionalPixelShader; if (!MyRenderProxy.Settings.EnableShadows) { if (DirectionalEnvironmentLight_NoShadow == PixelShaderId.NULL) { DirectionalEnvironmentLight_NoShadow = MyShaders.CreatePs("light_dir.hlsl", new[] { new ShaderMacro("NO_SHADOWS", null) }); } directionalPixelShader = DirectionalEnvironmentLight_NoShadow; } else { directionalPixelShader = DirectionalEnvironmentLight_Pixel; } MySunlightConstantsLayout constants; constants.Direction = MyEnvironment.DirectionalLightDir; constants.Color = MyEnvironment.DirectionalLightIntensity; var mapping = MyMapping.MapDiscard(m_sunlightConstants); mapping.WriteAndPosition(ref constants); mapping.Unmap(); //context.VertexShader.Set(MyCommon.FullscreenShader.VertexShader); RC.SetPS(directionalPixelShader); RC.SetCB(1, m_sunlightConstants); RC.SetCB(4, MyRender11.DynamicShadows.ShadowCascades.CascadeConstantBuffer); RC.DeviceContext.PixelShader.SetSamplers(0, MyRender11.StandardSamplers); RC.DeviceContext.PixelShader.SetSampler(MyCommon.SHADOW_SAMPLER_SLOT, MyRender11.m_shadowmapSamplerState); RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.SKYBOX_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.DaySkybox, MyTextureEnum.CUBEMAP, true))); RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.SKYBOX_IBL_SLOT, MyRender11.IsIntelBrokenCubemapsWorkaround ? MyTextures.GetView(MyTextures.IntelFallbackCubeTexId) : MyEnvironmentProbe.Instance.cubemapPrefiltered.ShaderView); RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.SKYBOX2_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.NightSkybox, MyTextureEnum.CUBEMAP, true))); RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.SKYBOX2_IBL_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.NightSkyboxPrefiltered, MyTextureEnum.CUBEMAP, true))); RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.CASCADES_SM_SLOT, MyRender11.DynamicShadows.ShadowCascades.CascadeShadowmapArray.ShaderView); RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.SHADOW_SLOT, MyRender11.PostProcessedShadows.ShaderView); RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.AMBIENT_BRDF_LUT_SLOT, MyCommon.GetAmbientBrdfLut()); RC.BindSRV(MyCommon.AO_SLOT, MyScreenDependants.m_ambientOcclusion); MyScreenPass.RunFullscreenPixelFreq(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer)); if (MyRender11.MultisamplingEnabled) { RC.SetPS(DirectionalEnvironmentLight_Sample); MyScreenPass.RunFullscreenSampleFreq(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer)); } }
internal void Init() { var srcData = MyTextures.Textures.Data[m_mergeList[0].Index]; var srcDesc = MyTextures.GetView(m_mergeList[0]).Description; Size = MyTextures.GetSize(m_mergeList[0]); ArrayLen = m_mergeList.Length; Texture2DDescription desc = new Texture2DDescription(); desc.ArraySize = ArrayLen; desc.BindFlags = BindFlags.ShaderResource; desc.CpuAccessFlags = CpuAccessFlags.None; desc.Format = srcDesc.Format; desc.Height = (int)Size.Y; desc.Width = (int)Size.X; desc.MipLevels = srcDesc.Texture2D.MipLevels; desc.SampleDescription.Count = 1; desc.SampleDescription.Quality = 0; desc.Usage = ResourceUsage.Default; m_resource = new Texture2D(MyRender11.Device, desc); m_resource.DebugName = m_debugName; // foreach mip var mipmaps = srcDesc.Texture2D.MipLevels; for (int a = 0; a < ArrayLen; a++) { var data = MyTextures.Textures.Data[m_mergeList[a].Index]; var tex2D = data.Resource as Texture2D; MyRenderProxy.Assert(tex2D != null, "MyTextureArray supports only 2D textures. Inconsistent texture: " + data.Name); bool consistent = tex2D.Description.Format == desc.Format && tex2D.Description.MipLevels == desc.MipLevels && tex2D.Description.Width == desc.Width && tex2D.Description.Height == desc.Height; if (!consistent) { string errorMsg = "All MyTextureArray has to have the same pixel format, width / height and # of mipmaps. Inconsistent textures: " + data.Name + " / " + srcData.Name; MyRenderProxy.Error(errorMsg); MyRender11.Log.WriteLine(errorMsg); } for (int m = 0; m < mipmaps; m++) { MyRender11.DeviceContext.CopySubresourceRegion(tex2D, Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource, Resource.CalculateSubResourceIndex(m, a, mipmaps)); } } m_Srv = new ShaderResourceView(MyRender11.Device, Resource); }
internal MyTextureArray(TexId[] mergeList, string debugName) { var srcDesc = MyTextures.GetView(mergeList[0]).Description; Size = MyTextures.GetSize(mergeList[0]); ArrayLen = mergeList.Length; Texture2DDescription desc = new Texture2DDescription(); desc.ArraySize = ArrayLen; desc.BindFlags = BindFlags.ShaderResource; desc.CpuAccessFlags = CpuAccessFlags.None; desc.Format = srcDesc.Format; desc.Height = (int)Size.Y; desc.Width = (int)Size.X; desc.MipLevels = srcDesc.Texture2D.MipLevels; desc.SampleDescription.Count = 1; desc.SampleDescription.Quality = 0; desc.Usage = ResourceUsage.Default; m_resource = new Texture2D(MyRender11.Device, desc); m_resource.DebugName = debugName; // foreach mip var mipmaps = desc.MipLevels;// (int)Math.Log(Size.X, 2) + 1; for (int a = 0; a < ArrayLen; a++) { var tex2D = MyTextures.Textures.Data[mergeList[a].Index].Resource as Texture2D; MyRenderProxy.Assert(tex2D != null, "MyTextureArray supports only 2D textures"); MyRenderProxy.Assert(tex2D.Description.Format == desc.Format && tex2D.Description.MipLevels == desc.MipLevels && tex2D.Description.Width == desc.Width && tex2D.Description.Height == desc.Height, "All MyTextureArray has to have the same pixel format, width / height and # of mipmaps."); for (int m = 0; m < mipmaps; m++) { if (((Texture2D)MyTextures.Textures.Data[mergeList[a].Index].Resource).Description.Format != ((Texture2D)Resource).Description.Format) { MyRender11.Log.WriteLine(String.Format("Inconsistent format in textures array {0}", MyTextures.Textures.Data[mergeList[a].Index].Name)); } MyRender11.DeviceContext.CopySubresourceRegion(MyTextures.Textures.Data[mergeList[a].Index].Resource, Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource, Resource.CalculateSubResourceIndex(m, a, mipmaps)); } } ShaderView = new ShaderResourceView(MyRender11.Device, Resource); }
static void RenderDirectionalEnvironmentLight() { MySunlightConstantsLayout constants; constants.Direction = MyEnvironment.DirectionalLightDir; constants.Color = MyEnvironment.DirectionalLightIntensity; var mapping = MyMapping.MapDiscard(m_sunlightConstants); mapping.stream.Write(constants); mapping.Unmap(); //context.VertexShader.Set(MyCommon.FullscreenShader.VertexShader); RC.SetPS(DirectionalEnvironmentLight_Pixel); RC.SetCB(1, m_sunlightConstants); RC.SetCB(4, MyShadows.m_csmConstants); RC.Context.PixelShader.SetSamplers(0, MyRender11.StandardSamplers); RC.Context.PixelShader.SetSampler(MyCommon.SHADOW_SAMPLER_SLOT, MyRender11.m_shadowmapSamplerState); RC.Context.PixelShader.SetShaderResource(MyCommon.CASCADES_SM_SLOT, MyShadows.m_cascadeShadowmapArray.ShaderView); var z = Vector4.Transform(new Vector4(0.5f, 0.5f, -MyEnvironment.FarClipping, 1), MyEnvironment.Projection); RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.DaySkybox, MyTextureEnum.CUBEMAP, true))); //RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX_IBL_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.DaySkyboxPrefiltered, MyTextureEnum.CUBEMAP, true))); RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX_IBL_SLOT, MyRender11.IsIntelBrokenCubemapsWorkaround ? MyTextures.GetView(MyTextures.IntelFallbackCubeTexId) : MyGeometryRenderer.m_envProbe.cubemapPrefiltered.ShaderView); RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX2_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.NightSkybox, MyTextureEnum.CUBEMAP, true))); RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX2_IBL_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.NightSkyboxPrefiltered, MyTextureEnum.CUBEMAP, true))); RC.Context.PixelShader.SetShaderResource(MyCommon.SHADOW_SLOT, MyRender11.m_shadowsHelper.ShaderView); RC.Context.PixelShader.SetShaderResource(MyCommon.AMBIENT_BRDF_LUT_SLOT, MyCommon.GetAmbientBrdfLut()); RC.BindSRV(MyCommon.AO_SLOT, MyScreenDependants.m_ambientOcclusion); MyScreenPass.RunFullscreenPixelFreq(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer)); if (MyRender11.MultisamplingEnabled) { RC.SetPS(DirectionalEnvironmentLight_Sample); MyScreenPass.RunFullscreenSampleFreq(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer)); } }
internal unsafe static void RunForwardPostprocess(RenderTargetView rt, ShaderResourceView depth, ref Matrix viewMatrix, uint?atmosphereId) { var mapping = MyMapping.MapDiscard(RC.Context, MyCommon.ProjectionConstants); mapping.stream.Write(Matrix.Transpose(viewMatrix)); mapping.Unmap(); RC.SetCB(MyCommon.FRAME_SLOT, MyCommon.FrameConstants); RC.SetCB(MyCommon.PROJECTION_SLOT, MyCommon.ProjectionConstants); RC.Context.OutputMerger.SetTargets(rt); RC.Context.PixelShader.SetShaderResource(0, depth); RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.DaySkybox, MyTextureEnum.CUBEMAP, true))); RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX2_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.NightSkybox, MyTextureEnum.CUBEMAP, true))); RC.Context.PixelShader.SetSamplers(0, MyRender11.StandardSamplers); RC.Context.PixelShader.Set(m_ps); MyScreenPass.DrawFullscreenQuad(new MyViewport(256, 256)); RC.Context.OutputMerger.SetTargets(null as RenderTargetView); }
internal unsafe static void Render(MyBindableResource dst, MyBindableResource depth, MyBindableResource depthRead) { MyRender11.GetRenderProfiler().StartProfilingBlock("Gather"); Gather(); MyRender11.GetRenderProfiler().EndProfilingBlock(); MyRender11.GetRenderProfiler().StartProfilingBlock("Draw"); TransferData(); RC.SetupScreenViewport(); RC.BindDepthRT(depth, DepthStencilAccess.ReadOnly, dst); RC.SetBS(MyRender11.BlendAlphaPremult); RC.SetRS(MyRender11.m_nocullRasterizerState); RC.BindRawSRV(104, m_SB.Srv); RC.BindSRV(1, depthRead); RC.SetCB(2, MyCommon.GetObjectCB(sizeof(Matrix) * MaxCustomProjections)); RC.SetDS(MyDepthStencilState.DefaultDepthState); RC.SetCB(4, MyShadows.m_csmConstants); RC.Context.VertexShader.SetSampler(MyCommon.SHADOW_SAMPLER_SLOT, MyRender11.m_shadowmapSamplerState); RC.Context.VertexShader.SetShaderResource(MyCommon.CASCADES_SM_SLOT, MyShadows.m_cascadeShadowmapArray.ShaderView); RC.Context.VertexShader.SetSamplers(0, MyRender11.StandardSamplers); RC.Context.VertexShader.SetShaderResource(MyCommon.SKYBOX_IBL_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.DaySkyboxPrefiltered, MyTextureEnum.CUBEMAP, true))); RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX2_IBL_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.NightSkyboxPrefiltered, MyTextureEnum.CUBEMAP, true))); RC.SetVB(0, m_VB.Buffer, m_VB.Stride); RC.SetIB(m_IB.Buffer, m_IB.Format); RC.SetIL(m_inputLayout); for (int i = 0; i < m_batches.Count; i++) { // first part of batches contain sorted billboards and they read depth // second part of batches contain unsorted billboards and they ignore depth // switch here: if (m_batches[i].Offset == m_sortedBillboardsNum) { //RC.BindDepthRT(null, DepthStencilAccess.ReadOnly, dst); } if (m_batches[i].Lit) { RC.SetVS(m_vsLit); RC.SetPS(m_psLit); } else { RC.SetVS(m_vs); RC.SetPS(m_ps); } RC.BindRawSRV(0, m_batches[i].Texture); RC.Context.DrawIndexed(m_batches[i].Num * 6, m_batches[i].Offset * 6, 0); } RC.SetRS(null); m_batches.Clear(); MyRender11.GetRenderProfiler().EndProfilingBlock(); }
static void Gather() { // counting sorted billboards m_batches.Clear(); m_sortedNum = 0; PreGatherList(MyRenderProxy.BillboardsRead); PreGatherList(m_billboardsOnce); m_sortedBillboardsNum = m_sortedNum; m_unsorted = 0; m_sorted = 0; GatherList(MyRenderProxy.BillboardsRead); GatherList(m_billboardsOnce); Array.Sort(m_sortBuffer, 0, m_sortedNum); //Array.Reverse(m_sortBuffer, 0, m_sortedNum); //Array.Sort(m_sortBuffer, m_sortedNum, m_unsorted); var N = m_sorted + m_unsorted; var batch = new MyBillboardBatch(); //MyAssetTexture prevTexture = null; var prevTexId = TexId.NULL; int currentOffset = 0; if (N > 0) { var material = MyTransparentMaterials.GetMaterial(m_sortBuffer[0].Material); if (material.UseAtlas) { var item = m_atlasedTextures[material.Texture]; prevTexId = item.TextureId; } else { PreloadTexture(material.Texture); //prevTexture = MyTextureManager.GetTextureFast(material.Texture); prevTexId = MyTextures.GetTexture(material.Texture, MyTextureEnum.GUI, true); } } TexId batchTexId = TexId.NULL; MyTransparentMaterial prevMaterial = null; for (int i = 0; i < N; i++) { var billboard = m_sortBuffer[i]; var material = MyTransparentMaterials.GetMaterial(billboard.Material); var billboardData = new MyBillboardData(); billboardData.CustomProjectionID = billboard.CustomViewProjection; billboardData.Color = billboard.Color; if (material.UseAtlas) { var atlasItem = m_atlasedTextures[material.Texture]; //billboardData.UvModifiers = new HalfVector4(atlasItem.UvOffsetScale); batchTexId = atlasItem.TextureId; } else { batchTexId = MyTextures.GetTexture(material.Texture, MyTextureEnum.GUI, true); } billboardData.Reflective = billboard.Reflectivity; Vector3D pos0 = billboard.Position0; Vector3D pos1 = billboard.Position1; Vector3D pos2 = billboard.Position2; Vector3D pos3 = billboard.Position3; if (billboard.ParentID != -1) { if (MyIDTracker <MyActor> .FindByID((uint)billboard.ParentID) != null) { var matrix = MyIDTracker <MyActor> .FindByID((uint)billboard.ParentID).WorldMatrix; Vector3D.Transform(ref pos0, ref matrix, out pos0); Vector3D.Transform(ref pos1, ref matrix, out pos1); Vector3D.Transform(ref pos2, ref matrix, out pos2); Vector3D.Transform(ref pos3, ref matrix, out pos3); } } if (billboard.CustomViewProjection != -1) { var billboardViewProjection = MyRenderProxy.BillboardsViewProjectionRead[billboard.CustomViewProjection]; //pos0 -= MyEnvironment.CameraPosition; //pos1 -= MyEnvironment.CameraPosition; //pos2 -= MyEnvironment.CameraPosition; //pos3 -= MyEnvironment.CameraPosition; } else { pos0 -= MyEnvironment.CameraPosition; pos1 -= MyEnvironment.CameraPosition; pos2 -= MyEnvironment.CameraPosition; pos3 -= MyEnvironment.CameraPosition; } var normal = Vector3.Cross(pos1 - pos0, pos2 - pos0); normal.Normalize(); billboardData.Normal = normal; m_vertexData[i * 4 + 0].Position = pos0; m_vertexData[i * 4 + 1].Position = pos1; m_vertexData[i * 4 + 2].Position = pos2; m_vertexData[i * 4 + 3].Position = pos3; var uv0 = new Vector2(material.UVOffset.X + billboard.UVOffset.X, material.UVOffset.Y + billboard.UVOffset.Y); var uv1 = new Vector2(material.UVOffset.X + material.UVSize.X + billboard.UVOffset.X, material.UVOffset.Y + billboard.UVOffset.Y); var uv2 = new Vector2(material.UVOffset.X + material.UVSize.X + billboard.UVOffset.X, material.UVOffset.Y + material.UVSize.Y + billboard.UVOffset.Y); var uv3 = new Vector2(material.UVOffset.X + billboard.UVOffset.X, material.UVOffset.Y + material.UVSize.Y + billboard.UVOffset.Y); if (material.UseAtlas) { var atlasItem = m_atlasedTextures[material.Texture]; uv0 = uv0 * new Vector2(atlasItem.UvOffsetScale.Z, atlasItem.UvOffsetScale.W) + new Vector2(atlasItem.UvOffsetScale.X, atlasItem.UvOffsetScale.Y); uv1 = uv1 * new Vector2(atlasItem.UvOffsetScale.Z, atlasItem.UvOffsetScale.W) + new Vector2(atlasItem.UvOffsetScale.X, atlasItem.UvOffsetScale.Y); uv2 = uv2 * new Vector2(atlasItem.UvOffsetScale.Z, atlasItem.UvOffsetScale.W) + new Vector2(atlasItem.UvOffsetScale.X, atlasItem.UvOffsetScale.Y); uv3 = uv3 * new Vector2(atlasItem.UvOffsetScale.Z, atlasItem.UvOffsetScale.W) + new Vector2(atlasItem.UvOffsetScale.X, atlasItem.UvOffsetScale.Y); } m_vertexData[i * 4 + 0].Texcoord = new HalfVector2(uv0); m_vertexData[i * 4 + 1].Texcoord = new HalfVector2(uv1); m_vertexData[i * 4 + 2].Texcoord = new HalfVector2(uv2); m_vertexData[i * 4 + 3].Texcoord = new HalfVector2(uv3); pos0.AssertIsValid(); pos1.AssertIsValid(); pos2.AssertIsValid(); pos3.AssertIsValid(); MyTriangleBillboard triBillboard = billboard as MyTriangleBillboard; if (triBillboard != null) { m_vertexData[i * 4 + 3].Position = pos2; // second triangle will die in rasterizer m_vertexData[i * 4 + 0].Texcoord = new HalfVector2(triBillboard.UV0); m_vertexData[i * 4 + 1].Texcoord = new HalfVector2(triBillboard.UV1); m_vertexData[i * 4 + 2].Texcoord = new HalfVector2(triBillboard.UV2); billboardData.Normal = triBillboard.Normal0; // pew pew pew :O } m_billboardData[i] = billboardData; bool closeBatch = (batchTexId != prevTexId) || ((i == m_sortedNum) && (i > 0)); if (closeBatch) { batch = new MyBillboardBatch(); batch.Offset = currentOffset; batch.Num = i - currentOffset; batch.Texture = prevTexId != TexId.NULL ? MyTextures.Views[prevTexId.Index] : null; batch.Lit = prevMaterial.CanBeAffectedByOtherLights; m_batches.Add(batch); currentOffset = i; } prevTexId = batchTexId; prevMaterial = material; } if (N > 0) { batch = new MyBillboardBatch(); batch.Offset = currentOffset; batch.Num = N - currentOffset; batch.Texture = prevTexId != TexId.NULL ? MyTextures.GetView(prevTexId) : null; batch.Lit = prevMaterial.CanBeAffectedByOtherLights; m_batches.Add(batch); } }
internal static ShaderResourceView GetAmbientBrdfLut() { return(MyTextures.GetView(MyTextures.GetTexture("Textures/Miscellaneous/ambient_brdf.dds", MyTextureEnum.CUSTOM, true))); }
internal unsafe static void RunForwardPostprocess(RenderTargetView rt, ShaderResourceView depth, ref Matrix viewMatrix, uint?atmosphereId) { var transpose = Matrix.Transpose(viewMatrix); var mapping = MyMapping.MapDiscard(RC.DeviceContext, MyCommon.ProjectionConstants); mapping.WriteAndPosition(ref transpose); mapping.Unmap(); RC.SetCB(MyCommon.FRAME_SLOT, MyCommon.FrameConstants); RC.SetCB(MyCommon.PROJECTION_SLOT, MyCommon.ProjectionConstants); RC.DeviceContext.OutputMerger.SetTargets(rt); RC.DeviceContext.PixelShader.SetShaderResource(0, depth); RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.SKYBOX_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.DaySkybox, MyTextureEnum.CUBEMAP, true))); RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.SKYBOX2_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.NightSkybox, MyTextureEnum.CUBEMAP, true))); RC.DeviceContext.PixelShader.SetSamplers(0, MyRender11.StandardSamplers); RC.DeviceContext.PixelShader.Set(m_ps); MyScreenPass.DrawFullscreenQuad(new MyViewport(256, 256)); if (atmosphereId != null) { var atmosphere = MyAtmosphereRenderer.GetAtmosphere(atmosphereId.Value); var constants = new AtmosphereConstants(); //TODO(AF) These values are computed in MyAtmosphere as well. Find a way to remove the duplication var worldMatrix = atmosphere.WorldMatrix; worldMatrix.Translation -= MyEnvironment.CameraPosition; double distance = worldMatrix.Translation.Length(); double atmosphereTop = atmosphere.AtmosphereRadius * atmosphere.Settings.AtmosphereTopModifier * atmosphere.PlanetScaleFactor * atmosphere.Settings.RayleighTransitionModifier; float rayleighHeight = atmosphere.Settings.RayleighHeight; float t = 0.0f; if (distance > atmosphereTop) { if (distance > atmosphereTop * 2.0f) { t = 1.0f; } else { t = (float)((distance - atmosphereTop) / atmosphereTop); } } rayleighHeight = MathHelper.Lerp(atmosphere.Settings.RayleighHeight, atmosphere.Settings.RayleighHeightSpace, t); constants.PlanetCentre = (Vector3)worldMatrix.Translation; constants.AtmosphereRadius = atmosphere.AtmosphereRadius * atmosphere.Settings.AtmosphereTopModifier; constants.GroundRadius = atmosphere.PlanetRadius * 1.01f * atmosphere.Settings.SeaLevelModifier; constants.BetaRayleighScattering = atmosphere.BetaRayleighScattering / atmosphere.Settings.RayleighScattering; constants.BetaMieScattering = atmosphere.BetaMieScattering / atmosphere.Settings.MieColorScattering; constants.HeightScaleRayleighMie = atmosphere.HeightScaleRayleighMie * new Vector2(rayleighHeight, atmosphere.Settings.MieHeight); constants.MieG = atmosphere.Settings.MieG; constants.PlanetScaleFactor = atmosphere.PlanetScaleFactor; constants.AtmosphereScaleFactor = atmosphere.AtmosphereScaleFactor; constants.Intensity = atmosphere.Settings.Intensity; constants.FogIntensity = atmosphere.Settings.FogIntensity; var cb = MyCommon.GetObjectCB(sizeof(AtmosphereConstants)); mapping = MyMapping.MapDiscard(RC.DeviceContext, cb); mapping.WriteAndPosition(ref constants); mapping.Unmap(); RC.SetBS(MyRender11.BlendAdditive); RC.SetCB(2, cb); RC.DeviceContext.PixelShader.SetShaderResource(2, MyAtmosphereRenderer.GetAtmosphereLuts(atmosphereId.Value).TransmittanceLut.ShaderView); RC.DeviceContext.PixelShader.Set(m_atmosphere); MyScreenPass.DrawFullscreenQuad(new MyViewport(MyEnvironmentProbe.CubeMapResolution, MyEnvironmentProbe.CubeMapResolution)); } RC.DeviceContext.OutputMerger.SetTargets(null as RenderTargetView); }
unsafe static void DrawBatches(MyRenderContext RC, MyStringId material, int matIndex, bool transparent) { if (m_jobs.Count == 0) { return; } var matDesc = m_materials[material][matIndex]; MyScreenDecalType type = matDesc.DecalType; if (transparent) { // Always fallback to colormap for transparent surface decals type = MyScreenDecalType.ColorMap; } switch (type) { case MyScreenDecalType.NormalMap: BindResources(RC); RC.SetPS(m_psNormalMap); RC.SetBS(MyRender11.BlendDecalNormal); break; case MyScreenDecalType.ColorMap: if (transparent) { BindResourcesTransparentBillboards(RC); RC.SetPS(m_psColorMapTransparent); } else { BindResources(RC); RC.SetPS(m_psColorMap); RC.SetBS(MyRender11.BlendDecalColor); } break; case MyScreenDecalType.NormalColorMap: BindResources(RC); RC.SetPS(m_psNormalColorMap); RC.SetBS(MyRender11.BlendDecalNormalColor); break; case MyScreenDecalType.NormalColorExtMap: BindResources(RC); RC.SetPS(m_psNormalColorExtMap); RC.SetBS(MyRender11.BlendDecalNormalColorExt); break; default: throw new Exception("Unknown decal type"); } // factor 1 makes overwriting of gbuffer color & subtracting from ao RC.DeviceContext.PixelShader.SetShaderResource(3, MyTextures.GetView(matDesc.AlphamaskTexture)); RC.DeviceContext.PixelShader.SetShaderResource(4, MyTextures.GetView(matDesc.ColorMetalTexture)); RC.DeviceContext.PixelShader.SetShaderResource(5, MyTextures.GetView(matDesc.NormalmapTexture)); RC.DeviceContext.PixelShader.SetShaderResource(6, MyTextures.GetView(matDesc.ExtensionsTexture)); var decalCb = MyCommon.GetObjectCB(sizeof(MyDecalConstants) * DECAL_BATCH_SIZE); int batchCount = m_jobs.Count / DECAL_BATCH_SIZE + 1; int offset = 0; for (int i1 = 0; i1 < batchCount; i1++) { var mapping = MyMapping.MapDiscard(decalCb); int leftDecals = m_jobs.Count - offset; int decalCount = leftDecals > DECAL_BATCH_SIZE ? DECAL_BATCH_SIZE : leftDecals; for (int i2 = 0; i2 < decalCount; ++i2) { MyDecalConstants constants = new MyDecalConstants(); EncodeJobConstants(i2, ref constants); mapping.WriteAndPosition(ref constants); } mapping.Unmap(); // Draw a box without buffer: 36 vertices -> 12 triangles. 2 triangles per face -> 6 faces MyImmediateRC.RC.DeviceContext.DrawIndexed(36 * decalCount, 0, 0); offset += DECAL_BATCH_SIZE; } }
unsafe static void DrawBatches(MyRenderContext RC, MyStringId material) { if (m_matrices.Count == 0) { return; } var matDesc = m_materials[material]; switch (matDesc.DecalType) { case MyScreenDecalType.NormalMap: BindResources(RC, false); RC.SetPS(m_psNormalMap); RC.SetBS(MyRender11.BlendDecalNormal); break; case MyScreenDecalType.ColorMap: BindResources(RC, true); RC.SetPS(m_psColorMap); RC.SetBS(MyRender11.BlendDecalColor); break; case MyScreenDecalType.NormalColorMap: BindResources(RC, false); RC.SetPS(m_psNormalColorMap); RC.SetBS(MyRender11.BlendDecalNormalColor); break; default: throw new Exception("Unknown decal type"); } // factor 1 makes overwriting of gbuffer color & subtracting from ao RC.DeviceContext.PixelShader.SetShaderResource(3, MyTextures.GetView(matDesc.AlphamaskTexture)); RC.DeviceContext.PixelShader.SetShaderResource(4, MyTextures.GetView(matDesc.ColorMetalTexture)); RC.DeviceContext.PixelShader.SetShaderResource(5, MyTextures.GetView(matDesc.NormalmapTexture)); var decalCb = MyCommon.GetObjectCB(sizeof(MyDecalConstants) * DECAL_BATCH_SIZE); int batchCount = m_matrices.Count / DECAL_BATCH_SIZE + 1; int offset = 0; for (int i1 = 0; i1 < batchCount; i1++) { var mapping = MyMapping.MapDiscard(decalCb); int leftDecals = m_matrices.Count - offset; int decalCount = leftDecals > DECAL_BATCH_SIZE ? DECAL_BATCH_SIZE : leftDecals; for (int i2 = 0; i2 < decalCount; ++i2) { Matrix worldMatrix = Matrix.Transpose(m_matrices[i2]); Matrix transposeInverseMatrix = Matrix.Transpose(Matrix.Invert(m_matrices[i2])); mapping.WriteAndPosition(ref worldMatrix); mapping.WriteAndPosition(ref transposeInverseMatrix); } mapping.Unmap(); // Draw a box without buffer: 36 vertices -> 12 triangles. 2 triangles per face -> 6 faces MyImmediateRC.RC.DeviceContext.DrawIndexed(36 * decalCount, 0, 0); offset += DECAL_BATCH_SIZE; } m_matrices.Clear(); }
internal unsafe static void Render(MyBindableResource dst, MyBindableResource depth, MyBindableResource depthRead) { if (!MyRender11.DebugOverrides.BillboardsDynamic) { OnFrameStart(); } m_stats.Clear(); MyRender11.GetRenderProfiler().StartProfilingBlock("Gather"); Gather(); MyRender11.GetRenderProfiler().EndProfilingBlock(); MyRender11.GetRenderProfiler().StartProfilingBlock("Draw"); TransferData(); RC.SetupScreenViewport(); RC.BindDepthRT(depth, DepthStencilAccess.ReadOnly, dst); RC.SetBS(MyRender11.BlendAlphaPremult); RC.SetRS(MyRender11.m_nocullRasterizerState); RC.BindRawSRV(104, m_SB); RC.BindSRV(1, depthRead); RC.SetCB(2, MyCommon.GetObjectCB(sizeof(Matrix) * MaxCustomProjections)); RC.SetDS(MyDepthStencilState.DefaultDepthState); RC.SetCB(4, MyRender11.DynamicShadows.ShadowCascades.CascadeConstantBuffer); RC.DeviceContext.VertexShader.SetSampler(MyCommon.SHADOW_SAMPLER_SLOT, SamplerStates.m_shadowmap); RC.DeviceContext.VertexShader.SetShaderResource(MyCommon.CASCADES_SM_SLOT, MyRender11.DynamicShadows.ShadowCascades.CascadeShadowmapArray.SRV); RC.DeviceContext.VertexShader.SetSamplers(0, SamplerStates.StandardSamplers); RC.DeviceContext.VertexShader.SetShaderResource(MyCommon.SKYBOX_IBL_SLOT, MyRender11.IsIntelBrokenCubemapsWorkaround ? MyTextures.GetView(MyTextures.IntelFallbackCubeTexId) : MyEnvironmentProbe.Instance.cubemapPrefiltered.SRV); RC.DeviceContext.VertexShader.SetShaderResource(MyCommon.SKYBOX2_IBL_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.NightSkyboxPrefiltered, MyTextureEnum.CUBEMAP, true))); RC.SetVB(0, m_VB.Buffer, m_VB.Stride); RC.SetIB(m_IB.Buffer, m_IB.Format); RC.SetIL(m_inputLayout); for (int i = 0; i < m_batches.Count; i++) { // first part of batches contain sorted billboards and they read depth // second part of batches contain unsorted billboards and they ignore depth // switch here: if (m_batches[i].Offset == m_sortedBillboardsNum) { //RC.BindDepthRT(null, DepthStencilAccess.ReadOnly, dst); } if (m_batches[i].Lit) { RC.SetVS(m_vsLit); if (m_batches[i].AlphaCutout) { RC.SetPS(m_psAlphaCutoutAndLit); } else { RC.SetPS(m_psLit); } } else if (m_batches[i].AlphaCutout) { RC.SetVS(m_vs); RC.SetPS(m_psAlphaCutout); } else { RC.SetVS(m_vs); RC.SetPS(m_ps); } RC.BindRawSRV(0, m_batches[i].Texture); RC.DeviceContext.DrawIndexed(m_batches[i].Num * 6, m_batches[i].Offset * 6, 0); ++RC.Stats.BillboardDrawIndexed; } m_stats.Billboards += m_sorted + m_unsorted; RC.SetRS(null); RC.SetBS(null); m_batches.Clear(); MyRender11.GatherStats(m_stats); MyRender11.GetRenderProfiler().EndProfilingBlock(); }
// can be on another job internal unsafe static void Draw() { var decals = IdIndex.Values.ToArray(); // sort visible decals by material Array.Sort(decals, DecalsMaterialComparer); /// // copy gbuffer with normals for read (uhoh) // bind copy and depth for read // bind gbuffer for write var RC = MyImmediateRC.RC; RC.Context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; RC.SetIB(m_IB.Buffer, m_IB.Format); RC.SetIL(null); RC.Context.Rasterizer.SetViewport(0, 0, MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y); RC.SetCB(MyCommon.FRAME_SLOT, MyCommon.FrameConstants); RC.BindDepthRT( MyGBuffer.Main.Get(MyGbufferSlot.DepthStencil), DepthStencilAccess.DepthReadOnly, MyGBuffer.Main.Get(MyGbufferSlot.GBuffer0), MyGBuffer.Main.Get(MyGbufferSlot.GBuffer1), MyGBuffer.Main.Get(MyGbufferSlot.GBuffer2)); RC.SetVS(m_vs); RC.SetPS(m_ps); RC.SetDS(MyDepthStencilState.DepthTest); RC.Context.PixelShader.SetSamplers(0, MyRender11.StandardSamplers); RC.BindSRV(0, MyGBuffer.Main.DepthStencil.Depth); RC.Context.PixelShader.SetShaderResources(1, MyRender11.m_gbuffer1Copy.ShaderView); var decalCb = MyCommon.GetObjectCB(sizeof(MyDecalConstants) * MAX_DECALS); RC.SetCB(2, decalCb); var prevMaterial = new MyStringId(); MyScreenDecalType decalType = MyScreenDecalType.ScreenDecalBump; for (int i = 0; i < decals.Length; ++i) { var index = decals[i]; var material = Decals.Data[index].Material; if (i == 0 || material != prevMaterial) { DrawBatch(decalType); var matDesc = Materials[material]; decalType = matDesc.DecalType; // factor 1 makes overwriting of gbuffer color & subtracting from ao RC.SetBS(MyRender11.BlendDecal, matDesc.DecalType == MyScreenDecalType.ScreenDecalBump ? new SharpDX.Color4(0) : SharpDX.Color4.White); RC.Context.PixelShader.SetShaderResources(3, MyTextures.GetView(matDesc.AlphamaskTexture), MyTextures.GetView(matDesc.ColorMetalTexture), MyTextures.GetView(matDesc.NormalmapTexture)); } var parent = MyIDTracker <MyActor> .FindByID(Decals.Data[index].ParentID); if (parent != null) { var parentMatrix = parent.WorldMatrix; var volumeMatrix = Decals.Data[index].LocalOBB * parentMatrix * Matrix.CreateTranslation(-MyEnvironment.CameraPosition); m_matrices.Add(volumeMatrix); } } DrawBatch(decalType); RC.SetBS(null); }
internal static void RenderColoredTextures(List <renderColoredTextureProperties> texturesToRender) { if (texturesToRender.Count == 0) { return; } if (!m_initialized) { Init(); } const int RENDER_TEXTURE_RESOLUTION = 512; RC.DeviceContext.OutputMerger.BlendState = null; RC.SetIL(null); RC.SetPS(m_ps); RC.SetCB(0, MyCommon.FrameConstants); RC.SetCB(1, m_cb); Dictionary <Vector2I, MyRenderTarget> createdRenderTextureTargets = new Dictionary <Vector2I, MyRenderTarget>(); foreach (var texture in texturesToRender) { TexId texId = MyTextures.GetTexture(texture.TextureName, MyTextureEnum.COLOR_METAL, true); if (texId == TexId.NULL) { continue; } Vector2 texSize = MyTextures.GetSize(texId); Vector2I renderTargetResolution = new Vector2I(RENDER_TEXTURE_RESOLUTION, RENDER_TEXTURE_RESOLUTION); if (texSize.Y > 0) { if (texSize.Y < RENDER_TEXTURE_RESOLUTION) { renderTargetResolution.X = (int)texSize.X; renderTargetResolution.Y = (int)texSize.Y; } else { renderTargetResolution.X *= (int)(texSize.X / texSize.Y); } } MyViewport viewport = new MyViewport(renderTargetResolution.X, renderTargetResolution.Y); MyRenderTarget renderTexture = null; if (!createdRenderTextureTargets.TryGetValue(renderTargetResolution, out renderTexture)) { renderTexture = new MyRenderTarget(renderTargetResolution.X, renderTargetResolution.Y, SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb, 1, 0); createdRenderTextureTargets[renderTargetResolution] = renderTexture; } RC.BindDepthRT(null, DepthStencilAccess.ReadWrite, renderTexture); // Set color var mapping = MyMapping.MapDiscard(m_cb); Vector4 color = new Vector4(texture.ColorMaskHSV, 1); mapping.WriteAndPosition(ref color); mapping.Unmap(); // Set texture RC.DeviceContext.PixelShader.SetShaderResource(0, MyTextures.GetView(texId)); // Draw MyScreenPass.DrawFullscreenQuad(viewport); // Save to file MyTextureData.ToFile(renderTexture.GetHWResource(), texture.PathToSave, ImageFileFormat.Png); } texturesToRender.Clear(); foreach (var texture in createdRenderTextureTargets) { texture.Value.Release(); } createdRenderTextureTargets.Clear(); RC.BindDepthRT(null, DepthStencilAccess.ReadWrite, null); RC.BindGBufferForRead(0, MyGBuffer.Main); }
internal unsafe static void RenderSpotlights() { RC.BindDepthRT(MyGBuffer.Main.Get(MyGbufferSlot.DepthStencil), DepthStencilAccess.ReadOnly, MyGBuffer.Main.Get(MyGbufferSlot.LBuffer)); RC.DeviceContext.Rasterizer.SetViewport(0, 0, MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y); RC.DeviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; var coneMesh = MyMeshes.GetMeshId(X.TEXT("Models/Debug/Cone.mwm")); var buffers = MyMeshes.GetLodMesh(coneMesh, 0).Buffers; RC.SetVB(0, buffers.VB0.Buffer, buffers.VB0.Stride); RC.SetIB(buffers.IB.Buffer, buffers.IB.Format); RC.SetVS(SpotlightProxyVs); RC.SetIL(SpotlightProxyIL); RC.SetRS(MyRender11.m_invTriRasterizerState); var cb = MyCommon.GetObjectCB(sizeof(SpotlightConstants)); RC.SetCB(1, cb); RC.DeviceContext.PixelShader.SetSampler(13, MyRender11.m_alphamaskSamplerState); RC.DeviceContext.PixelShader.SetSampler(14, MyRender11.m_shadowmapSamplerState); RC.DeviceContext.PixelShader.SetSampler(15, MyRender11.m_shadowmapSamplerState); int index = 0; int casterIndex = 0; foreach (var id in VisibleSpotlights) { MyLights.WriteSpotlightConstants(id, ref Spotlights[index]); var mapping = MyMapping.MapDiscard(cb); mapping.WriteAndPosition(ref Spotlights[index]); mapping.Unmap(); RC.DeviceContext.PixelShader.SetShaderResource(13, MyTextures.GetView(MyLights.Spotlights[id.Index].ReflectorTexture)); if (id.CastsShadowsThisFrame) { RC.DeviceContext.PixelShader.SetShaderResource(14, MyRender11.DynamicShadows.ShadowmapsPool[casterIndex].ShaderView); casterIndex++; } RC.SetPS(SpotlightPs_Pixel); if (MyRender11.MultisamplingEnabled) { RC.SetDS(MyDepthStencilState.TestEdgeStencil, 0); } RC.DeviceContext.DrawIndexed(MyMeshes.GetLodMesh(coneMesh, 0).Info.IndicesNum, 0, 0); if (MyRender11.MultisamplingEnabled) { RC.SetPS(SpotlightPs_Sample); RC.SetDS(MyDepthStencilState.TestEdgeStencil, 0x80); RC.DeviceContext.DrawIndexed(MyMeshes.GetLodMesh(coneMesh, 0).Info.IndicesNum, 0, 0); } index++; if (index >= SPOTLIGHTS_MAX) { break; } } if (MyRender11.MultisamplingEnabled) { RC.SetDS(MyDepthStencilState.DefaultDepthState); } RC.SetRS(null); }
internal static unsafe void Render() { if (m_cloudLayers.Count == 0) { return; } var immediateContext = MyImmediateRC.RC; immediateContext.SetVS(m_proxyVs); immediateContext.SetPS(m_cloudPs); immediateContext.SetIL(m_proxyIL); immediateContext.SetRS(MyRender11.m_nocullRasterizerState); immediateContext.SetBS(MyRender11.BlendTransparent); immediateContext.SetDS(MyDepthStencilState.DepthTest); var cb = MyCommon.GetObjectCB(sizeof(CloudsConstants)); immediateContext.SetCB(1, cb); immediateContext.DeviceContext.PixelShader.SetSamplers(0, m_textureSampler); immediateContext.BindDepthRT(MyGBuffer.Main.Get(MyGbufferSlot.DepthStencil), DepthStencilAccess.ReadOnly, MyGBuffer.Main.Get(MyGbufferSlot.LBuffer)); m_cloudLayers.OrderByDescending(x => { MyCloudLayer cloudLayer = x.Value; Vector3D cameraToLayer = cloudLayer.CenterPoint - MyEnvironment.CameraPosition; Vector3D layerToCameraDirection = -Vector3D.Normalize(cameraToLayer); return((cameraToLayer + layerToCameraDirection * cloudLayer.Altitude).Length()); }); foreach (var cloudLayer in m_cloudLayers) { var modifiableData = m_modifiableCloudLayerData[cloudLayer.Key]; int currentGameplayFrame = MyRender11.Settings.GameplayFrame; var increment = cloudLayer.Value.AngularVelocity * (float)(currentGameplayFrame - modifiableData.LastGameplayFrameUpdate) / 10.0f; modifiableData.RadiansAroundAxis += increment; // Constant for backward compatibility if (modifiableData.RadiansAroundAxis >= 2 * Math.PI) { modifiableData.RadiansAroundAxis -= 2 * Math.PI; } modifiableData.LastGameplayFrameUpdate = currentGameplayFrame; double scaledAltitude = cloudLayer.Value.Altitude; Vector3D centerPoint = cloudLayer.Value.CenterPoint; Vector3D cameraPosition = MyEnvironment.CameraPosition; double cameraDistanceFromCenter = (centerPoint - cameraPosition).Length(); if (cloudLayer.Value.ScalingEnabled) { double threshold = cloudLayer.Value.Altitude * 0.95; if (cameraDistanceFromCenter > threshold) { scaledAltitude = MathHelper.Clamp(scaledAltitude * (1 - MathHelper.Clamp((cameraDistanceFromCenter - threshold) / (threshold * 1.5), 0.0, 1.0)), cloudLayer.Value.MinScaledAltitude, cloudLayer.Value.Altitude); } } MatrixD worldMatrix = MatrixD.CreateScale(scaledAltitude) * MatrixD.CreateFromAxisAngle(cloudLayer.Value.RotationAxis, (float)modifiableData.RadiansAroundAxis); worldMatrix.Translation = cloudLayer.Value.CenterPoint; worldMatrix.Translation -= MyEnvironment.CameraPosition; float layerAlpha = 1.0f; double currentRelativeAltitude = (cameraDistanceFromCenter - cloudLayer.Value.MinScaledAltitude) / (cloudLayer.Value.MaxPlanetHillRadius - cloudLayer.Value.MinScaledAltitude); if (cloudLayer.Value.FadeOutRelativeAltitudeStart > cloudLayer.Value.FadeOutRelativeAltitudeEnd) { layerAlpha = (float)MathHelper.Clamp(1.0 - (cloudLayer.Value.FadeOutRelativeAltitudeStart - currentRelativeAltitude) / (cloudLayer.Value.FadeOutRelativeAltitudeStart - cloudLayer.Value.FadeOutRelativeAltitudeEnd), 0.0, 1.0); } else if (cloudLayer.Value.FadeOutRelativeAltitudeStart < cloudLayer.Value.FadeOutRelativeAltitudeEnd) { layerAlpha = (float)MathHelper.Clamp(1.0 - (currentRelativeAltitude - cloudLayer.Value.FadeOutRelativeAltitudeStart) / (cloudLayer.Value.FadeOutRelativeAltitudeEnd - cloudLayer.Value.FadeOutRelativeAltitudeStart), 0.0, 1.0); } Vector4 layerColor = new Vector4(1, 1, 1, layerAlpha); var constants = new CloudsConstants(); constants.World = MatrixD.Transpose(worldMatrix); constants.ViewProj = MatrixD.Transpose(MyEnvironment.ViewProjectionAt0); constants.Color = layerColor; var mapping = MyMapping.MapDiscard(cb); mapping.WriteAndPosition(ref constants); mapping.Unmap(); MeshId sphereMesh = cloudLayer.Value.Mesh; LodMeshId lodMesh = MyMeshes.GetLodMesh(sphereMesh, 0); MyMeshBuffers buffers = lodMesh.Buffers; immediateContext.DeviceContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(buffers.VB0.Buffer, buffers.VB0.Stride, 0)); immediateContext.DeviceContext.InputAssembler.SetVertexBuffers(1, new VertexBufferBinding(buffers.VB1.Buffer, buffers.VB1.Stride, 0)); immediateContext.SetIB(buffers.IB.Buffer, buffers.IB.Format); immediateContext.DeviceContext.PixelShader.SetShaderResource(0, MyTextures.GetView(cloudLayer.Value.TextureInfo.ColorMetalTexture)); immediateContext.DeviceContext.PixelShader.SetShaderResource(1, MyTextures.GetView(cloudLayer.Value.TextureInfo.AlphaTexture)); immediateContext.DeviceContext.PixelShader.SetShaderResource(2, MyTextures.GetView(cloudLayer.Value.TextureInfo.NormalGlossTexture)); immediateContext.DeviceContext.DrawIndexed(lodMesh.Info.IndicesNum, 0, 0); } immediateContext.DeviceContext.PixelShader.SetShaderResource(0, null); immediateContext.DeviceContext.PixelShader.SetShaderResource(1, null); immediateContext.DeviceContext.PixelShader.SetShaderResource(2, null); immediateContext.SetDS(null); immediateContext.SetBS(null); immediateContext.SetRS(null); }