using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; /// partial class ID2D1ShaderGenerator { /// partial class InitializeFromDispatchData { /// /// Writes the InitializeFromDispatchData method. /// /// The input instance with gathered shader info. /// The instance to write into. public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { writer.WriteLine("/// "); writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator)); writer.WriteLine("readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InitializeFromDispatchData(global::System.ReadOnlySpan data)"); using (writer.WriteBlock()) { // If there are no fields, the method body is just empty if (info.Fields.IsEmpty) { return; } // Insert the fallback for empty shaders. This will generate the following code: writer.WriteLine("if (data.IsEmpty)"); using (writer.WriteBlock()) { writer.WriteLine("return;"); } // Get a reference to the data through the generated native layout type writer.WriteLine(); writer.WriteLine("ref readonly global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data));"); // Generate loading statements for each captured field foreach (FieldInfo fieldInfo in info.Fields) { switch (fieldInfo) { case FieldInfo.Primitive primitive: // Read a primitive value writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.{string.Join(".", primitive.FieldPath)}) = buffer.{string.Join("_", primitive.FieldPath)};"); break; case FieldInfo.NonLinearMatrix matrix: string fieldPath = string.Join(".", matrix.FieldPath); string fieldNamePrefix = string.Join("_", matrix.FieldPath); // Read all rows of a given matrix type: // // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[0] = buffer.; // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[1] = buffer.; // ... // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[N] = buffer.; for (int j = 0; j < matrix.Rows; j++) { writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.{fieldPath})[0] = buffer.{fieldNamePrefix}_{j};"); } break; } } } } } }