public void GenerateNodeCode(ShaderGenerator visitor, GraphContext graphContext, GenerationMode generationMode) { var sb = new ShaderStringBuilder(); var inputValue = GetSlotValue(InputSlotId, generationMode); var outputValue = GetSlotValue(OutputSlotId, generationMode); sb.AppendLine("{0} {1};", FindOutputSlot <MaterialSlot>(OutputSlotId).concreteValueType.ToString(precision), GetVariableNameForSlot(OutputSlotId)); if (!generationMode.IsPreview()) { sb.AppendLine("{0} _{1}_Flip = {0} ({2}", FindOutputSlot <MaterialSlot>(OutputSlotId).concreteValueType.ToString(precision), GetVariableNameForNode(), Convert.ToInt32(m_RedChannel)); if (channelCount > 1) { sb.Append(", {0}", Convert.ToInt32(m_GreenChannel)); } if (channelCount > 2) { sb.Append(", {0}", Convert.ToInt32(m_BlueChannel)); } if (channelCount > 3) { sb.Append(", {0}", Convert.ToInt32(m_AlphaChannel)); } sb.Append(");"); } sb.AppendLine("{0}({1}, _{2}_Flip, {3});", GetFunctionName(), inputValue, GetVariableNameForNode(), outputValue); visitor.AddShaderChunk(sb.ToString(), false); }
public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMode) { var inputValue = GetSlotValue(InputSlotId, generationMode); var outputValue = GetSlotValue(OutputSlotId, generationMode); sb.AppendLine("{0} {1};", FindOutputSlot <MaterialSlot>(OutputSlotId).concreteValueType.ToShaderString(), GetVariableNameForSlot(OutputSlotId)); if (!generationMode.IsPreview()) { sb.AppendLine("{0} _{1}_InvertColors = {0} ({2}", FindOutputSlot <MaterialSlot>(OutputSlotId).concreteValueType.ToShaderString(), GetVariableNameForNode(), Convert.ToInt32(m_RedChannel)); if (channelCount > 1) { sb.Append(", {0}", Convert.ToInt32(m_GreenChannel)); } if (channelCount > 2) { sb.Append(", {0}", Convert.ToInt32(m_BlueChannel)); } if (channelCount > 3) { sb.Append(", {0}", Convert.ToInt32(m_AlphaChannel)); } sb.Append(");"); } sb.AppendLine("{0}({1}, _{2}_InvertColors, {3});", GetFunctionName(), inputValue, GetVariableNameForNode(), outputValue); }
internal override void AppendBatchablePropertyDeclarations(ShaderStringBuilder builder, string delimiter = ";") { int numLayers = value.layers.Count; if (numLayers > 0) { builder.Append("DECLARE_STACK_CB("); builder.Append(referenceName); builder.Append(")"); builder.AppendLine(delimiter); } }
public override void AppendHLSLParameterDeclaration(ShaderStringBuilder sb, string paramName) { if (m_BareResource) { sb.Append("TEXTURE2D("); sb.Append(paramName); sb.Append(")"); } else { base.AppendHLSLParameterDeclaration(sb, paramName); } }
internal override void AppendNonBatchablePropertyDeclarations(ShaderStringBuilder builder, string delimiter = ";") { int numLayers = value.layers.Count; if (numLayers > 0) { // declare regular texture properties (for fallback case) for (int i = 0; i < value.layers.Count; i++) { string layerRefName = value.layers[i].layerRefName; builder.AppendLine( $"TEXTURE2D({layerRefName}); SAMPLER(sampler{layerRefName}); {concretePrecision.ToShaderString()}4 {layerRefName}_TexelSize;"); } // declare texture stack builder.Append("DECLARE_STACK"); builder.Append((numLayers <= 1) ? "" : numLayers.ToString()); builder.Append("("); builder.Append(referenceName); builder.Append(","); for (int i = 0; i < value.layers.Count; i++) { if (i != 0) { builder.Append(","); } builder.Append(value.layers[i].layerRefName); } builder.Append(")"); builder.AppendLine(delimiter); // TODO: don't like delimiter, pretty sure it's not necessary if we invert the defaults on GEtPropertyDeclaration / GetPropertyArgument string // declare the actual virtual texture property "variable" as a macro define to the BuildVTProperties function builder.AppendLine("#define " + referenceName + " BuildVTProperties_" + referenceName + "()"); } }
public override void AppendHLSLParameterDeclaration(ShaderStringBuilder sb, string paramName) { if (m_BareResource) { // we have to use our modified macro declaration here, to ensure that something is declared for GLES2 platforms // (the standard SAMPLER macro doesn't declare anything, so the commas will be messed up in the parameter list) sb.Append("UNITY_BARE_SAMPLER("); sb.Append(paramName); sb.Append(")"); } else { base.AppendHLSLParameterDeclaration(sb, paramName); } }
internal override string GetPropertyDeclarationString(string delimiter = ";") { ShaderStringBuilder s = new ShaderStringBuilder(); s.AppendLine("Gradient {0}_Definition()", referenceName); using (s.BlockScope()) { string[] colors = new string[8]; for (int i = 0; i < colors.Length; i++) { colors[i] = string.Format("g.colors[{0}] = {1}4(0, 0, 0, 0);", i, concretePrecision.ToShaderString()); } for (int i = 0; i < value.colorKeys.Length; i++) { colors[i] = string.Format("g.colors[{0}] = {1}4({2}, {3}, {4}, {5});" , i , concretePrecision.ToShaderString() , NodeUtils.FloatToShaderValue(value.colorKeys[i].color.r) , NodeUtils.FloatToShaderValue(value.colorKeys[i].color.g) , NodeUtils.FloatToShaderValue(value.colorKeys[i].color.b) , NodeUtils.FloatToShaderValue(value.colorKeys[i].time)); } string[] alphas = new string[8]; for (int i = 0; i < alphas.Length; i++) { alphas[i] = string.Format("g.alphas[{0}] = {1}2(0, 0);", i, concretePrecision.ToShaderString()); } for (int i = 0; i < value.alphaKeys.Length; i++) { alphas[i] = string.Format("g.alphas[{0}] = {1}2({2}, {3});" , i , concretePrecision.ToShaderString() , NodeUtils.FloatToShaderValue(value.alphaKeys[i].alpha) , NodeUtils.FloatToShaderValue(value.alphaKeys[i].time)); } s.AppendLine("Gradient g;"); s.AppendLine("g.type = {0};", (int)value.mode); s.AppendLine("g.colorsLength = {0};", value.colorKeys.Length); s.AppendLine("g.alphasLength = {0};", value.alphaKeys.Length); for (int i = 0; i < colors.Length; i++) { s.AppendLine(colors[i]); } for (int i = 0; i < alphas.Length; i++) { s.AppendLine(alphas[i]); } s.AppendLine("return g;", true); } s.AppendIndentation(); s.Append("#define {0} {0}_Definition()", referenceName); return(s.ToString()); }
public string GetDotsInstancingPropertiesDeclaration(GenerationMode mode) { // Hybrid V1 needs to declare a special macro to that is injected into // builtin instancing variables. // Hybrid V2 does not need it. #if !ENABLE_HYBRID_RENDERER_V2 var builder = new ShaderStringBuilder(); var batchAll = mode == GenerationMode.Preview; int instancedCount = GetDotsInstancingPropertiesCount(mode); if (instancedCount > 0) { builder.AppendLine("#if defined(UNITY_HYBRID_V1_INSTANCING_ENABLED)"); builder.Append("#define HYBRID_V1_CUSTOM_ADDITIONAL_MATERIAL_VARS\t"); int count = 0; foreach (var prop in properties.Where(n => batchAll || (n.generatePropertyBlock && n.isBatchable))) { if (prop.gpuInstanced) { string varName = $"{prop.referenceName}_Array"; string sType = prop.concreteShaderValueType.ToShaderString(prop.concretePrecision); builder.Append("UNITY_DEFINE_INSTANCED_PROP({0}, {1})", sType, varName); if (count < instancedCount - 1) { builder.Append("\\"); } builder.AppendLine(""); count++; } } foreach (var prop in properties.Where(n => batchAll || (n.generatePropertyBlock && n.isBatchable))) { if (prop.gpuInstanced) { string varName = $"{prop.referenceName}_Array"; builder.AppendLine("#define {0} UNITY_ACCESS_INSTANCED_PROP(unity_Builtins0, {1})", prop.referenceName, varName); } } } builder.AppendLine("#endif"); return(builder.ToString()); #else return(""); #endif }
public string GetDotsInstancingPropertiesDeclaration(GenerationMode mode) { // Hybrid V1 needs to declare a special macro to that is injected into // builtin instancing variables. // Hybrid V2 does not need it. #if !ENABLE_HYBRID_RENDERER_V2 var builder = new ShaderStringBuilder(); var batchAll = mode == GenerationMode.Preview; var dotsInstancingProperties = DotsInstancingProperties(mode); if (dotsInstancingProperties.Any()) { builder.AppendLine("#if defined(UNITY_HYBRID_V1_INSTANCING_ENABLED)"); builder.Append("#define HYBRID_V1_CUSTOM_ADDITIONAL_MATERIAL_VARS\t"); int count = 0; int instancedCount = dotsInstancingProperties.Count(); foreach (var prop in dotsInstancingProperties) { string varName = $"{prop.referenceName}_Array"; string sType = prop.concreteShaderValueType.ToShaderString(prop.concretePrecision); builder.Append("UNITY_DEFINE_INSTANCED_PROP({0}, {1})", sType, varName); // Combine the UNITY_DEFINE_INSTANCED_PROP lines with \ so the generated // macro expands into multiple definitions if there are more than one. if (count < instancedCount - 1) { builder.Append("\\"); } builder.AppendLine(""); count++; } foreach (var prop in dotsInstancingProperties) { string varName = $"{prop.referenceName}_Array"; builder.AppendLine("#define {0} UNITY_ACCESS_INSTANCED_PROP(unity_Builtins0, {1})", prop.referenceName, varName); } } builder.AppendLine("#endif"); return(builder.ToString()); #else return(""); #endif }
public string GetDotsInstancingPropertiesDeclaration(GenerationMode mode) { var builder = new ShaderStringBuilder(); var batchAll = mode == GenerationMode.Preview; int instancedCount = GetDotsInstancingPropertiesCount(mode); if (instancedCount > 0) { builder.AppendLine("#if defined(UNITY_DOTS_INSTANCING_ENABLED)"); builder.AppendLine("#define SHADER_GRAPH_GENERATED"); builder.Append("#define DOTS_CUSTOM_ADDITIONAL_MATERIAL_VARS\t"); int count = 0; foreach (var prop in properties.Where(n => batchAll || (n.generatePropertyBlock && n.isBatchable))) { if (prop.gpuInstanced) { string varName = $"{prop.referenceName}_Array"; string sType = prop.concreteShaderValueType.ToShaderString(prop.concretePrecision); builder.Append("UNITY_DEFINE_INSTANCED_PROP({0}, {1})", sType, varName); if (count < instancedCount - 1) { builder.Append("\\"); } builder.AppendLine(""); count++; } } foreach (var prop in properties.Where(n => batchAll || (n.generatePropertyBlock && n.isBatchable))) { if (prop.gpuInstanced) { string varName = $"{prop.referenceName}_Array"; builder.AppendLine("#define {0} UNITY_ACCESS_INSTANCED_PROP(unity_Builtins0, {1})", prop.referenceName, varName); } } } builder.AppendLine("#endif"); return(builder.ToString()); }
public string GetDotsInstancingPropertiesDeclaration(GenerationMode mode) { // Hybrid V1 needs to declare a special macro to that is injected into // builtin instancing variables. // Hybrid V2 does not need it. #if !ENABLE_HYBRID_RENDERER_V2 var builder = new ShaderStringBuilder(); var batchAll = (mode == GenerationMode.Preview); // build a list of all HLSL properties var hybridHLSLProps = new List <HLSLProperty>(); properties.ForEach(p => p.ForeachHLSLProperty(h => { if (h.declaration == HLSLDeclaration.HybridPerInstance) { hybridHLSLProps.Add(h); } })); if (hybridHLSLProps.Any()) { builder.AppendLine("#if defined(UNITY_HYBRID_V1_INSTANCING_ENABLED)"); builder.AppendLine("#define HYBRID_V1_CUSTOM_ADDITIONAL_MATERIAL_VARS \\"); int count = 0; foreach (var prop in hybridHLSLProps) { // Combine multiple UNITY_DEFINE_INSTANCED_PROP lines with \ so the generated // macro expands into multiple definitions if there are more than one. if (count > 0) { builder.Append("\\"); builder.AppendNewLine(); } builder.Append("UNITY_DEFINE_INSTANCED_PROP("); builder.Append(prop.GetValueTypeString()); builder.Append(", "); builder.Append(prop.name); builder.Append("_Array)"); count++; } builder.AppendNewLine(); foreach (var prop in hybridHLSLProps) { string varName = $"{prop.name}_Array"; builder.AppendLine("#define {0} UNITY_ACCESS_INSTANCED_PROP(unity_Builtins0, {1})", prop.name, varName); } } builder.AppendLine("#endif"); return(builder.ToString()); #else return(""); #endif }
public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMode) { if (asset == null || hasError) { var outputSlots = new List <MaterialSlot>(); GetOutputSlots(outputSlots); var outputPrecision = asset != null ? asset.outputPrecision : ConcretePrecision.Single; foreach (var slot in outputSlots) { sb.AppendLine($"{slot.concreteValueType.ToShaderString(outputPrecision)} {GetVariableNameForSlot(slot.id)} = {slot.GetDefaultValue(GenerationMode.ForReals)};"); } return; } var inputVariableName = $"_{GetVariableNameForNode()}"; GenerationUtils.GenerateSurfaceInputTransferCode(sb, asset.requirements, asset.inputStructName, inputVariableName); foreach (var outSlot in asset.outputs) { sb.AppendLine("{0} {1};", outSlot.concreteValueType.ToShaderString(asset.outputPrecision), GetVariableNameForSlot(outSlot.id)); } var arguments = new List <string>(); foreach (var prop in asset.inputs) { prop.ValidateConcretePrecision(asset.graphPrecision); var inSlotId = m_PropertyIds[m_PropertyGuids.IndexOf(prop.guid.ToString())]; arguments.Add(GetSlotValue(inSlotId, generationMode, prop.concretePrecision)); } // pass surface inputs through arguments.Add(inputVariableName); foreach (var outSlot in asset.outputs) { arguments.Add(GetVariableNameForSlot(outSlot.id)); } foreach (var feedbackSlot in asset.vtFeedbackVariables) { string feedbackVar = GetVariableNameForNode() + "_" + feedbackSlot; sb.AppendLine("{0} {1};", ConcreteSlotValueType.Vector4.ToShaderString(ConcretePrecision.Single), feedbackVar); arguments.Add(feedbackVar); } sb.AppendIndentation(); sb.Append(asset.functionName); sb.Append("("); bool firstArg = true; foreach (var arg in arguments) { if (!firstArg) { sb.Append(", "); } firstArg = false; sb.Append(arg); } sb.Append(");"); sb.AppendNewLine(); }
public virtual void AppendHLSLParameterDeclaration(ShaderStringBuilder sb, string paramName) { sb.Append(concreteValueType.ToShaderString()); sb.Append(" "); sb.Append(paramName); }
public static bool GenerateShaderPass(AbstractMaterialNode masterNode, ShaderPass pass, GenerationMode mode, ActiveFields activeFields, ShaderGenerator result, List <string> sourceAssetDependencyPaths, List <Dependency[]> dependencies, string resourceClassName, string assemblyName) { // -------------------------------------------------- // Debug // Get scripting symbols BuildTargetGroup buildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup; string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup); bool isDebug = defines.Contains(kDebugSymbol); // -------------------------------------------------- // Setup // Initiailize Collectors var propertyCollector = new PropertyCollector(); var keywordCollector = new KeywordCollector(); masterNode.owner.CollectShaderKeywords(keywordCollector, mode); // Get upstream nodes from ShaderPass port mask List <AbstractMaterialNode> vertexNodes; List <AbstractMaterialNode> pixelNodes; GetUpstreamNodesForShaderPass(masterNode, pass, out vertexNodes, out pixelNodes); // Track permutation indices for all nodes List <int>[] vertexNodePermutations = new List <int> [vertexNodes.Count]; List <int>[] pixelNodePermutations = new List <int> [pixelNodes.Count]; // Get active fields from upstream Node requirements ShaderGraphRequirementsPerKeyword graphRequirements; GetActiveFieldsAndPermutationsForNodes(masterNode, pass, keywordCollector, vertexNodes, pixelNodes, vertexNodePermutations, pixelNodePermutations, activeFields, out graphRequirements); // GET CUSTOM ACTIVE FIELDS HERE! // Get active fields from ShaderPass AddRequiredFields(pass.requiredAttributes, activeFields.baseInstance); AddRequiredFields(pass.requiredVaryings, activeFields.baseInstance); // Get Port references from ShaderPass var pixelSlots = FindMaterialSlotsOnNode(pass.pixelPorts, masterNode); var vertexSlots = FindMaterialSlotsOnNode(pass.vertexPorts, masterNode); // Function Registry var functionBuilder = new ShaderStringBuilder(); var functionRegistry = new FunctionRegistry(functionBuilder); // Hash table of named $splice(name) commands // Key: splice token // Value: string to splice Dictionary <string, string> spliceCommands = new Dictionary <string, string>(); // -------------------------------------------------- // Dependencies // Propagate active field requirements using dependencies // Must be executed before types are built foreach (var instance in activeFields.all.instances) { ShaderSpliceUtil.ApplyDependencies(instance, dependencies); } // -------------------------------------------------- // Pass Setup // Name if (!string.IsNullOrEmpty(pass.displayName)) { spliceCommands.Add("PassName", $"Name \"{pass.displayName}\""); } else { spliceCommands.Add("PassName", "// Name: <None>"); } // Tags if (!string.IsNullOrEmpty(pass.lightMode)) { spliceCommands.Add("LightMode", $"\"LightMode\" = \"{pass.lightMode}\""); } else { spliceCommands.Add("LightMode", "// LightMode: <None>"); } // Render state BuildRenderStatesFromPass(pass, ref spliceCommands); // -------------------------------------------------- // Pass Code // Pragmas using (var passPragmaBuilder = new ShaderStringBuilder()) { if (pass.pragmas != null) { foreach (string pragma in pass.pragmas) { passPragmaBuilder.AppendLine($"#pragma {pragma}"); } } if (passPragmaBuilder.length == 0) { passPragmaBuilder.AppendLine("// PassPragmas: <None>"); } spliceCommands.Add("PassPragmas", passPragmaBuilder.ToCodeBlack()); } // Includes using (var passIncludeBuilder = new ShaderStringBuilder()) { if (pass.includes != null) { foreach (string include in pass.includes) { passIncludeBuilder.AppendLine($"#include \"{include}\""); } } if (passIncludeBuilder.length == 0) { passIncludeBuilder.AppendLine("// PassIncludes: <None>"); } spliceCommands.Add("PassIncludes", passIncludeBuilder.ToCodeBlack()); } // Keywords using (var passKeywordBuilder = new ShaderStringBuilder()) { if (pass.keywords != null) { foreach (KeywordDescriptor keyword in pass.keywords) { passKeywordBuilder.AppendLine(keyword.ToDeclarationString()); } } if (passKeywordBuilder.length == 0) { passKeywordBuilder.AppendLine("// PassKeywords: <None>"); } spliceCommands.Add("PassKeywords", passKeywordBuilder.ToCodeBlack()); } // -------------------------------------------------- // Graph Vertex var vertexBuilder = new ShaderStringBuilder(); // If vertex modification enabled if (activeFields.baseInstance.Contains("features.graphVertex")) { // Setup string vertexGraphInputName = "VertexDescriptionInputs"; string vertexGraphOutputName = "VertexDescription"; string vertexGraphFunctionName = "VertexDescriptionFunction"; var vertexGraphInputGenerator = new ShaderGenerator(); var vertexGraphFunctionBuilder = new ShaderStringBuilder(); var vertexGraphOutputBuilder = new ShaderStringBuilder(); // Build vertex graph inputs ShaderSpliceUtil.BuildType(GetTypeForStruct("VertexDescriptionInputs", resourceClassName, assemblyName), activeFields, vertexGraphInputGenerator, isDebug); // Build vertex graph outputs // Add struct fields to active fields SubShaderGenerator.GenerateVertexDescriptionStruct(vertexGraphOutputBuilder, vertexSlots, vertexGraphOutputName, activeFields.baseInstance); // Build vertex graph functions from ShaderPass vertex port mask SubShaderGenerator.GenerateVertexDescriptionFunction( masterNode.owner as GraphData, vertexGraphFunctionBuilder, functionRegistry, propertyCollector, keywordCollector, mode, masterNode, vertexNodes, vertexNodePermutations, vertexSlots, vertexGraphInputName, vertexGraphFunctionName, vertexGraphOutputName); // Generate final shader strings vertexBuilder.AppendLines(vertexGraphInputGenerator.GetShaderString(0, false)); vertexBuilder.AppendNewLine(); vertexBuilder.AppendLines(vertexGraphOutputBuilder.ToString()); vertexBuilder.AppendNewLine(); vertexBuilder.AppendLines(vertexGraphFunctionBuilder.ToString()); } // Add to splice commands if (vertexBuilder.length == 0) { vertexBuilder.AppendLine("// GraphVertex: <None>"); } spliceCommands.Add("GraphVertex", vertexBuilder.ToCodeBlack()); // -------------------------------------------------- // Graph Pixel // Setup string pixelGraphInputName = "SurfaceDescriptionInputs"; string pixelGraphOutputName = "SurfaceDescription"; string pixelGraphFunctionName = "SurfaceDescriptionFunction"; var pixelGraphInputGenerator = new ShaderGenerator(); var pixelGraphOutputBuilder = new ShaderStringBuilder(); var pixelGraphFunctionBuilder = new ShaderStringBuilder(); // Build pixel graph inputs ShaderSpliceUtil.BuildType(GetTypeForStruct("SurfaceDescriptionInputs", resourceClassName, assemblyName), activeFields, pixelGraphInputGenerator, isDebug); // Build pixel graph outputs // Add struct fields to active fields SubShaderGenerator.GenerateSurfaceDescriptionStruct(pixelGraphOutputBuilder, pixelSlots, pixelGraphOutputName, activeFields.baseInstance); // Build pixel graph functions from ShaderPass pixel port mask SubShaderGenerator.GenerateSurfaceDescriptionFunction( pixelNodes, pixelNodePermutations, masterNode, masterNode.owner as GraphData, pixelGraphFunctionBuilder, functionRegistry, propertyCollector, keywordCollector, mode, pixelGraphFunctionName, pixelGraphOutputName, null, pixelSlots, pixelGraphInputName); var instanceCount = propertyCollector.GetDotsInstancingPropertiesCount(mode); using (var instancingOptions = new ShaderStringBuilder()) { instancingOptions.AppendLine("#pragma multi_compile_instancing"); if (masterNode is MasterNode node && node.dotsInstancing.isOn) { instancingOptions.AppendLine("#define UNITY_DOTS_SHADER"); instancingOptions.AppendLine("#pragma instancing_options nolightprobe"); instancingOptions.AppendLine("#pragma instancing_options nolodfade"); } if (instanceCount > 0) { instancingOptions.AppendLine("#if SHADER_TARGET >= 35 && (defined(SHADER_API_D3D11) || defined(SHADER_API_GLES3) || defined(SHADER_API_GLCORE) || defined(SHADER_API_XBOXONE) || defined(SHADER_API_PSSL) || defined(SHADER_API_VULKAN) || defined(SHADER_API_METAL))"); instancingOptions.AppendLine("#define UNITY_SUPPORT_INSTANCING"); instancingOptions.AppendLine("#endif"); instancingOptions.AppendLine("#if defined(UNITY_SUPPORT_INSTANCING) && defined(INSTANCING_ON)"); instancingOptions.AppendLine("#define UNITY_DOTS_INSTANCING_ENABLED"); instancingOptions.AppendLine("#endif"); } spliceCommands.Add("PassInstancing", instancingOptions.ToCodeBlack()); } using (var dotsInstancingCode = new ShaderStringBuilder()) { if (instanceCount > 0) { dotsInstancingCode.AppendLine("//-------------------------------------------------------------------------------------"); dotsInstancingCode.AppendLine("// Dots Instancing vars"); dotsInstancingCode.AppendLine("//-------------------------------------------------------------------------------------"); dotsInstancingCode.AppendLine(""); dotsInstancingCode.Append(propertyCollector.GetDotsInstancingPropertiesDeclaration(mode)); } spliceCommands.Add("DotsInstancingVars", dotsInstancingCode.ToCodeBlack()); } using (var pixelBuilder = new ShaderStringBuilder()) { // Generate final shader strings pixelBuilder.AppendLines(pixelGraphInputGenerator.GetShaderString(0, false)); pixelBuilder.AppendNewLine(); pixelBuilder.AppendLines(pixelGraphOutputBuilder.ToString()); pixelBuilder.AppendNewLine(); pixelBuilder.AppendLines(pixelGraphFunctionBuilder.ToString()); // Add to splice commands if (pixelBuilder.length == 0) { pixelBuilder.AppendLine("// GraphPixel: <None>"); } spliceCommands.Add("GraphPixel", pixelBuilder.ToCodeBlack()); } // -------------------------------------------------- // Graph Functions if (functionBuilder.length == 0) { functionBuilder.AppendLine("// GraphFunctions: <None>"); } spliceCommands.Add("GraphFunctions", functionBuilder.ToCodeBlack()); // -------------------------------------------------- // Graph Keywords using (var keywordBuilder = new ShaderStringBuilder()) { keywordCollector.GetKeywordsDeclaration(keywordBuilder, mode); if (keywordBuilder.length == 0) { keywordBuilder.AppendLine("// GraphKeywords: <None>"); } spliceCommands.Add("GraphKeywords", keywordBuilder.ToCodeBlack()); } // -------------------------------------------------- // Graph Properties using (var propertyBuilder = new ShaderStringBuilder()) { propertyCollector.GetPropertiesDeclaration(propertyBuilder, mode, masterNode.owner.concretePrecision); if (propertyBuilder.length == 0) { propertyBuilder.AppendLine("// GraphProperties: <None>"); } spliceCommands.Add("GraphProperties", propertyBuilder.ToCodeBlack()); } // -------------------------------------------------- // Graph Defines using (var graphDefines = new ShaderStringBuilder()) { graphDefines.AppendLine("#define {0}", pass.referenceName); if (graphRequirements.permutationCount > 0) { List <int> activePermutationIndices; // Depth Texture activePermutationIndices = graphRequirements.allPermutations.instances .Where(p => p.requirements.requiresDepthTexture) .Select(p => p.permutationIndex) .ToList(); if (activePermutationIndices.Count > 0) { graphDefines.AppendLine(KeywordUtil.GetKeywordPermutationSetConditional(activePermutationIndices)); graphDefines.AppendLine("#define REQUIRE_DEPTH_TEXTURE"); graphDefines.AppendLine("#endif"); } // Opaque Texture activePermutationIndices = graphRequirements.allPermutations.instances .Where(p => p.requirements.requiresCameraOpaqueTexture) .Select(p => p.permutationIndex) .ToList(); if (activePermutationIndices.Count > 0) { graphDefines.AppendLine(KeywordUtil.GetKeywordPermutationSetConditional(activePermutationIndices)); graphDefines.AppendLine("#define REQUIRE_OPAQUE_TEXTURE"); graphDefines.AppendLine("#endif"); } } else { // Depth Texture if (graphRequirements.baseInstance.requirements.requiresDepthTexture) { graphDefines.AppendLine("#define REQUIRE_DEPTH_TEXTURE"); } // Opaque Texture if (graphRequirements.baseInstance.requirements.requiresCameraOpaqueTexture) { graphDefines.AppendLine("#define REQUIRE_OPAQUE_TEXTURE"); } } // Add to splice commands spliceCommands.Add("GraphDefines", graphDefines.ToCodeBlack()); } // -------------------------------------------------- // Main // Main include is expected to contain vert/frag definitions for the pass // This must be defined after all graph code using (var mainBuilder = new ShaderStringBuilder()) { mainBuilder.AppendLine($"#include \"{pass.varyingsInclude}\""); mainBuilder.AppendLine($"#include \"{pass.passInclude}\""); // Add to splice commands spliceCommands.Add("MainInclude", mainBuilder.ToCodeBlack()); } // -------------------------------------------------- // Debug // Debug output all active fields using (var debugBuilder = new ShaderStringBuilder()) { if (isDebug) { // Active fields debugBuilder.AppendLine("// ACTIVE FIELDS:"); foreach (string field in activeFields.baseInstance.fields) { debugBuilder.AppendLine("// " + field); } } if (debugBuilder.length == 0) { debugBuilder.AppendLine("// <None>"); } // Add to splice commands spliceCommands.Add("Debug", debugBuilder.ToCodeBlack()); } // -------------------------------------------------- // Finalize // Get Template string templateLocation = GetTemplatePath("PassMesh.template"); if (!File.Exists(templateLocation)) { return(false); } // Get Template preprocessor string templatePath = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Templates"; var templatePreprocessor = new ShaderSpliceUtil.TemplatePreprocessor(activeFields, spliceCommands, isDebug, templatePath, sourceAssetDependencyPaths, assemblyName, resourceClassName); // Process Template templatePreprocessor.ProcessTemplateFile(templateLocation); result.AddShaderChunk(templatePreprocessor.GetShaderCode().ToString(), false); return(true); }
public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMode) { bool success = false; if (IsSlotConnected(VirtualTextureInputId)) { var vtProperty = GetSlotProperty(VirtualTextureInputId) as VirtualTextureShaderProperty; if (vtProperty != null) { var layerOutputVariables = new List <string>(); int layerCount = vtProperty.value.layers.Count; for (int i = 0; i < layerCount; i++) { if (IsSlotConnected(OutputSlotIds[i])) { // declare output variables up front string layerOutputVariable = GetVariableNameForSlot(OutputSlotIds[i]); sb.AppendLine("$precision4 " + layerOutputVariable + ";"); layerOutputVariables.Add(layerOutputVariable); } } if (layerOutputVariables.Count > 0) { // assign feedback variable sb.AppendIndentation(); if (!noFeedback) { sb.Append("float4 "); sb.Append(GetFeedbackVariableName()); sb.Append(" = "); } sb.Append(GetFunctionName(out var unused)); sb.Append("("); sb.Append(GetSlotValue(UVInputId, generationMode)); switch (lodCalculation) { case LodCalculation.VtLevel_Lod: case LodCalculation.VtLevel_Bias: sb.Append(", "); sb.Append((lodCalculation == LodCalculation.VtLevel_Lod) ? GetSlotValue(LODInputId, generationMode) : GetSlotValue(BiasInputId, generationMode)); break; case LodCalculation.VtLevel_Derivatives: sb.Append(", "); sb.Append(GetSlotValue(DxInputId, generationMode)); sb.Append(", "); sb.Append(GetSlotValue(DyInputId, generationMode)); break; } sb.Append(", "); sb.Append(vtProperty.referenceName); foreach (string layerOutputVariable in layerOutputVariables) { sb.Append(", "); sb.Append(layerOutputVariable); } sb.Append(");"); sb.AppendNewLine(); success = true; } } } if (!success) { // set all outputs to zero for (int i = 0; i < kMaxLayers; i++) { if (IsSlotConnected(OutputSlotIds[i])) { // declare output variables up front string layerOutputVariable = GetVariableNameForSlot(OutputSlotIds[i]); sb.AppendLine("$precision4 " + layerOutputVariable + " = 0;"); } } // TODO: should really just disable feedback in this case (need different feedback interface to do this) sb.AppendLine("$precision4 " + GetFeedbackVariableName() + " = 1;"); } }
void AppendVtSample(ShaderStringBuilder sb, string propertiesName, string vtInputVariable, string infoVariable, int layerIndex, string outputVariableName) { sb.AppendIndentation(); sb.Append(outputVariableName); sb.Append(" = "); sb.Append("SampleVTLayerWithTextureType("); sb.Append(propertiesName); sb.Append(", "); sb.Append(vtInputVariable); sb.Append(", "); sb.Append(infoVariable); sb.Append(", "); sb.Append(layerIndex.ToString()); sb.Append(");"); sb.AppendNewLine(); }
public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMode) { var outputGraphPrecision = asset?.outputGraphPrecision ?? GraphPrecision.Single; var outputPrecision = outputGraphPrecision.ToConcrete(concretePrecision); if (asset == null || hasError) { var outputSlots = new List <MaterialSlot>(); GetOutputSlots(outputSlots); foreach (var slot in outputSlots) { sb.AppendLine($"{slot.concreteValueType.ToShaderString(outputPrecision)} {GetVariableNameForSlot(slot.id)} = {slot.GetDefaultValue(GenerationMode.ForReals)};"); } return; } var inputVariableName = $"_{GetVariableNameForNode()}"; GenerationUtils.GenerateSurfaceInputTransferCode(sb, asset.requirements, asset.inputStructName, inputVariableName); // declare output variables foreach (var outSlot in asset.outputs) { sb.AppendLine("{0} {1};", outSlot.concreteValueType.ToShaderString(outputPrecision), GetVariableNameForSlot(outSlot.id)); } var arguments = new List <string>(); foreach (AbstractShaderProperty prop in asset.inputs) { // setup the property concrete precision (fallback to node concrete precision when it's switchable) prop.SetupConcretePrecision(this.concretePrecision); var inSlotId = m_PropertyIds[m_PropertyGuids.IndexOf(prop.guid.ToString())]; arguments.Add(GetSlotValue(inSlotId, generationMode, prop.concretePrecision)); if (prop.isConnectionTestable) { arguments.Add(IsSlotConnected(inSlotId) ? "true" : "false"); } } var dropdowns = asset.dropdowns; foreach (var dropdown in dropdowns) { var name = GetDropdownEntryName(dropdown.referenceName); if (dropdown.ContainsEntry(name)) { arguments.Add(dropdown.IndexOfName(name).ToString()); } else { arguments.Add(dropdown.value.ToString()); } } // pass surface inputs through arguments.Add(inputVariableName); foreach (var outSlot in asset.outputs) { arguments.Add(GetVariableNameForSlot(outSlot.id)); } foreach (var feedbackSlot in asset.vtFeedbackVariables) { string feedbackVar = GetVariableNameForNode() + "_" + feedbackSlot; sb.AppendLine("{0} {1};", ConcreteSlotValueType.Vector4.ToShaderString(ConcretePrecision.Single), feedbackVar); arguments.Add(feedbackVar); } sb.AppendIndentation(); sb.Append(asset.functionName); sb.Append("("); bool firstArg = true; foreach (var arg in arguments) { if (!firstArg) { sb.Append(", "); } firstArg = false; sb.Append(arg); } sb.Append(");"); sb.AppendNewLine(); }
internal override void AppendNonBatchablePropertyDeclarations(ShaderStringBuilder builder, string delimiter = ";") { int numLayers = value.layers.Count; if (numLayers > 0) { if (!value.procedural) { // declare regular texture properties (for fallback case) for (int i = 0; i < value.layers.Count; i++) { string layerRefName = value.layers[i].layerRefName; builder.AppendLine( $"TEXTURE2D({layerRefName}); SAMPLER(sampler{layerRefName}); {concretePrecision.ToShaderString()}4 {layerRefName}_TexelSize;"); } } // declare texture stack builder.AppendIndentation(); builder.Append("DECLARE_STACK"); builder.Append((numLayers <= 1) ? "" : numLayers.ToString()); builder.Append("("); builder.Append(referenceName); builder.Append(","); for (int i = 0; i < value.layers.Count; i++) { if (i != 0) { builder.Append(","); } builder.Append(value.layers[i].layerRefName); } builder.Append(")"); builder.Append(delimiter); builder.AppendNewLine(); // declare the actual virtual texture property "variable" as a macro define to the BuildVTProperties function builder.AppendIndentation(); builder.Append("#define "); builder.Append(referenceName); builder.Append(" AddTextureType(BuildVTProperties_"); builder.Append(referenceName); builder.Append("()"); for (int i = 0; i < value.layers.Count; i++) { builder.Append(","); builder.Append("TEXTURETYPE_"); builder.Append(value.layers[i].layerTextureType.ToString().ToUpper()); } builder.Append(")"); builder.AppendNewLine(); } }
public static void GetKeywordPermutationDeclarations(ShaderStringBuilder sb, List <List <KeyValuePair <ShaderKeyword, int> > > permutations) { if (permutations.Count == 0) { return; } for (int p = 0; p < permutations.Count; p++) { // ShaderStringBuilder.Append doesnt apply indentation sb.AppendIndentation(); // Append correct if bool isLast = false; if (p == 0) { sb.Append("#if "); } else if (p == permutations.Count - 1) { sb.Append("#else"); isLast = true; } else { sb.Append("#elif "); } // Last permutation is always #else if (!isLast) { // Track whether && is required bool appendAnd = false; // Iterate all keywords that are part of the permutation for (int i = 0; i < permutations[p].Count; i++) { // When previous keyword was inserted subsequent requires && string and = appendAnd ? " && " : string.Empty; switch (permutations[p][i].Key.keywordType) { case KeywordType.Enum: { sb.Append($"{and}defined({permutations[p][i].Key.referenceName}_{permutations[p][i].Key.entries[permutations[p][i].Value].referenceName})"); appendAnd = true; break; } case KeywordType.Boolean: { // HLSL does not support a !value predicate if (permutations[p][i].Value != 0) { continue; } sb.Append($"{and}defined({permutations[p][i].Key.referenceName})"); appendAnd = true; break; } default: throw new ArgumentOutOfRangeException(); } } } sb.AppendNewLine(); // Define the matching permutation keyword sb.IncreaseIndent(); sb.AppendLine($"#define KEYWORD_PERMUTATION_{p}"); sb.DecreaseIndent(); } // End statement sb.AppendLine("#endif"); }
private bool ProcessSpliceCommand(Token spliceCommand, int lineEnd, ref int cur) { if (!Expect(spliceCommand.s, spliceCommand.end, '(')) { return(false); } else { Token param = ParseUntil(spliceCommand.s, spliceCommand.end + 1, lineEnd, ')'); if (!param.IsValid()) { Error("ERROR: splice command is missing a ')'", spliceCommand.s, spliceCommand.start); return(false); } else { // append everything before the beginning of the escape sequence AppendSubstring(spliceCommand.s, cur, true, spliceCommand.start - 1, false); // find the named fragment string name = param.GetString(); // unfortunately this allocates a new string string fragment; if ((namedFragments != null) && namedFragments.TryGetValue(name, out fragment)) { // splice the fragment result.Append(fragment); } else { // no named fragment found result.Append("/* WARNING: $splice Could not find named fragment '{0}' */", name); } // advance to just after the ')' and continue parsing cur = param.end + 1; } } return(true); }