/// <summary> /// Main drawing method for this renderer that must be implemented. /// </summary> /// <param name="context">The context.</param> protected abstract void DrawCore(RenderDrawContext context);
/// <inheritdoc/> public override void Prepare(RenderDrawContext context) { EffectObjectNodes.Clear(false); // Make sure descriptor set pool is large enough var expectedDescriptorSetPoolSize = RenderNodes.Count * effectDescriptorSetSlots.Count; if (ResourceGroupPool.Length < expectedDescriptorSetPoolSize) { Array.Resize(ref ResourceGroupPool, expectedDescriptorSetPoolSize); } // Allocate PerFrame, PerView and PerDraw resource groups and constant buffers var renderEffects = RenderData.GetData(RenderEffectKey); int effectSlotCount = EffectPermutationSlotCount; foreach (var view in RenderSystem.Views) { var viewFeature = view.Features[Index]; Dispatcher.ForEach(viewFeature.RenderNodes, () => prepareThreadContext.Value, (renderNodeReference, batch) => { var threadContext = batch.Context; var renderNode = this.GetRenderNode(renderNodeReference); var renderObject = renderNode.RenderObject; // Get RenderEffect var staticObjectNode = renderObject.StaticObjectNode; var staticEffectObjectNode = staticObjectNode * effectSlotCount + effectSlots[renderNode.RenderStage.Index].Index; var renderEffect = renderEffects[staticEffectObjectNode]; // Not compiled yet? if (renderEffect.Effect == null) { renderNode.RenderEffect = renderEffect; renderNode.EffectObjectNode = EffectObjectNodeReference.Invalid; renderNode.Resources = null; RenderNodes[renderNodeReference.Index] = renderNode; return; } var renderEffectReflection = renderEffect.Reflection; // PerView resources/cbuffer var viewLayout = renderEffectReflection.PerViewLayout; if (viewLayout != null) { var viewCount = RenderSystem.Views.Count; if (viewLayout.Entries?.Length < viewCount) { // TODO: Should this be a first loop? lock (viewLayout) { if (viewLayout.Entries?.Length < viewCount) { var newEntries = new ResourceGroupEntry[viewCount]; for (int index = 0; index < viewLayout.Entries.Length; index++) { newEntries[index] = viewLayout.Entries[index]; } for (int index = viewLayout.Entries.Length; index < viewCount; index++) { newEntries[index].Resources = new ResourceGroup(); } viewLayout.Entries = newEntries; } } } if (viewLayout.Entries[view.Index].MarkAsUsed(RenderSystem)) { threadContext.ResourceGroupAllocator.PrepareResourceGroup(viewLayout, BufferPoolAllocationType.UsedMultipleTimes, viewLayout.Entries[view.Index].Resources); // Register it in list of view layouts to update for this frame viewFeature.Layouts.Add(viewLayout); } } // PerFrame resources/cbuffer var frameLayout = renderEffect.Reflection.PerFrameLayout; if (frameLayout != null && frameLayout.Entry.MarkAsUsed(RenderSystem)) { threadContext.ResourceGroupAllocator.PrepareResourceGroup(frameLayout, BufferPoolAllocationType.UsedMultipleTimes, frameLayout.Entry.Resources); // Register it in list of view layouts to update for this frame FrameLayouts.Add(frameLayout); } // PerDraw resources/cbuffer // Get nodes var viewObjectNode = GetViewObjectNode(renderNode.ViewObjectNode); // Allocate descriptor set renderNode.Resources = threadContext.ResourceGroupAllocator.AllocateResourceGroup(); if (renderEffectReflection.PerDrawLayout != null) { threadContext.ResourceGroupAllocator.PrepareResourceGroup(renderEffectReflection.PerDrawLayout, BufferPoolAllocationType.UsedOnce, renderNode.Resources); } // Create EffectObjectNode var effectObjectNodeIndex = EffectObjectNodes.Add(new EffectObjectNode(renderEffect, viewObjectNode.ObjectNode)); // Link to EffectObjectNode (created right after) // TODO: rewrite this renderNode.EffectObjectNode = new EffectObjectNodeReference(effectObjectNodeIndex); renderNode.RenderEffect = renderEffect; // Bind well-known descriptor sets var descriptorSetPoolOffset = ComputeResourceGroupOffset(renderNodeReference); ResourceGroupPool[descriptorSetPoolOffset + perFrameDescriptorSetSlot.Index] = frameLayout?.Entry.Resources; ResourceGroupPool[descriptorSetPoolOffset + perViewDescriptorSetSlot.Index] = renderEffect.Reflection.PerViewLayout?.Entries[view.Index].Resources; ResourceGroupPool[descriptorSetPoolOffset + perDrawDescriptorSetSlot.Index] = renderNode.Resources; // Create resource group for everything else in case of fallback effects if (renderEffect.State != RenderEffectState.Normal && renderEffect.FallbackParameters != null) { if (renderEffect.FallbackParameterUpdater.ResourceGroups == null) { // First time renderEffect.FallbackParameterUpdater = new EffectParameterUpdater(renderEffect.Reflection.FallbackUpdaterLayout, renderEffect.FallbackParameters); } renderEffect.FallbackParameterUpdater.Update(RenderSystem.GraphicsDevice, threadContext.ResourceGroupAllocator, renderEffect.FallbackParameters); var fallbackResourceGroupMapping = renderEffect.Reflection.FallbackResourceGroupMapping; for (int i = 0; i < fallbackResourceGroupMapping.Length; ++i) { ResourceGroupPool[descriptorSetPoolOffset + fallbackResourceGroupMapping[i]] = renderEffect.FallbackParameterUpdater.ResourceGroups[i]; } } // Compile pipeline state object (if first time or need change) // TODO GRAPHICS REFACTOR how to invalidate if we want to change some state? (setting to null should be fine) if (renderEffect.PipelineState == null) { var mutablePipelineState = batch.MutablePipelineState; var pipelineState = mutablePipelineState.State; pipelineState.SetDefaults(); // Effect pipelineState.EffectBytecode = renderEffect.Effect.Bytecode; pipelineState.RootSignature = renderEffect.Reflection.RootSignature; // Extract outputs from render stage pipelineState.Output = renderNode.RenderStage.Output; pipelineState.RasterizerState.MultisampleCount = renderNode.RenderStage.Output.MultisampleCount; // Bind VAO ProcessPipelineState(Context, renderNodeReference, ref renderNode, renderObject, pipelineState); foreach (var pipelineProcessor in PipelineProcessors) { pipelineProcessor.Process(renderNodeReference, ref renderNode, renderObject, pipelineState); } mutablePipelineState.Update(); renderEffect.PipelineState = mutablePipelineState.CurrentState; } RenderNodes[renderNodeReference.Index] = renderNode; }); viewFeature.RenderNodes.Close(); viewFeature.Layouts.Close(); } EffectObjectNodes.Close(); FrameLayouts.Close(); }
/// <param name="context"></param> /// <inheritdoc/> public override void PrepareEffectPermutations(RenderDrawContext context) { base.PrepareEffectPermutations(context); // TODO: Temporary until we have a better system for handling permutations var renderEffects = RenderData.GetData(RenderEffectKey); int effectSlotCount = EffectPermutationSlotCount; Dispatcher.ForEach(RenderSystem.Views, view => { var viewFeature = view.Features[Index]; Dispatcher.ForEach(viewFeature.RenderNodes, renderNodeReference => { var renderNode = this.GetRenderNode(renderNodeReference); var renderObject = renderNode.RenderObject; // Get RenderEffect var staticObjectNode = renderObject.StaticObjectNode; var staticEffectObjectNode = staticObjectNode * effectSlotCount + effectSlots[renderNode.RenderStage.Index].Index; var renderEffect = renderEffects[staticEffectObjectNode]; var effectSelector = renderObject.ActiveRenderStages[renderNode.RenderStage.Index].EffectSelector; // Create it (first time) or regenerate it if effect changed if (renderEffect == null || effectSelector != renderEffect.EffectSelector) { renderEffect = new RenderEffect(renderObject.ActiveRenderStages[renderNode.RenderStage.Index].EffectSelector); renderEffects[staticEffectObjectNode] = renderEffect; } // Is it the first time this frame that we check this RenderEffect? if (renderEffect.MarkAsUsed(RenderSystem)) { renderEffect.EffectValidator.BeginEffectValidation(); } }); }); // Step1: Perform permutations PrepareEffectPermutationsImpl(context); PrepareRenderTargetExtensionsMixins(context); var currentTime = DateTime.UtcNow; // Step2: Compile effects Dispatcher.ForEach(RenderObjects, renderObject => { //var renderObject = RenderObjects[index]; var staticObjectNode = renderObject.StaticObjectNode; for (int i = 0; i < effectSlotCount; ++i) { var staticEffectObjectNode = staticObjectNode * effectSlotCount + i; var renderEffect = renderEffects[staticEffectObjectNode]; // Skip if not used if (renderEffect == null) { continue; } // Skip reflection update unless a state change requires it renderEffect.IsReflectionUpdateRequired = false; if (!renderEffect.IsUsedDuringThisFrame(RenderSystem)) { continue; } // Skip if nothing changed if (renderEffect.EffectValidator.ShouldSkip) { // Reset pending effect, as it is now obsolete anyway renderEffect.Effect = null; renderEffect.State = RenderEffectState.Skip; } else if (renderEffect.EffectValidator.EndEffectValidation() && (renderEffect.Effect == null || !renderEffect.Effect.SourceChanged) && !(renderEffect.State == RenderEffectState.Error && currentTime >= renderEffect.RetryTime)) { InvalidateEffectPermutation(renderObject, renderEffect); // Still, let's check if there is a pending effect compiling var pendingEffect = renderEffect.PendingEffect; if (pendingEffect == null || !pendingEffect.IsCompleted) { continue; } renderEffect.ClearFallbackParameters(); if (pendingEffect.IsFaulted) { // The effect can fail compilation asynchronously renderEffect.State = RenderEffectState.Error; renderEffect.Effect = ComputeFallbackEffect?.Invoke(renderObject, renderEffect, RenderEffectState.Error); } else { renderEffect.State = RenderEffectState.Normal; renderEffect.Effect = pendingEffect.Result; } renderEffect.PendingEffect = null; } else { // Reset pending effect, as it is now obsolete anyway renderEffect.PendingEffect = null; renderEffect.State = RenderEffectState.Normal; // CompilerParameters are ThreadStatic if (staticCompilerParameters == null) { staticCompilerParameters = new CompilerParameters(); } foreach (var effectValue in renderEffect.EffectValidator.EffectValues) { staticCompilerParameters.SetObject(effectValue.Key, effectValue.Value); } TaskOrResult <Effect> asyncEffect; try { // The effect can fail compilation synchronously asyncEffect = RenderSystem.EffectSystem.LoadEffect(renderEffect.EffectSelector.EffectName, staticCompilerParameters); staticCompilerParameters.Clear(); } catch { staticCompilerParameters.Clear(); renderEffect.ClearFallbackParameters(); renderEffect.State = RenderEffectState.Error; renderEffect.Effect = ComputeFallbackEffect?.Invoke(renderObject, renderEffect, RenderEffectState.Error); continue; } renderEffect.Effect = asyncEffect.Result; if (renderEffect.Effect == null) { // Effect still compiling, let's find if there is a fallback renderEffect.ClearFallbackParameters(); renderEffect.PendingEffect = asyncEffect.Task; renderEffect.State = RenderEffectState.Compiling; renderEffect.Effect = ComputeFallbackEffect?.Invoke(renderObject, renderEffect, RenderEffectState.Compiling); } } renderEffect.IsReflectionUpdateRequired = true; } }); // Step3: Uupdate reflection infos (offset, etc...) foreach (var renderObject in RenderObjects) { var staticObjectNode = renderObject.StaticObjectNode; for (int i = 0; i < effectSlotCount; ++i) { var staticEffectObjectNode = staticObjectNode * effectSlotCount + i; var renderEffect = renderEffects[staticEffectObjectNode]; // Skip if not used if (renderEffect == null || !renderEffect.IsReflectionUpdateRequired) { continue; } var effect = renderEffect.Effect; if (effect == null && renderEffect.State == RenderEffectState.Compiling) { // Need to wait for completion because we have nothing else renderEffect.PendingEffect.Wait(); if (!renderEffect.PendingEffect.IsFaulted) { renderEffect.Effect = effect = renderEffect.PendingEffect.Result; renderEffect.State = RenderEffectState.Normal; } else { renderEffect.ClearFallbackParameters(); renderEffect.State = RenderEffectState.Error; renderEffect.Effect = effect = ComputeFallbackEffect?.Invoke(renderObject, renderEffect, RenderEffectState.Error); } } var effectHashCode = effect != null ? (uint)effect.GetHashCode() : 0; // Effect is last 16 bits renderObject.StateSortKey = (renderObject.StateSortKey & 0xFFFF0000) | (effectHashCode & 0x0000FFFF); if (effect != null) { RenderEffectReflection renderEffectReflection; if (!InstantiatedEffects.TryGetValue(effect, out renderEffectReflection)) { renderEffectReflection = new RenderEffectReflection(); // Build root signature automatically from reflection renderEffectReflection.DescriptorReflection = EffectDescriptorSetReflection.New(RenderSystem.GraphicsDevice, effect.Bytecode, effectDescriptorSetSlots, "PerFrame"); renderEffectReflection.ResourceGroupDescriptions = new ResourceGroupDescription[renderEffectReflection.DescriptorReflection.Layouts.Count]; // Compute ResourceGroup hashes for (int index = 0; index < renderEffectReflection.DescriptorReflection.Layouts.Count; index++) { var descriptorSet = renderEffectReflection.DescriptorReflection.Layouts[index]; if (descriptorSet.Layout == null) { continue; } var constantBufferReflection = effect.Bytecode.Reflection.ConstantBuffers.FirstOrDefault(x => x.Name == descriptorSet.Name); renderEffectReflection.ResourceGroupDescriptions[index] = new ResourceGroupDescription(descriptorSet.Layout, constantBufferReflection); } renderEffectReflection.RootSignature = RootSignature.New(RenderSystem.GraphicsDevice, renderEffectReflection.DescriptorReflection); renderEffectReflection.BufferUploader.Compile(RenderSystem.GraphicsDevice, renderEffectReflection.DescriptorReflection, effect.Bytecode); // Prepare well-known descriptor set layouts renderEffectReflection.PerDrawLayout = CreateDrawResourceGroupLayout(renderEffectReflection.ResourceGroupDescriptions[perDrawDescriptorSetSlot.Index], renderEffect.State); renderEffectReflection.PerFrameLayout = CreateFrameResourceGroupLayout(renderEffectReflection.ResourceGroupDescriptions[perFrameDescriptorSetSlot.Index], renderEffect.State); renderEffectReflection.PerViewLayout = CreateViewResourceGroupLayout(renderEffectReflection.ResourceGroupDescriptions[perViewDescriptorSetSlot.Index], renderEffect.State); InstantiatedEffects.Add(effect, renderEffectReflection); // Notify a new effect has been compiled EffectCompiled?.Invoke(RenderSystem, effect, renderEffectReflection); } // Setup fallback parameters if (renderEffect.State != RenderEffectState.Normal && renderEffectReflection.FallbackUpdaterLayout == null) { // Process all "non standard" layouts var layoutMapping = new int[renderEffectReflection.DescriptorReflection.Layouts.Count - 3]; var layouts = new DescriptorSetLayoutBuilder[renderEffectReflection.DescriptorReflection.Layouts.Count - 3]; int layoutMappingIndex = 0; for (int index = 0; index < renderEffectReflection.DescriptorReflection.Layouts.Count; index++) { var layout = renderEffectReflection.DescriptorReflection.Layouts[index]; // Skip well-known layouts (already handled) if (layout.Name == "PerDraw" || layout.Name == "PerFrame" || layout.Name == "PerView") { continue; } layouts[layoutMappingIndex] = layout.Layout; layoutMapping[layoutMappingIndex++] = index; } renderEffectReflection.FallbackUpdaterLayout = new EffectParameterUpdaterLayout(RenderSystem.GraphicsDevice, effect, layouts); renderEffectReflection.FallbackResourceGroupMapping = layoutMapping; } // Update effect renderEffect.Effect = effect; renderEffect.Reflection = renderEffectReflection; // Invalidate pipeline state (new effect) renderEffect.PipelineState = null; renderEffects[staticEffectObjectNode] = renderEffect; } else { renderEffect.Reflection = RenderEffectReflection.Empty; renderEffect.PipelineState = null; } } } }
/// <summary> /// Actual implementation of <see cref="PrepareEffectPermutations"/>. /// </summary> /// <param name="context"></param> public virtual void PrepareEffectPermutationsImpl(RenderDrawContext context) { }
public PrepareThreadContext(RenderContext renderContext) { MutablePipelineState = new MutablePipelineState(renderContext.GraphicsDevice); Context = renderContext.GetThreadContext(); }
/// <inheritdoc/> public override void Draw(RenderDrawContext context, RenderView renderView, RenderViewStage renderViewStage, int startIndex, int endIndex) { var commandList = context.CommandList; foreach (var renderFeature in RenderFeatures) { renderFeature.Draw(context, renderView, renderViewStage, startIndex, endIndex); } // TODO: stackalloc? var descriptorSetsLocal = descriptorSets.Value; if (descriptorSetsLocal == null || descriptorSetsLocal.Length < EffectDescriptorSetSlotCount) { descriptorSetsLocal = descriptorSets.Value = new DescriptorSet[EffectDescriptorSetSlotCount]; } MeshDraw currentDrawData = null; int emptyBufferSlot = -1; for (int index = startIndex; index < endIndex; index++) { var renderNodeReference = renderViewStage.SortedRenderNodes[index].RenderNode; var renderNode = GetRenderNode(renderNodeReference); var renderMesh = (RenderMesh)renderNode.RenderObject; var drawData = renderMesh.ActiveMeshDraw; // Get effect // TODO: Use real effect slot var renderEffect = renderNode.RenderEffect; if (renderEffect.Effect == null) { continue; } // Bind VB if (currentDrawData != drawData) { for (int slot = 0; slot < drawData.VertexBuffers.Length; slot++) { var vertexBuffer = drawData.VertexBuffers[slot]; commandList.SetVertexBuffer(slot, vertexBuffer.Buffer, vertexBuffer.Offset, vertexBuffer.Stride); } // If the mesh's vertex buffers miss any input streams, an additional input binding will have been added to the pipeline state. // We bind an additional empty vertex buffer to that slot handle those streams gracefully. if (emptyBufferSlot != drawData.VertexBuffers.Length) { commandList.SetVertexBuffer(drawData.VertexBuffers.Length, emptyBuffer, 0, 0); emptyBufferSlot = drawData.VertexBuffers.Length; } if (drawData.IndexBuffer != null) { commandList.SetIndexBuffer(drawData.IndexBuffer.Buffer, drawData.IndexBuffer.Offset, drawData.IndexBuffer.Is32Bit); } currentDrawData = drawData; } var resourceGroupOffset = ComputeResourceGroupOffset(renderNodeReference); // Update cbuffer renderEffect.Reflection.BufferUploader.Apply(context.CommandList, ResourceGroupPool, resourceGroupOffset); // Bind descriptor sets for (int i = 0; i < descriptorSetsLocal.Length; ++i) { var resourceGroup = ResourceGroupPool[resourceGroupOffset++]; if (resourceGroup != null) { descriptorSetsLocal[i] = resourceGroup.DescriptorSet; } } commandList.SetPipelineState(renderEffect.PipelineState); commandList.SetDescriptorSets(0, descriptorSetsLocal); // Draw if (drawData.IndexBuffer == null) { if (renderMesh.InstanceCount > 0) { commandList.DrawInstanced(drawData.DrawCount, renderMesh.InstanceCount, drawData.StartLocation); } else { commandList.Draw(drawData.DrawCount, drawData.StartLocation); } } else { if (renderMesh.InstanceCount > 0) { commandList.DrawIndexedInstanced(drawData.DrawCount, renderMesh.InstanceCount, drawData.StartLocation); } else { commandList.DrawIndexed(drawData.DrawCount, drawData.StartLocation); } } } }