/// <summary>
 /// Explore the ShaderSource and add the necessary shaders
 /// </summary>
 /// <param name="shaderSource">the ShaderSource to explore</param>
 /// <param name="macros">the macros used</param>
 /// <returns></returns>
 public HashSet<ModuleMixinInfo> LoadShaderSource(ShaderSource shaderSource, SiliconStudio.Shaders.Parser.ShaderMacro[] macros)
 {
     var mixinsToAnalyze = new HashSet<ModuleMixinInfo>();
     ExtendLibrary(shaderSource, macros, mixinsToAnalyze);
     ReplaceMixins(mixinsToAnalyze); // no longer replace mixin, redo analysis everytime since there is no way to correctly detect something changed
     return mixinsToAnalyze;
 }
Example #2
0
        public CompilerResults Compile(ShaderSource shaderSource, CompilerParameters compilerParameters)
        {
            ShaderMixinSource mixinToCompile;
            var shaderMixinGeneratorSource = shaderSource as ShaderMixinGeneratorSource;

            if (shaderMixinGeneratorSource != null)
            {
                mixinToCompile = ShaderMixinManager.Generate(shaderMixinGeneratorSource.Name, compilerParameters);
            }
            else
            {
                mixinToCompile = shaderSource as ShaderMixinSource;
                var shaderClassSource = shaderSource as ShaderClassSource;

                if (shaderClassSource != null)
                {
                    mixinToCompile = new ShaderMixinSource { Name = shaderClassSource.ClassName };
                    mixinToCompile.Mixins.Add(shaderClassSource);
                }

                if (mixinToCompile == null)
                {
                    throw new ArgumentException("Unsupported ShaderSource type [{0}]. Supporting only ShaderMixinSource/pdxfx, ShaderClassSource", "shaderSource");
                }
                if (string.IsNullOrEmpty(mixinToCompile.Name))
                {
                    throw new ArgumentException("ShaderMixinSource must have a name", "shaderSource");
                }
            }

            // Copy global parameters to used Parameters by default, as it is used by the compiler
            mixinToCompile.UsedParameters.Set(CompilerParameters.GraphicsPlatformKey, compilerParameters.Platform);
            mixinToCompile.UsedParameters.Set(CompilerParameters.GraphicsProfileKey, compilerParameters.Profile);
            mixinToCompile.UsedParameters.Set(CompilerParameters.DebugKey, compilerParameters.Debug);

            // Compile the whole mixin tree
            var compilerResults = new CompilerResults { Module = string.Format("EffectCompile [{0}]", mixinToCompile.Name) };
            var bytecode = Compile(mixinToCompile, compilerParameters);

            // Since bytecode.Result is a struct, we check if any of its member has been set to know if it's valid
            if (bytecode.Result.CompilationLog != null || bytecode.Task != null)
            {
                if (bytecode.Result.CompilationLog != null)
                {
                    bytecode.Result.CompilationLog.CopyTo(compilerResults);
                }
                compilerResults.Bytecode = bytecode;
                compilerResults.UsedParameters = mixinToCompile.UsedParameters;
            }
            return compilerResults;
        }
Example #3
0
        /// <summary>
        /// create the context for each composition by cloning their dependencies
        /// </summary>
        /// <param name="shaderSource">the entry ShaderSource (root)</param>
        /// <param name="dictionary">the ouputed compositions</param>
        /// <param name="compilationContext">the compilation context</param>
        /// <param name="cloneContext">The clone context.</param>
        /// <returns>a list of all the needed mixins</returns>
        private static List <ModuleMixin> BuildCompositionsDictionary(ShaderSource shaderSource, CompositionDictionary dictionary, ShaderCompilationContext compilationContext, CloneContext cloneContext, LoggerResult log)
        {
            if (shaderSource is ShaderMixinSource)
            {
                var shaderMixinSource = shaderSource as ShaderMixinSource;

                var finalModule = compilationContext.GetModuleMixinFromShaderSource(shaderSource);

                //PerformanceLogger.Start(PerformanceStage.DeepClone);
                finalModule = finalModule.DeepClone(new CloneContext(cloneContext));
                //PerformanceLogger.Pause(PerformanceStage.DeepClone);

                foreach (var composition in shaderMixinSource.Compositions)
                {
                    //look for the key
                    var foundVars = finalModule.FindAllVariablesByName(composition.Key).Where(value => value.Variable.Qualifiers.Contains(XenkoStorageQualifier.Compose)).ToList();

                    if (foundVars.Count > 1)
                    {
                        log.Error(XenkoMessageCode.ErrorAmbiguousComposition, new SourceSpan(), composition.Key);
                    }
                    else if (foundVars.Count > 0)
                    {
                        Variable foundVar     = foundVars[0].Variable;
                        var      moduleMixins = BuildCompositionsDictionary(composition.Value, dictionary, compilationContext, cloneContext, log);
                        if (moduleMixins == null)
                        {
                            return(null);
                        }

                        dictionary.Add(foundVar, moduleMixins);
                    }
                    else
                    {
                        // No matching variable was found
                        // TODO: log a message?
                    }
                }
                return(new List <ModuleMixin> {
                    finalModule
                });
            }


            if (shaderSource is ShaderClassSource)
            {
                var finalModule = compilationContext.GetModuleMixinFromShaderSource(shaderSource);

                //PerformanceLogger.Start(PerformanceStage.DeepClone);
                finalModule = finalModule.DeepClone(new CloneContext(cloneContext));
                //PerformanceLogger.Pause(PerformanceStage.DeepClone);

                return(new List <ModuleMixin> {
                    finalModule
                });
            }

            if (shaderSource is ShaderArraySource)
            {
                var shaderArraySource = shaderSource as ShaderArraySource;
                var compositionArray  = new List <ModuleMixin>();
                foreach (var shader in shaderArraySource.Values)
                {
                    var mixin = BuildCompositionsDictionary(shader, dictionary, compilationContext, cloneContext, log);
                    if (mixin == null)
                    {
                        return(null);
                    }
                    compositionArray.AddRange(mixin);
                }
                return(compositionArray);
            }

            return(null);
        }
Example #4
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form
            {
                ClientSize = new Size(800, 600),
                Text       = "Tutorial 21: Specular Mapping",
            };

            using (var device = LightDevice.Create(form))
            {
                //---------------------
                // Target & Pipeline
                //---------------------

                var target = new RenderTarget(device.GetDefaultTarget(),
                                              device.CreateDefaultDepthStencilTarget());
                target.Apply();

                Pipeline pipeline = device.CompilePipeline(InputTopology.Triangle,
                                                           ShaderSource.FromResource("SpecMap_vs.fx", ShaderType.Vertex),
                                                           ShaderSource.FromResource("SpecMap_ps.fx", ShaderType.Pixel));
                pipeline.Apply();

                //---------------------
                // Vertex buffer
                //---------------------

                var          vertexDataProcessor = pipeline.CreateVertexDataProcessor <ModelVertex>();
                VertexBuffer vertexBuffer;
                using (var stream = Assembly.GetEntryAssembly().GetManifestResourceStream("Tutorial21.cube.txt"))
                {
                    vertexBuffer = vertexDataProcessor.CreateImmutableBuffer(Model.ReadModelFile(stream));
                }

                //---------------------
                // Constant buffer (Matrix, VS)
                //---------------------

                var matrixBuffer = pipeline.CreateConstantBuffer <MatrixBuffer>();
                pipeline.SetConstant(ShaderType.Vertex, 0, matrixBuffer);

                void SetupProjMatrix()
                {
                    matrixBuffer.Value.Projection =
                        device.CreatePerspectiveFieldOfView((float)Math.PI / 4).Transpose();
                }

                device.ResolutionChanged += (sender, e) => SetupProjMatrix();

                matrixBuffer.Value.World = Matrix4x4.Identity.Transpose();
                SetupProjMatrix();

                //---------------------
                // Constant buffer (Camera, VS)
                //---------------------

                var cameraBuffer = pipeline.CreateConstantBuffer <CameraBuffer>();
                pipeline.SetConstant(ShaderType.Vertex, 1, cameraBuffer);

                //---------------------
                // Constant buffer (Light, PS)
                //---------------------

                var lightBuffer = pipeline.CreateConstantBuffer <LightBuffer>();
                pipeline.SetConstant(ShaderType.Pixel, 0, lightBuffer);

                lightBuffer.Value.DiffuseColor   = Color.White.WithAlpha(1);
                lightBuffer.Value.LightDirection = Vector3.Normalize(new Vector3(0, 0, 1));
                lightBuffer.Value.SpecularColor  = Color.White.WithAlpha(1);
                lightBuffer.Value.SpecularPower  = 16;
                lightBuffer.Update();

                //---------------------
                // Texture
                //---------------------

                Texture2D CreateTextureFromResource(string name)
                {
                    using (var stream = Assembly.GetEntryAssembly().GetManifestResourceStream($"Tutorial21.{name}.dds"))
                    {
                        return(device.CreateTexture2D(stream));
                    }
                }

                var tex1 = CreateTextureFromResource("stone02");
                var tex2 = CreateTextureFromResource("bump02");
                var tex3 = CreateTextureFromResource("spec02");
                pipeline.SetResource(0, tex1);
                pipeline.SetResource(1, tex2);
                pipeline.SetResource(2, tex3);

                //---------------------
                // Camera
                //---------------------

                var camera = new Camera();

                //---------------------
                // Start main loop
                //---------------------

                form.Show();

                var frameCounter = new FrameCounter();
                frameCounter.Start();

                device.RunMultithreadLoop(delegate()
                {
                    // Update matrix buffer

                    var time         = frameCounter.NextFrame() / 1000;
                    Matrix4x4 rotate = Matrix4x4.CreateRotationX(time * 3) *
                                       Matrix4x4.CreateRotationY(time * 6) *
                                       Matrix4x4.CreateRotationZ(time * 4);

                    matrixBuffer.Value.World *= rotate;
                    matrixBuffer.Value.View   = camera.GetViewMatrix().Transpose();
                    matrixBuffer.Update();

                    // Update camera buffer

                    cameraBuffer.Value.CameraPosition = camera.Position;
                    cameraBuffer.Update();

                    // Clear and draw

                    target.ClearAll();
                    vertexBuffer.DrawAll();

                    device.Present(true);
                });
            }
        }
Example #5
0
 public LightSkyBoxShaderGroup(ShaderSource mixin) : base(mixin)
 {
     HasEffectPermutations = true;
 }
 /// <summary>
 /// Get the module mixin based on the ShaderSource
 /// </summary>
 /// <param name="shaderSource">the ShaderSource</param>
 /// <returns>the ModuleMixin</returns>
 public ModuleMixin GetModuleMixinFromShaderSource(ShaderSource shaderSource)
 {
     var found = MixinInfos.FirstOrDefault(x => x.ShaderSource.Equals(shaderSource));
     return found == null ? null : found.Mixin;
 }
 /// <summary>
 /// Explore the ShaderSource and add the necessary shaders
 /// </summary>
 /// <param name="shaderSource">the ShaderSource to explore</param>
 /// <param name="macros">the macros used</param>
 private void ExtendLibrary(ShaderSource shaderSource, SiliconStudio.Shaders.Parser.ShaderMacro[] macros, HashSet<ModuleMixinInfo> mixinToAnalyze)
 {
     if (shaderSource is ShaderMixinSource)
     {
         var newMacros = MergeMacroSets((ShaderMixinSource)shaderSource, macros);
         mixinToAnalyze.Add(GetModuleMixinInfo(shaderSource, newMacros));
         foreach (var composition in ((ShaderMixinSource)shaderSource).Compositions)
             ExtendLibrary(composition.Value, newMacros, mixinToAnalyze);
     }
     else if (shaderSource is ShaderClassSource)
         mixinToAnalyze.Add(GetModuleMixinInfo(shaderSource, macros));
     else if (shaderSource is ShaderArraySource)
     {
         foreach (var shader in ((ShaderArraySource)shaderSource).Values)
             ExtendLibrary(shader, macros, mixinToAnalyze);
     }
 }
Example #8
0
        private void CanvasLoad(object sender, EventArgs e)
        {
            GL.ClearColor(0.59f, 0.59f, 0.59f, 1.0f);
            GL.Enable(EnableCap.DepthTest);

            var LightPos = new Vector3(0.0f, -0.5f, 0.5f);

            var pointLight = new PointLight
            {
                Ambient   = new Vector3(0.2f, 0.4f, 0.6f),
                Diffuse   = new Vector3(0.8f, 0.9f, 0.5f),
                Specular  = new Vector3(1.0f, 0.8f, 1.0f),
                Position  = new Vector3(0.0f, -0.5f, 0.5f),
                Constant  = 1.0f,
                Linear    = 0.35f,
                Quadratic = 0.44f,
                Source    = new Cube(LightPos, 0.05f, Material.LightSource, Matrix4.Identity),
            };

            var spotLight = new SpotLight
            {
                Ambient     = new Vector3(0.2f, 0.4f, 0.6f),
                Diffuse     = new Vector3(0.8f, 0.9f, 0.5f),
                Specular    = new Vector3(1.0f, 0.8f, 1.0f),
                Position    = LightPos,
                Direction   = new Vector3(-0.2f, 0.45f, 0.0f) - LightPos,
                Constant    = 1.0f,
                Linear      = 0.35f,
                Quadratic   = 0.44f,
                CutOff      = (float)Math.Cos(MathHelper.DegreesToRadians(18.5)),
                OuterCutOff = (float)Math.Cos(MathHelper.DegreesToRadians(29.5)),
            };

            var spotLight1 = new SpotLight
            {
                Ambient     = new Vector3(0.2f, 0.4f, 0.6f),
                Diffuse     = new Vector3(0.8f, 0.9f, 0.5f),
                Specular    = new Vector3(1.0f, 0.8f, 1.0f),
                Position    = LightPos,
                Direction   = new Vector3(0.2f, -0.9f, 0.0f) - LightPos,
                Constant    = 1.0f,
                Linear      = 0.35f,
                Quadratic   = 0.44f,
                CutOff      = (float)Math.Cos(MathHelper.DegreesToRadians(18.5)),
                OuterCutOff = (float)Math.Cos(MathHelper.DegreesToRadians(29.5)),
            };

            Matrix4 model    = Matrix4.Identity;
            Matrix4 cylinder = Matrix4.Mult(Matrix4.CreateTranslation(0.4f, 0.0f, 0.0f), model);

            cylinder = Matrix4.Mult(Matrix4.CreateTranslation(0.0f, 0.1f, 0.0f), cylinder);
            Matrix4 conus = Matrix4.Mult(Matrix4.CreateTranslation(-0.4f, 0.4f, 0.0f), model);
            Matrix4 cube  = Matrix4.Mult(Matrix4.CreateTranslation(0.1f, 0.5f, 0.0f), model);

            GraphicScene = new Scene(ShaderSource.Phong(1, 0))
            {
                Shapes = new List <Shape>
                {
                    new Cone(new Vector3(0.0f, 0.0f, 0.0f), 0.1f, 0.3f, Material.Ruby, conus),
                    new Cube(new Vector3(0.0f, 0.0f, 0.15f), 0.3f, Material.Pearl, cube),
                    new Cylinder(new Vector3(0.0f, 0.0f, 0.0f), 0.1f, 0.3f, Material.Bronze, cylinder),
                    new Sheet(new Vector3(1.0f, -1.0f, 0.0f), new Vector3(1.0f, 1.0f, 0.0f), new Vector3(-1.0f, -1.0f, 0.0f), new Vector3(-1.0f, 1.0f, 0.0f), Material.YellowPlastic, Matrix4.Identity),
                    new Sheet(new Vector3(1.0f, 1.0f, 0.0f), new Vector3(1.0f, -1.0f, 0.0f), new Vector3(1.0f, 1.0f, 1.0f), new Vector3(1.0f, -1.0f, 1.0f), Material.YellowPlastic, Matrix4.Identity),
                    new Sheet(new Vector3(-1.0f, 1.0f, 0.0f), new Vector3(1.0f, 1.0f, 0.0f), new Vector3(-1.0f, 1.0f, 1.0f), new Vector3(1.0f, 1.0f, 1.0f), Material.YellowPlastic, Matrix4.Identity),
                },
                //Lights = new List<LightSource>
                //{
                //    pointLight,
                //},
            };

            GraphicScene.Add(pointLight);
            //GraphicScene.Add(spotLight);
            //GraphicScene.Add(spotLight1);

            isLoad      = true;
            Status.Text = "Готово";
        }
Example #9
0
 public bool AreEqual(ShaderSource shaderSource, Xenko.Core.Shaders.Parser.ShaderMacro[] macros)
 {
     return(ShaderSource.Equals(shaderSource) && macros.All(macro => Macros.Any(x => x.Name == macro.Name && x.Definition == macro.Definition)) && Macros.All(macro => macros.Any(x => x.Name == macro.Name && x.Definition == macro.Definition)));
 }
Example #10
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form
            {
                ClientSize = new Size(800, 600),
                Text       = "Tutorial 7: 3D Model Rendering",
            };

            using (var device = LightDevice.Create(form))
            {
                //---------------------
                // Target & Pipeline
                //---------------------

                var target = new RenderTarget(device.GetDefaultTarget(),
                                              device.CreateDefaultDepthStencilTarget());
                target.Apply();

                Pipeline pipeline = device.CompilePipeline(InputTopology.Triangle,
                                                           ShaderSource.FromResource("Light_vs.fx", ShaderType.Vertex),
                                                           ShaderSource.FromResource("Light_ps.fx", ShaderType.Pixel));
                pipeline.Apply();

                //---------------------
                // Vertex buffer
                //---------------------

                var          vertexDataProcessor = pipeline.CreateVertexDataProcessor <ModelVertex>();
                VertexBuffer vertexBuffer;
                using (var stream = Assembly.GetEntryAssembly().GetManifestResourceStream("Tutorial07.Cube.txt"))
                {
                    vertexBuffer = vertexDataProcessor.CreateImmutableBuffer(Model.ReadModelFile(stream));
                }

                //---------------------
                // Constant buffer (VS)
                //---------------------

                var constantBufferVS = pipeline.CreateConstantBuffer <VSConstants>();
                pipeline.SetConstant(ShaderType.Vertex, 0, constantBufferVS);

                void SetupProjMatrix()
                {
                    constantBufferVS.Value.Projection =
                        device.CreatePerspectiveFieldOfView((float)Math.PI / 4).Transpose();
                }

                device.ResolutionChanged += (sender, e) => SetupProjMatrix();

                constantBufferVS.Value.World = Matrix4x4.Identity.Transpose();
                SetupProjMatrix();

                //---------------------
                // Constant buffer (PS)
                //---------------------

                var constantBufferPS = pipeline.CreateConstantBuffer <PSConstants>();
                pipeline.SetConstant(ShaderType.Pixel, 0, constantBufferPS);

                constantBufferPS.Value.Diffuse  = Color.White.WithAlpha(1);
                constantBufferPS.Value.LightDir = Vector3.Normalize(new Vector3(-3f, -4f, 6f));
                constantBufferPS.Update();

                //---------------------
                // Texture
                //---------------------

                Texture2D tex;
                using (var stream = Assembly.GetEntryAssembly().GetManifestResourceStream("Tutorial07.seafloor.dds"))
                {
                    tex = device.CreateTexture2D(stream);
                }
                pipeline.SetResource(0, tex);

                //---------------------
                // Camera
                //---------------------

                var camera = new Camera();

                //---------------------
                // Start main loop
                //---------------------

                form.Show();

                var frameCounter = new FrameCounter();
                frameCounter.Start();

                device.RunMultithreadLoop(delegate()
                {
                    // Update matrix

                    var time         = frameCounter.NextFrame() / 1000;
                    Matrix4x4 rotate = Matrix4x4.CreateRotationX(time * 3) *
                                       Matrix4x4.CreateRotationY(time * 6) *
                                       Matrix4x4.CreateRotationZ(time * 4);

                    constantBufferVS.Value.World *= rotate;
                    constantBufferVS.Value.View   = camera.GetViewMatrix().Transpose();
                    constantBufferVS.Update();

                    // Clear and draw
                    target.ClearAll();
                    vertexBuffer.DrawAll();

                    device.Present(true);
                });
            }
        }
Example #11
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form();

            form.ClientSize = new Size(800, 600);

            using (var device = LightDevice.Create(form))
            {
                var target = new RenderTargetList(device.GetDefaultTarget());
                target.Apply();

                Pipeline pipeline = device.CompilePipeline(InputTopology.Triangle,
                                                           ShaderSource.FromResource("Shader.fx", ShaderType.Vertex | ShaderType.Pixel));

                Texture2D texture;
                using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("TextureTriangle.Hiyori.png"))
                {
                    using (var bitmap = new Bitmap(stream))
                    {
                        texture = device.CreateTexture2D(bitmap);
                        pipeline.SetResource(0, texture);
                    }
                }

                pipeline.Apply();

                var input  = pipeline.CreateVertexDataProcessor <Vertex>();
                var buffer = input.CreateImmutableBuffer(new[] {
                    new Vertex {
                        TexCoord = new Vector4(0, 0, 0, 0), Position = new Vector4(-0.5f, 0.5f, 0.5f, 1.0f)
                    },
                    new Vertex {
                        TexCoord = new Vector4(1, 0, 0, 0), Position = new Vector4(0.5f, 0.5f, 0.5f, 1.0f)
                    },
                    new Vertex {
                        TexCoord = new Vector4(0, 1, 0, 0), Position = new Vector4(-0.5f, -0.5f, 0.5f, 1.0f)
                    },

                    new Vertex {
                        TexCoord = new Vector4(0, 1, 0, 0), Position = new Vector4(-0.5f, -0.5f, 0.5f, 1.0f)
                    },
                    new Vertex {
                        TexCoord = new Vector4(1, 0, 0, 0), Position = new Vector4(0.5f, 0.5f, 0.5f, 1.0f)
                    },
                    new Vertex {
                        TexCoord = new Vector4(1, 1, 0, 0), Position = new Vector4(0.5f, -0.5f, 0.5f, 1.0f)
                    },
                });

                form.Show();
                device.RunMultithreadLoop(delegate()
                {
                    target.ClearAll();
                    buffer.DrawAll();
                    device.Present(true);
                });
            }
        }
        //Deferred Renderer Rework - New GBuffer -
        //32:32:32 WorldPos, (16b:SPARE, 16b:materialIdx)
        //8:8:8 Norm, 8:SPARE
        //reproject z buffer and recompute chain for culling

        public DeferredRenderer(Framebuffer[] fbufs, LightManager man)
        {
            lMan = man;

            InfoBindings  = new TextureBinding[fbufs.Length];
            InfoBindings2 = new TextureBinding[fbufs.Length];
            DepthBindings = new TextureBinding[fbufs.Length];
            Framebuffers  = new Framebuffer[fbufs.Length];
            HiZMap        = new TextureView[fbufs.Length][];
            views         = new ViewData[fbufs.Length];
            HiZMapUBO     = new UniformBuffer(false);
            unsafe
            {
                int    off = 0;
                float *fp  = (float *)HiZMapUBO.Update();
                fp += 4;
                for (int i = 0; i < views.Length; i++)
                {
                    views[i] = new ViewData()
                    {
                        depthBuf = new Texture()
                        {
                            Width           = fbufs[i].Width,
                            Height          = fbufs[i].Height,
                            Depth           = 1,
                            Format          = PixelInternalFormat.DepthComponent32f,
                            GenerateMipmaps = false,
                            LayerCount      = 1,
                            LevelCount      = 1,
                            Target          = TextureTarget.Texture2D
                        }.Build(),
                        infoTex = new Texture()
                        {
                            Width           = fbufs[i].Width,
                            Height          = fbufs[i].Height,
                            Depth           = 1,
                            Format          = PixelInternalFormat.Rgba32f,
                            GenerateMipmaps = false,
                            LayerCount      = 1,
                            LevelCount      = 1,
                            Target          = TextureTarget.Texture2D
                        }.Build(),
                        infoTex2 = new Texture()
                        {
                            Width           = fbufs[i].Width,
                            Height          = fbufs[i].Height,
                            Depth           = 1,
                            Format          = PixelInternalFormat.Rgba8,
                            GenerateMipmaps = false,
                            LayerCount      = 1,
                            LevelCount      = 1,
                            Target          = TextureTarget.Texture2D
                        }.Build(),
                        hiZ = new Texture()
                        {
                            Width           = fbufs[i].Width,
                            Height          = fbufs[i].Height,
                            Depth           = 1,
                            Format          = PixelInternalFormat.Rg32f,
                            GenerateMipmaps = false,
                            LayerCount      = 1,
                            LevelCount      = (int)(MathHelper.Log2((ulong)Math.Max(fbufs[i].Width, fbufs[i].Height)) + 1),
                            Target          = TextureTarget.Texture2D
                        }.Build(),
                        gbuffer = new Framebuffer(fbufs[i].Width, fbufs[i].Height),
                    };

                    views[i].depthView = new TextureView()
                    {
                        BaseLayer  = 0,
                        BaseLevel  = 0,
                        Format     = PixelInternalFormat.DepthComponent32f,
                        LayerCount = 1,
                        LevelCount = 1,
                        Target     = TextureTarget.Texture2D
                    }.Build(views[i].depthBuf);

                    views[i].infoView = new TextureView()
                    {
                        BaseLayer  = 0,
                        BaseLevel  = 0,
                        Format     = PixelInternalFormat.Rgba32f,
                        LayerCount = 1,
                        LevelCount = 1,
                        Target     = TextureTarget.Texture2D
                    }.Build(views[i].infoTex);

                    views[i].infoView2 = new TextureView()
                    {
                        BaseLayer  = 0,
                        BaseLevel  = 0,
                        Format     = PixelInternalFormat.Rgba8,
                        LayerCount = 1,
                        LevelCount = 1,
                        Target     = TextureTarget.Texture2D
                    }.Build(views[i].infoTex2);

                    views[i].hiZView = new TextureView[views[i].hiZ.LevelCount];
                    for (int j = 0; j < views[i].hiZView.Length; j++)
                    {
                        views[i].hiZView[j] = new TextureView()
                        {
                            BaseLayer  = 0,
                            BaseLevel  = j,
                            Format     = PixelInternalFormat.Rg32f,
                            LayerCount = 1,
                            LevelCount = 1,
                            Target     = TextureTarget.Texture2D,
                        }.Build(views[i].hiZ);
                        var f_arr = (float[])views[i].hiZView[j].GetImageHandle().SetResidency(Residency.Resident, AccessMode.ReadWrite);
                        for (int q = 0; q < f_arr.Length; q++)
                        {
                            *(fp++) = f_arr[q];
                        }
                        fp += 2;
                    }
                    views[i].hiZTex = new TextureView()
                    {
                        BaseLayer  = 0,
                        BaseLevel  = 0,
                        Format     = PixelInternalFormat.Rg32f,
                        LayerCount = 1,
                        LevelCount = views[i].hiZView.Length,
                        Target     = TextureTarget.Texture2D
                    }.Build(views[i].hiZ);

                    var sampler = new TextureSampler();
                    sampler.SetEnableLinearFilter(false, true, false);
                    sampler.MinReadLevel = 0;
                    sampler.MaxReadLevel = views[i].hiZView.Length;
                    sampler.SetTileMode(TileMode.ClampToBorder, TileMode.ClampToBorder);

                    views[i].hiZBinding = new TextureBinding()
                    {
                        View    = views[i].hiZTex,
                        Sampler = sampler
                    };
                    var f_arr_ = (float[])views[i].hiZBinding.GetTextureHandle().SetResidency(Residency.Resident);
                    for (int q = 0; q < f_arr_.Length; q++)
                    {
                        *(fp++) = f_arr_[q];
                    }
                    fp += 2;

                    views[i].gbuffer[FramebufferAttachment.DepthAttachment]  = views[i].depthView;
                    views[i].gbuffer[FramebufferAttachment.ColorAttachment0] = views[i].infoView;
                    views[i].gbuffer[FramebufferAttachment.ColorAttachment1] = views[i].infoView2;
                    Framebuffers[i] = views[i].gbuffer;

                    views[i].program = new ShaderProgram(
                        ShaderSource.Load(ShaderType.VertexShader, "Shaders/RenderToTexture/FrameBufferTriangle/vertex.glsl"),
                        ShaderSource.Load(ShaderType.FragmentShader, "Shaders/RenderToTexture/FrameBufferTriangle/fragment.glsl")
                        );
                    views[i].copy = new ShaderProgram(
                        ShaderSource.Load(ShaderType.ComputeShader, "Shaders/HiZ/copy.glsl", $"#define MIP_COUNT {views[i].hiZView.Length}")
                        );
                    views[i].copyState = new RenderState(null, views[i].copy, null, new UniformBuffer[] { Engine.GlobalParameters, HiZMapUBO }, false, false, DepthFunc.Always, InverseDepth.Far, InverseDepth.Near, BlendFactor.SrcAlpha, BlendFactor.OneMinusSrcAlpha, Vector4.Zero, InverseDepth.ClearDepth, CullFaceMode.Back);
                    views[i].mipchain  = new ShaderProgram(
                        ShaderSource.Load(ShaderType.ComputeShader, "Shaders/HiZ/mipchain.glsl", $"#define MIP_COUNT {views[i].hiZView.Length}")
                        );
                    views[i].mipchainState = new RenderState(null, views[i].mipchain, null, new UniformBuffer[] { Engine.GlobalParameters, HiZMapUBO }, false, false, DepthFunc.Always, InverseDepth.Far, InverseDepth.Near, BlendFactor.SrcAlpha, BlendFactor.OneMinusSrcAlpha, Vector4.Zero, InverseDepth.ClearDepth, CullFaceMode.Back);

                    views[i].state = new RenderState(fbufs[i], views[i].program, null, new UniformBuffer[] { Engine.GlobalParameters }, false, true, DepthFunc.Always, InverseDepth.Far, InverseDepth.Near, BlendFactor.SrcAlpha, BlendFactor.OneMinusSrcAlpha, Vector4.Zero, InverseDepth.ClearDepth, CullFaceMode.None);

                    InfoBindings[i] = new TextureBinding()
                    {
                        View    = views[i].infoView,
                        Sampler = TextureSampler.Default
                    };
                    InfoBindings[i].GetTextureHandle().SetResidency(Residency.Resident);

                    InfoBindings2[i] = new TextureBinding()
                    {
                        View    = views[i].infoView2,
                        Sampler = TextureSampler.Default
                    };
                    InfoBindings2[i].GetTextureHandle().SetResidency(Residency.Resident);

                    DepthBindings[i] = new TextureBinding()
                    {
                        View    = views[i].depthView,
                        Sampler = TextureSampler.Default,
                    };
                    DepthBindings[i].GetTextureHandle().SetResidency(Residency.Resident);

                    HiZMap[i] = views[i].hiZView;

                    views[i].cBuffer = new CommandBuffer();
                    views[i].cBuffer.SetRenderState(views[i].state);
                    views[i].cBuffer.Draw(PrimitiveType.Triangles, 0, 3, 1, 0);
                }
                HiZMapUBO.UpdateDone();
            }
        }
Example #13
0
        public static void Run()
        {
            GraphicsContext context = new GraphicsContext()
            {
                Camera = new FirstPersonCamera(new Vector3(4, 3, 3), Vector3.UnitY)
            };
            Matrix4 World = Matrix4.Identity;


            VoxelTypeMap v = new VoxelTypeMap();

            v[0] = new VoxelTypeMap.VoxelTypeData()
            {
                Color   = Vector4.One,
                Visible = false
            };

            v[1] = new VoxelTypeMap.VoxelTypeData()
            {
                Color   = Vector4.UnitY * 0.7f + Vector4.UnitW,
                Visible = true
            };

            v[2] = new VoxelTypeMap.VoxelTypeData()
            {
                Color   = Vector4.UnitX + Vector4.UnitW,
                Visible = true
            };

            BlockManager man = new BlockManager();

            man.Side       = 32;
            man.VoxelTypes = v;

            //Rendering stuff
            ShaderProgram prog = null;

            GraphicsDevice.Load += () =>
            {
                //GraphicsDevice.Winding = FaceWinding.Clockwise;
                GraphicsDevice.CullMode         = OpenTK.Graphics.OpenGL4.CullFaceMode.Back;
                GraphicsDevice.DepthTestEnabled = true;
                GraphicsDevice.Window.KeyUp    += (k, e) =>
                {
                    if (e.Key == OpenTK.Input.Key.Z)
                    {
                        GraphicsDevice.Wireframe = !GraphicsDevice.Wireframe;
                    }
                    else if (e.Key == OpenTK.Input.Key.C)
                    {
                        GraphicsDevice.CullEnabled = !GraphicsDevice.CullEnabled;
                    }
                };

                Random rng = new Random(0);
                double n   = 64;

                v.UpdateBuffers();
                GraphicsDevice.SetBufferTexture(0, v.ColorData);

                ShaderSource vShader = ShaderSource.Load(OpenTK.Graphics.OpenGL4.ShaderType.VertexShader, "Testing/VoxTest/vertex.glsl");
                ShaderSource fShader = ShaderSource.Load(OpenTK.Graphics.OpenGL4.ShaderType.FragmentShader, "Testing/VoxTest/fragment.glsl");

                prog = new ShaderProgram(vShader, fShader);
                prog.Set("materialColors", 0);
            };

            GraphicsDevice.Update += (e) =>
            {
                context.Update(e);

                //World *= Matrix4.CreateRotationY(0.01f);

                prog.Set("World", Matrix4.Identity);
                prog.Set("View", context.View);
                prog.Set("Proj", context.Projection);
                prog.Set("Fcoef", (float)(2.0f / Math.Log(1000001) / Math.Log(2)));
                prog.Set("lightDir", new Vector3(5, 10, 5).Normalized());
            };


            GraphicsDevice.Render += (e) =>
            {
                GraphicsDevice.Clear();

                for (int k = -2; k < 0; k++)
                {
                    Vector3 a = new Vector3();
                    a.Y = k * man.Side;
                    for (int i = -5; i <= 5; i++)
                    {
                        a.Z = i * man.Side;
                        for (int j = -5; j <= 5; j++)
                        {
                            a.X = j * man.Side;
                            Vector3 dir = (context.Camera as FirstPersonCamera).Direction;
                            if (Vector3.Dot(dir.Normalized(), a.Normalized()) >= -0.3)
                            {
                                //Chunk c = man.Draw(-Vector3.UnitY * 123, out World);
                                Chunk c = man.Draw(context.Camera.Position + a, out World);
                                if (c.ChunkReady)
                                {
                                    c.Bind();
                                    prog.Set("World", World);

                                    prog.Set("range1", c.NormalOffsets[1]);
                                    prog.Set("range2", c.NormalOffsets[2]);
                                    prog.Set("range3", c.NormalOffsets[3]);
                                    prog.Set("range4", c.NormalOffsets[4]);
                                    prog.Set("range5", c.NormalOffsets[5]);
                                    GraphicsDevice.SetShaderProgram(prog);


                                    GraphicsDevice.Draw(OpenTK.Graphics.OpenGL4.PrimitiveType.Triangles, 0, c.NormalGroupSizes[6]);
                                }
                            }
                        }
                    }
                }

                GraphicsDevice.SwapBuffers();
            };

            GraphicsDevice.Name = "Voxel Test";
            GraphicsDevice.Run(60, 0);
            if (GraphicsDevice.Cleanup != null)
            {
                GraphicsDevice.Cleanup();
            }
        }
        public static void Run()
        {
            ShaderProgram prog = null, terrProg = null;
            Texture       tex = null, t2 = null;

            GraphicsContext context = new GraphicsContext()
            {
                Camera = new FirstPersonCamera(new Vector3(4, 3, 3), Vector3.UnitY)
            };

            BitmapTextureSource bmpTex, b2, b3;

            bmpTex = TextDrawer.CreateWriter("Times New Roman", FontStyle.Regular).Write("Hello!", 200, System.Drawing.Color.White);
            b2     = new BitmapTextureSource("test.jpg", 0);
            b3     = new BitmapTextureSource("test.png", 0);


            Texture fbufTex = null, t3 = null;
            FramebufferTextureSource fbufTexSrc = new FramebufferTextureSource(256, 256, 0);
            Framebuffer fbuf = null;

            Matrix4      World = Matrix4.Identity;
            EngineObject eObj = null, fsq = null;
            float        timer = 0;

            CubeMapTextureSource tFace = new CubeMapTextureSource(CubeMapTextureSource.CubeMapFace.PositiveY, b3),
                                 bFace = new CubeMapTextureSource(CubeMapTextureSource.CubeMapFace.PositiveX, b3),
                                 lFace = new CubeMapTextureSource(CubeMapTextureSource.CubeMapFace.PositiveZ, b3),
                                 rFace = new CubeMapTextureSource(CubeMapTextureSource.CubeMapFace.NegativeX, b3),
                                 fFace = new CubeMapTextureSource(CubeMapTextureSource.CubeMapFace.NegativeY, b3),
                                 hFace = new CubeMapTextureSource(CubeMapTextureSource.CubeMapFace.NegativeZ, b3);

            GraphicsDevice.Load += () =>
            {
                // setup settings, load textures, sounds
                GraphicsDevice.Wireframe        = false;
                GraphicsDevice.AlphaEnabled     = true;
                GraphicsDevice.DepthTestEnabled = true;
                GraphicsDevice.CullEnabled      = false;
                GraphicsDevice.CullMode         = CullFaceMode.Back;

                eObj = new EngineObject();
                float[] data =
                { -1, -1, 1,
                  1,  -1, 1,
                  0,   1, 1 };

                uint[] indexData = new uint[]
                {
                    0, 1, 2
                };


                ShaderSource vert  = ShaderSource.Load(ShaderType.VertexShader, "Testing/TG_A/vertex.glsl");
                ShaderSource frag  = ShaderSource.Load(ShaderType.FragmentShader, "Testing/TG_A/fragment.glsl");
                ShaderSource tctrl = ShaderSource.Load(ShaderType.TessControlShader, "Testing/TG_A/tesscontrol.glsl");
                ShaderSource teval = ShaderSource.Load(ShaderType.TessEvaluationShader, "Testing/TG_A/tessdomain.glsl");

                ShaderSource vA = ShaderSource.Load(ShaderType.VertexShader, "Shaders/TerrainGen/vertex.glsl");
                ShaderSource fA = ShaderSource.Load(ShaderType.FragmentShader, "Shaders/TerrainGen/fragment.glsl");
                terrProg = new ShaderProgram(vA, fA);
                terrProg.Set("World", Matrix4.Identity);

                fbuf    = new Framebuffer(256, 256);
                fbufTex = new Texture();
                fbufTex.SetData(fbufTexSrc);
                fbuf[FramebufferAttachment.ColorAttachment0] = fbufTex;

                fsq = FullScreenQuadFactory.Create();

                t3 = new Texture();
                t3.SetData(tFace);
                t3.SetData(bFace);
                t3.SetData(lFace);
                t3.SetData(rFace);
                t3.SetData(fFace);
                t3.SetData(hFace);
                t3.SetEnableLinearFilter(true);
                t3.SetAnisotropicFilter(Texture.MaxAnisotropy);

                tex = new Texture();
                tex.SetData(bmpTex);
                tex.SetAnisotropicFilter(Texture.MaxAnisotropy);

                t2 = new Texture();
                t2.SetData(b3);
                t2.SetAnisotropicFilter(Texture.MaxAnisotropy);


                prog = new ShaderProgram(vert, tctrl, teval, frag);
                prog.Set("img", 0);
                prog.Set("heightmap", 1);
                prog.Set("World", World);

                vert.Dispose();
                frag.Dispose();
                tctrl.Dispose();
                teval.Dispose();

                //eObj = FullScreenQuadFactory.Create();
                eObj = CubeFactory.Create();
                eObj.SetTexture(0, t2);
                eObj.SetTexture(1, t3);

                b3.Dispose();
            };
            bool eyePosStill = false;

            GraphicsDevice.Update += (e) =>
            {
                // add game logic, input handling
                if (GraphicsDevice.Keyboard[Key.Escape])
                {
                    GraphicsDevice.Exit();
                }

                if (GraphicsDevice.Keyboard[Key.Z])
                {
                    GraphicsDevice.Wireframe = !GraphicsDevice.Wireframe;
                    //GraphicsDevice.CullEnabled = !GraphicsDevice.Wireframe;
                }

                if (GraphicsDevice.Keyboard[Key.F])
                {
                    eyePosStill = !eyePosStill;
                    Console.WriteLine("EyePosStill = " + eyePosStill);
                }

                context.Update(e);
                //context.Projection = Matrix4.Identity;
                //context.View = Matrix4.Identity;

                prog.Set("View", context.View);
                prog.Set("Proj", context.Projection);
                if (!eyePosStill)
                {
                    prog.Set("eyePos", context.Camera.Position);
                }

                prog.Set("Fcoef", (float)(2.0f / Math.Log(1000001) / Math.Log(2)));

                //timer += 0.001f;
                //World = Matrix4.RotateY(timer);
                World = Matrix4.CreateScale(10);
                prog.Set("World", World);

                prog.Set("timer", timer);
                terrProg.Set("timer", timer);
            };

            bool te1 = false;

            GraphicsDevice.Render += (e) =>
            {
                GraphicsDevice.SetFramebuffer(fbuf);
                GraphicsDevice.Clear();

                fsq.Bind();
                GraphicsDevice.SetShaderProgram(terrProg);
                GraphicsDevice.SetViewport(0, 0, 256, 256);
                GraphicsDevice.Draw(PrimitiveType.Triangles, 0, fsq.IndexCount);

                eObj.Bind();
                GraphicsDevice.SetShaderProgram(prog);
                GraphicsDevice.SetViewport(0, 0, GraphicsDevice.WindowSize.Width, GraphicsDevice.WindowSize.Height);
                GraphicsDevice.PatchCount = 3;
                GraphicsDevice.Draw(PrimitiveType.Patches, 0, eObj.IndexCount);

                GraphicsDevice.SwapBuffers();
                if (!te1)
                {
                    te1 = true;
                    GraphicsDevice.SaveTexture(fbufTex, "test1.png");
                }
            };

            GraphicsDevice.Name = "The Julis Faction";
            // Run the game at 60 updates per second
            GraphicsDevice.Run(60.0, 60.0);
            if (GraphicsDevice.Cleanup != null)
            {
                GraphicsDevice.Cleanup();
            }
        }
Example #15
0
 protected LightShaderGroupAndDataPool(ShaderSource mixin, string compositionName, ILightShadowMapShaderGroupData shadowGroupData)
     : base(mixin, compositionName, shadowGroupData)
 {
     dataPool = new PoolListStruct <T>(4, CreateData);
 }
Example #16
0
        public void LoadGLEntryPoints()
        {
            /* Basic entry points. If you don't have these, you're screwed. */
            try
            {
                INTERNAL_glGetString = (GetString) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetString"),
                    typeof(GetString)
                );
                glGetIntegerv = (GetIntegerv) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetIntegerv"),
                    typeof(GetIntegerv)
                );
                glEnable = (Enable) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glEnable"),
                    typeof(Enable)
                );
                glDisable = (Disable) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDisable"),
                    typeof(Disable)
                );
                glViewport = (G_Viewport) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glViewport"),
                    typeof(G_Viewport)
                );
                glDepthRange = (DepthRange) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDepthRange"),
                    typeof(DepthRange)
                );
                glScissor = (Scissor) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glScissor"),
                    typeof(Scissor)
                );
                glBlendColor = (BlendColor) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBlendColor"),
                    typeof(BlendColor)
                );
                glBlendFuncSeparate = (BlendFuncSeparate) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBlendFuncSeparate"),
                    typeof(BlendFuncSeparate)
                );
                glBlendEquationSeparate = (BlendEquationSeparate) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBlendEquationSeparate"),
                    typeof(BlendEquationSeparate)
                );
                glColorMask = (ColorMask) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glColorMask"),
                    typeof(ColorMask)
                );
                glDepthMask = (DepthMask) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDepthMask"),
                    typeof(DepthMask)
                );
                glDepthFunc = (DepthFunc) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDepthFunc"),
                    typeof(DepthFunc)
                );
                glStencilMask = (StencilMask) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glStencilMask"),
                    typeof(StencilMask)
                );
                glStencilFuncSeparate = (StencilFuncSeparate) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glStencilFuncSeparate"),
                    typeof(StencilFuncSeparate)
                );
                glStencilOpSeparate = (StencilOpSeparate) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glStencilOpSeparate"),
                    typeof(StencilOpSeparate)
                );
                glStencilFunc = (StencilFunc) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glStencilFunc"),
                    typeof(StencilFunc)
                );
                glStencilOp = (StencilOp) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glStencilOp"),
                    typeof(StencilOp)
                );
                glCullFace = (CullFace) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glCullFace"),
                    typeof(CullFace)
                );
                glFrontFace = (FrontFace) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glFrontFace"),
                    typeof(FrontFace)
                );
                glPolygonMode = (PolygonMode) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glPolygonMode"),
                    typeof(PolygonMode)
                );
                glPolygonOffset = (PolygonOffset) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glPolygonOffset"),
                    typeof(PolygonOffset)
                );
                glGenTextures = (GenTextures) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGenTextures"),
                    typeof(GenTextures)
                );
                glDeleteTextures = (DeleteTextures) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDeleteTextures"),
                    typeof(DeleteTextures)
                );
                glBindTexture = (G_BindTexture) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBindTexture"),
                    typeof(G_BindTexture)
                );
                glTexImage2D = (TexImage2D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexImage2D"),
                    typeof(TexImage2D)
                );
                glTexSubImage2D = (TexSubImage2D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexSubImage2D"),
                    typeof(TexSubImage2D)
                );
                glCompressedTexImage2D = (CompressedTexImage2D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glCompressedTexImage2D"),
                    typeof(CompressedTexImage2D)
                );
                glCompressedTexSubImage2D = (CompressedTexSubImage2D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glCompressedTexSubImage2D"),
                    typeof(CompressedTexSubImage2D)
                );
                glTexImage3D = (TexImage3D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexImage3D"),
                    typeof(TexImage3D)
                );
                glTexSubImage3D = (TexSubImage3D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexSubImage3D"),
                    typeof(TexSubImage3D)
                );
                glGetTexImage = (GetTexImage) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetTexImage"),
                    typeof(GetTexImage)
                );
                glTexParameteri = (TexParameteri) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexParameteri"),
                    typeof(TexParameteri)
                );
                glTexParameterf = (TexParameterf) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexParameterf"),
                    typeof(TexParameterf)
                );
                glActiveTexture = (ActiveTexture) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glActiveTexture"),
                    typeof(ActiveTexture)
                );
                glGetTexLevelParameteriv = (GetTexLevelParameteriv) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetTexLevelParameteriv"),
                    typeof(GetTexLevelParameteriv)
                );
                glPixelStorei = (PixelStorei) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glPixelStorei"),
                    typeof(PixelStorei)
                );
                glGenBuffers = (GenBuffers) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGenBuffers"),
                    typeof(GenBuffers)
                );
                glDeleteBuffers = (DeleteBuffers) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDeleteBuffers"),
                    typeof(DeleteBuffers)
                );
                glBindBuffer = (BindBuffer) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBindBuffer"),
                    typeof(BindBuffer)
                );
                glBufferData = (BufferData) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBufferData"),
                    typeof(BufferData)
                );
                glBufferSubData = (BufferSubData) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBufferSubData"),
                    typeof(BufferSubData)
                );
                glMapBuffer = (MapBuffer) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glMapBuffer"),
                    typeof(MapBuffer)
                );
                glUnmapBuffer = (UnmapBuffer) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glUnmapBuffer"),
                    typeof(UnmapBuffer)
                );
                glEnableVertexAttribArray = (EnableVertexAttribArray) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glEnableVertexAttribArray"),
                    typeof(EnableVertexAttribArray)
                );
                glDisableVertexAttribArray = (DisableVertexAttribArray) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDisableVertexAttribArray"),
                    typeof(DisableVertexAttribArray)
                );
                glVertexAttribPointer = (G_VertexAttribPointer) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glVertexAttribPointer"),
                    typeof(G_VertexAttribPointer)
                );
                glClearColor = (ClearColor) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glClearColor"),
                    typeof(ClearColor)
                );
                glClearDepth = (ClearDepth) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glClearDepth"),
                    typeof(ClearDepth)
                );
                glClearStencil = (ClearStencil) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glClearStencil"),
                    typeof(ClearStencil)
                );
                glClear = (G_Clear) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glClear"),
                    typeof(G_Clear)
                );
                glDrawBuffers = (DrawBuffers) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDrawBuffers"),
                    typeof(DrawBuffers)
                );
                glReadPixels = (ReadPixels) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glReadPixels"),
                    typeof(ReadPixels)
                );
                glDrawRangeElements = (DrawRangeElements) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDrawRangeElements"),
                    typeof(DrawRangeElements)
                );
                glDrawArrays = (DrawArrays) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDrawArrays"),
                    typeof(DrawArrays)
                );
                glGenQueries = (GenQueries) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGenQueries"),
                    typeof(GenQueries)
                );
                glDeleteQueries = (DeleteQueries) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDeleteQueries"),
                    typeof(DeleteQueries)
                );
                glBeginQuery = (BeginQuery) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBeginQuery"),
                    typeof(BeginQuery)
                );
                glEndQuery = (EndQuery) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glEndQuery"),
                    typeof(EndQuery)
                );
                glGetQueryObjectiv = (GetQueryObjectiv) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetQueryObjectiv"),
                    typeof(GetQueryObjectiv)
                );
                glCreateShader = (CreateShader) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glCreateShader"),
                    typeof(CreateShader)
                );
                glDeleteShader = (DeleteShader) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDeleteShader"),
                    typeof(DeleteShader)
                );
                glShaderSource = (ShaderSource) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glShaderSource"),
                    typeof(ShaderSource)
                );
                glCompileShader = (CompileShader) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glCompileShader"),
                    typeof(CompileShader)
                );
                glCreateProgram = (CreateProgram) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glCreateProgram"),
                    typeof(CreateProgram)
                );
                glDeleteProgram = (DeleteProgram) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDeleteProgram"),
                    typeof(DeleteProgram)
                );
                glAttachShader = (AttachShader) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glAttachShader"),
                    typeof(AttachShader)
                );
                glDetachShader = (DetachShader) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDetachShader"),
                    typeof(DetachShader)
                );
                glLinkProgram = (LinkProgram) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glLinkProgram"),
                    typeof(LinkProgram)
                );
                glUseProgram = (UseProgram) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glUseProgram"),
                    typeof(UseProgram)
                );
                glUniform1i = (Uniform1i) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glUniform1i"),
                    typeof(Uniform1i)
                );
                glUniform4fv = (Uniform4fv) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glUniform4fv"),
                    typeof(Uniform4fv)
                );
                glGetShaderiv = (GetShaderiv) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetShaderiv"),
                    typeof(GetShaderiv)
                );
                glGetProgramiv = (GetProgramiv) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetProgramiv"),
                    typeof(GetProgramiv)
                );
                glGetUniformLocation = (GetUniformLocation) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetUniformLocation"),
                    typeof(GetUniformLocation)
                );
                glGetAttribLocation = (GetAttribLocation) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetAttribLocation"),
                    typeof(GetAttribLocation)
                );
                glBindAttribLocation = (BindAttribLocation) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBindAttribLocation"),
                    typeof(BindAttribLocation)
                );
                glIsShader = (IsShader) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glIsShader"),
                    typeof(IsShader)
                );
                glIsProgram = (IsProgram) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glIsProgram"),
                    typeof(IsProgram)
                );
                glGetShaderInfoLog = (GetShaderInfoLog) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetShaderInfoLog"),
                    typeof(GetShaderInfoLog)
                );
                glGetProgramInfoLog = (GetProgramInfoLog) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetProgramInfoLog"),
                    typeof(GetProgramInfoLog)
                );
                glFlush = (Flush) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glFlush"),
                    typeof(Flush)
                );
            }
            catch
            {
                throw new NoSuitableGraphicsDeviceException("OpenGL 2.1 support is required!");
            }

            /* ARB_framebuffer_object. We're flexible, but not _that_ flexible. */
            try
            {
                glGenFramebuffers = (GenFramebuffers) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glGenFramebuffers"),
                    typeof(GenFramebuffers)
                );
                glDeleteFramebuffers = (DeleteFramebuffers) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glDeleteFramebuffers"),
                    typeof(DeleteFramebuffers)
                );
                glBindFramebuffer = (G_BindFramebuffer) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glBindFramebuffer"),
                    typeof(G_BindFramebuffer)
                );
                glFramebufferTexture2D = (FramebufferTexture2D) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glFramebufferTexture2D"),
                    typeof(FramebufferTexture2D)
                );
                glFramebufferRenderbuffer = (FramebufferRenderbuffer) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glFramebufferRenderbuffer"),
                    typeof(FramebufferRenderbuffer)
                );
            #if !DISABLE_FAUXBACKBUFFER
                glBlitFramebuffer = (BlitFramebuffer) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glBlitFramebuffer"),
                    typeof(BlitFramebuffer)
                );
            #endif
                glGenRenderbuffers = (GenRenderbuffers) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glGenRenderbuffers"),
                    typeof(GenRenderbuffers)
                );
                glDeleteRenderbuffers = (DeleteRenderbuffers) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glDeleteRenderbuffers"),
                    typeof(DeleteRenderbuffers)
                );
                glBindRenderbuffer = (BindRenderbuffer) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glBindRenderbuffer"),
                    typeof(BindRenderbuffer)
                );
                glRenderbufferStorage = (RenderbufferStorage) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glRenderbufferStorage"),
                    typeof(RenderbufferStorage)
                );
            }
            catch
            {
                throw new NoSuitableGraphicsDeviceException("OpenGL framebuffer support is required!");
            }

            /* ARB_instanced_arrays/ARB_draw_instanced are almost optional. */
            SupportsHardwareInstancing = true;
            try
            {
                glVertexAttribDivisor = (VertexAttribDivisor) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glVertexAttribDivisor"),
                    typeof(VertexAttribDivisor)
                );
                glDrawElementsInstanced = (DrawElementsInstanced) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDrawElementsInstanced"),
                    typeof(DrawElementsInstanced)
                );
            }
            catch
            {
                SupportsHardwareInstancing = false;
            }

            #if DEBUG
            /* ARB_debug_output, for debug contexts */
            IntPtr messageCallback = SDL.SDL_GL_GetProcAddress("glDebugMessageCallbackARB");
            IntPtr messageControl = SDL.SDL_GL_GetProcAddress("glDebugMessageControlARB");
            if (messageCallback == IntPtr.Zero || messageControl == IntPtr.Zero)
            {
                System.Console.WriteLine("ARB_debug_output not supported!");
            }
            else
            {
                glDebugMessageCallbackARB = (DebugMessageCallback) Marshal.GetDelegateForFunctionPointer(
                    messageCallback,
                    typeof(DebugMessageCallback)
                );
                glDebugMessageControlARB = (DebugMessageControl) Marshal.GetDelegateForFunctionPointer(
                    messageControl,
                    typeof(DebugMessageControl)
                );
                glDebugMessageCallbackARB(DebugCall, IntPtr.Zero);
                glDebugMessageControlARB(
                    GLenum.GL_DONT_CARE,
                    GLenum.GL_DONT_CARE,
                    GLenum.GL_DONT_CARE,
                    0,
                    IntPtr.Zero,
                    true
                );
                glDebugMessageControlARB(
                    GLenum.GL_DONT_CARE,
                    GLenum.GL_DEBUG_TYPE_OTHER_ARB,
                    GLenum.GL_DEBUG_SEVERITY_LOW_ARB,
                    0,
                    IntPtr.Zero,
                    false
                );
            }

            /* GREMEDY_string_marker, for apitrace */
            IntPtr stringMarkerCallback = SDL.SDL_GL_GetProcAddress("glStringMarkerGREMEDY");
            if (stringMarkerCallback == IntPtr.Zero)
            {
                System.Console.WriteLine("GREMEDY_string_marker not supported!");
            }
            else
            {
                glStringMarkerGREMEDY = (StringMarkerGREMEDY) Marshal.GetDelegateForFunctionPointer(
                    stringMarkerCallback,
                    typeof(StringMarkerGREMEDY)
                );
            }
            #endif
        }
Example #17
0
        public CompilerResults Compile(ShaderSource shaderSource, CompilerParameters compilerParameters, HashSet <string> modifiedShaders, HashSet <string> recentlyModifiedShaders)
        {
            ShaderMixinSourceTree mixinTree;
            var shaderMixinGeneratorSource = shaderSource as ShaderMixinGeneratorSource;
            var mainUsedParameters         = new ShaderMixinParameters();
            var usedParameters             = new List <ShaderMixinParameters>();

            string effectName = null;

            if (shaderMixinGeneratorSource != null)
            {
                effectName = shaderMixinGeneratorSource.Name;

                // getting the effect from the used parameters only makes sense when the source files are the same
                // TODO: improve this by updating earlyCompilerCache - cache can still be relevant
                if (modifiedShaders == null || modifiedShaders.Count == 0)
                {
                    // perform an early test only based on the parameters
                    var foundCompilerResults = GetShaderFromParameters(effectName, compilerParameters);
                    if (foundCompilerResults != null)
                    {
                        var earlyCompilerResults = new CompilerResults();
                        earlyCompilerResults.Module             = string.Format("EffectCompile [{0}]", effectName);
                        earlyCompilerResults.MainBytecode       = foundCompilerResults.MainBytecode;
                        earlyCompilerResults.MainUsedParameters = foundCompilerResults.MainUsedParameters;
                        foreach (var foundBytecode in foundCompilerResults.Bytecodes)
                        {
                            earlyCompilerResults.Bytecodes.Add(foundBytecode.Key, foundBytecode.Value);
                        }

                        foreach (var foundUsedParameters in foundCompilerResults.UsedParameters)
                        {
                            earlyCompilerResults.UsedParameters.Add(foundUsedParameters.Key, foundUsedParameters.Value);
                        }
                        return(earlyCompilerResults);
                    }
                }
                mixinTree = ShaderMixinManager.Generate(effectName, compilerParameters, out mainUsedParameters, out usedParameters);
            }
            else
            {
                effectName = "Effect";

                var shaderMixinSource = shaderSource as ShaderMixinSource;
                var shaderClassSource = shaderSource as ShaderClassSource;

                if (shaderClassSource != null)
                {
                    shaderMixinSource = new ShaderMixinSource();
                    shaderMixinSource.Mixins.Add(shaderClassSource);
                }

                if (shaderMixinSource != null)
                {
                    mixinTree = new ShaderMixinSourceTree()
                    {
                        Mixin = shaderMixinSource
                    };
                }
                else
                {
                    throw new ArgumentException("Unsupported ShaderSource type [{0}]. Supporting only ShaderMixinSource/pdxfx, ShaderClassSource", "shaderSource");
                }
            }

            // Copy global parameters to used Parameters by default, as it is used by the compiler
            mainUsedParameters.Set(CompilerParameters.GraphicsPlatformKey, compilerParameters.Platform);
            mainUsedParameters.Set(CompilerParameters.GraphicsProfileKey, compilerParameters.Profile);
            mainUsedParameters.Set(CompilerParameters.DebugKey, compilerParameters.Debug);

            foreach (var parameters in usedParameters)
            {
                parameters.Set(CompilerParameters.GraphicsPlatformKey, compilerParameters.Platform);
                parameters.Set(CompilerParameters.GraphicsProfileKey, compilerParameters.Profile);
                parameters.Set(CompilerParameters.DebugKey, compilerParameters.Debug);
            }

            // Compile the whole mixin tree
            var compilerResults = new CompilerResults();

            compilerResults.Module = string.Format("EffectCompile [{0}]", effectName);
            var wasCompiled = Compile(string.Empty, effectName, mixinTree, mainUsedParameters, usedParameters, modifiedShaders, recentlyModifiedShaders, compilerResults);

            if (wasCompiled && shaderMixinGeneratorSource != null)
            {
                lock (earlyCompilerCache)
                {
                    List <CompilerResults> effectCompilerResults;
                    if (!earlyCompilerCache.TryGetValue(effectName, out effectCompilerResults))
                    {
                        effectCompilerResults = new List <CompilerResults>();
                        earlyCompilerCache.Add(effectName, effectCompilerResults);
                    }

                    // Register bytecode used parameters so that they are checked when another effect is instanced
                    effectCompilerResults.Add(compilerResults);
                }
            }

            return(compilerResults);
        }
Example #18
0
        static void Main(string[] args)
        {
            GraphicsDevice.AppName          = "Vulkan Test";
            GraphicsDevice.EnableValidation = true;
            GraphicsDevice.RebuildShaders   = true;
            GraphicsDevice.Init();

            graph = new FrameGraph(0);

            var vertS = new SpecializedShader()
            {
                Name               = "FST_Vert",
                Shader             = ShaderSource.Load(ShaderType.VertexShader, "FullScreenTriangle/vertex.glsl"),
                SpecializationData = null
            };

            var fragS = new SpecializedShader()
            {
                Name               = "UVR_Frag",
                Shader             = ShaderSource.Load(ShaderType.FragmentShader, "UVRenderer/fragment.glsl"),
                SpecializationData = null,
            };

            graph.RegisterShader(vertS);
            graph.RegisterShader(fragS);

            for (int i = 0; i < GraphicsDevice.MaxFramesInFlight; i++)
            {
                var out_img = GraphicsDevice.DefaultFramebuffer[i].ColorAttachments[0];
                graph.RegisterResource(out_img);
            }

            var gpass = new GraphicsPass("main_pass")
            {
                Shaders          = new string[] { vertS.Name, fragS.Name },
                ViewportWidth    = GraphicsDevice.Width,
                ViewportHeight   = GraphicsDevice.Height,
                ViewportDynamic  = false,
                DepthWriteEnable = false,
                CullMode         = CullMode.None,
                RenderLayout     = new RenderLayout()
                {
                    Color = new RenderLayoutEntry[]
                    {
                        new RenderLayoutEntry()
                        {
                            DesiredLayout  = ImageLayout.ColorAttachmentOptimal,
                            FirstLoadStage = PipelineStage.ColorAttachOut,
                            Format         = GraphicsDevice.DefaultFramebuffer[GraphicsDevice.CurrentFrameID].ColorAttachments[0].Format,
                            LastStoreStage = PipelineStage.ColorAttachOut,
                            LoadOp         = AttachmentLoadOp.DontCare,
                            StoreOp        = AttachmentStoreOp.Store,
                        },
                    },
                    Depth = null,
                },
                DescriptorSetup = new DescriptorSetup()
                {
                    Descriptors   = null,
                    PushConstants = null,
                },
            };

            graph.RegisterGraphicsPass(gpass);
            graph.GatherDescriptors();

            GraphicsDevice.Window.Render += Window_Render;
            GraphicsDevice.Window.Run(60);

            /*
             * var fbuf = new Framegraph(0);
             * fbuf.RegisterAttachment(new AttachmentInfo()
             * {
             *  Name = "output",
             *  BaseSize = SizeClass.ScreenRelative,
             *  SizeX = 1,
             *  SizeY = 1,
             *  Format = ImageFormat.B8G8R8A8Unorm,
             *  Layers = 1,
             *  UseMipMaps = false,
             *  Usage = ImageUsage.ColorAttachment | ImageUsage.Sampled,
             * });
             * fbuf.RegisterAttachment(new AttachmentInfo()
             * {
             *  Name = "output_dpth",
             *  BaseSize = SizeClass.ScreenRelative,
             *  SizeX = 1,
             *  SizeY = 1,
             *  Format = ImageFormat.Depth32f,
             *  Layers = 1,
             *  UseMipMaps = false,
             *  Usage = ImageUsage.DepthAttachment | ImageUsage.TransferSrc,
             * });
             * fbuf.RegisterShaderParams(new ShaderParameterSet()
             * {
             *  Name = "output_shader_params",
             *  Buffers = null,
             *  SampledAttachments = null,
             *  Textures = null,
             * });
             * fbuf.RegisterPass(new GraphicsPass()
             * {
             *  Name = "main_pass",
             *  CullMode = CullMode.None,
             *  DepthAttachment = new AttachmentUsageInfo()
             *  {
             *      Name = "output_dpth",
             *      Usage = AttachmentUsage.WriteOnly
             *  },
             *  AttachmentUsage = new AttachmentUsageInfo[]{
             *      new AttachmentUsageInfo(){
             *          Name = "output",
             *          Usage = AttachmentUsage.WriteOnly
             *      }
             *  },
             *  DepthClamp = false,
             *  DepthTest = DepthTest.Always,
             *  EnableBlending = false,
             *  LineWidth = 1,
             *  PassDependencies = null,
             *  RasterizerDiscard = false,
             *  Shaders = new ShaderSource[] { vert, frag },
             *  Topology = PrimitiveType.Triangle,
             *  DrawCmd = new PlainDrawCmd()
             *  {
             *      BaseInstance = 0,
             *      BaseVertex = 0,
             *      InstanceCount = 1,
             *      VertexCount = 3
             *  }
             * });
             * fbuf.SetOutputPass("output");
             * fbuf.Compile();
             * while (!GraphicsDevice.Window.IsExiting)
             * {
             *  fbuf.Execute(true);
             *  GraphicsDevice.Window.PollEvents();
             * }*/
        }
Example #19
0
        /// <summary>
        /// create the context for each composition by cloning their dependencies
        /// </summary>
        /// <param name="shaderSource">the entry ShaderSource (root)</param>
        /// <param name="dictionary">the ouputed compositions</param>
        /// <param name="compilationContext">the compilation context</param>
        /// <param name="cloneContext">The clone context.</param>
        /// <returns>a list of all the needed mixins</returns>
        private static List<ModuleMixin> BuildCompositionsDictionary(ShaderSource shaderSource, CompositionDictionary dictionary, ShaderCompilationContext compilationContext, CloneContext cloneContext, LoggerResult log)
        {
            if (shaderSource is ShaderMixinSource)
            {
                var shaderMixinSource = shaderSource as ShaderMixinSource;

                var finalModule = compilationContext.GetModuleMixinFromShaderSource(shaderSource);

                //PerformanceLogger.Start(PerformanceStage.DeepClone);
                finalModule = finalModule.DeepClone(new CloneContext(cloneContext));
                //PerformanceLogger.Pause(PerformanceStage.DeepClone);

                foreach (var composition in shaderMixinSource.Compositions)
                {
                    //look for the key
                    var foundVars = finalModule.FindAllVariablesByName(composition.Key).Where(value => value.Variable.Qualifiers.Contains(ParadoxStorageQualifier.Compose)).ToList();

                    if (foundVars.Count > 1)
                    {
                        log.Error(ParadoxMessageCode.ErrorAmbiguousComposition, new SourceSpan(), composition.Key);
                    }
                    else if (foundVars.Count > 0)
                    {
                        Variable foundVar = foundVars[0].Variable;
                        var moduleMixins = BuildCompositionsDictionary(composition.Value, dictionary, compilationContext, cloneContext, log);
                        if (moduleMixins == null)
                            return null;

                        dictionary.Add(foundVar, moduleMixins);
                    }
                    else
                    {
                        // No matching variable was found
                        // TODO: log a message?
                    }
                }
                return new List<ModuleMixin> { finalModule };
            }


            if (shaderSource is ShaderClassSource)
            {
                var finalModule = compilationContext.GetModuleMixinFromShaderSource(shaderSource);

                //PerformanceLogger.Start(PerformanceStage.DeepClone);
                finalModule = finalModule.DeepClone(new CloneContext(cloneContext));
                //PerformanceLogger.Pause(PerformanceStage.DeepClone);

                return new List<ModuleMixin> { finalModule };
            }

            if (shaderSource is ShaderArraySource)
            {
                var shaderArraySource = shaderSource as ShaderArraySource;
                var compositionArray = new List<ModuleMixin>();
                foreach (var shader in shaderArraySource.Values)
                {
                    var mixin = BuildCompositionsDictionary(shader, dictionary, compilationContext, cloneContext, log);
                    if (mixin == null)
                        return null;
                    compositionArray.AddRange(mixin);
                }
                return compositionArray;
            }

            return null;
        }
Example #20
0
 public SkyBoxPlugin(string name, ShaderSource skyBoxComposition)
     : base(name)
 {
     Texture     = null;
     SkyBoxColor = skyBoxComposition;
 }
Example #21
0
 public void AddShading <T>(T shadingModel, ShaderSource shaderSource) where T : class, IMaterialShadingModelFeature
 {
     currentLayerContext.ShadingModels.Add(shadingModel, shaderSource);
 }
Example #22
0
        /// <summary>
        /// Get the module mixin based on the ShaderSource
        /// </summary>
        /// <param name="shaderSource">the ShaderSource</param>
        /// <returns>the ModuleMixin</returns>
        public ModuleMixin GetModuleMixinFromShaderSource(ShaderSource shaderSource)
        {
            var found = MixinInfos.FirstOrDefault(x => x.ShaderSource.Equals(shaderSource));

            return(found == null ? null : found.Mixin);
        }
Example #23
0
 protected override Shader.Platform CreateShader(ShaderSource source)
 {
     return(new GL_Shader(this, source));
 }
        /// <summary>
        /// Build the ModuleMixinInfo class
        /// </summary>
        /// <param name="shaderSource">the ShaderSource to load</param>
        /// <param name="macros">the macros applied on the source</param>
        /// <returns>the ModuleMixinInfo</returns>
        private ModuleMixinInfo BuildMixinInfo(ShaderSource shaderSource, SiliconStudio.Shaders.Parser.ShaderMacro[] macros)
        {
            ModuleMixinInfo mixinInfo = null;
            
            if (shaderSource is ShaderClassSource)
            {
                var shaderClassSource = shaderSource as ShaderClassSource;
                mixinInfo = new ModuleMixinInfo { ShaderSource = shaderClassSource, Macros = macros };
                LoadMixinFromClassSource(mixinInfo);
            }
            else if (shaderSource is ShaderMixinSource)
            {
                var shaderMixinSource = shaderSource as ShaderMixinSource;

                var shaderName = "Mix" + lastMixIndex;
                ++lastMixIndex;
                var fakeAst = new ShaderClassType(shaderName);
                foreach (var classSource in shaderMixinSource.Mixins)
                {
                    Identifier name;
                    if (classSource.GenericArguments != null && classSource.GenericArguments.Length > 0)
                        name = new IdentifierGeneric(classSource.ClassName, classSource.GenericArguments.Select(x => new Identifier(x.ToString())).ToArray());
                    else
                        name = new Identifier(classSource.ClassName);

                    fakeAst.BaseClasses.Add(new TypeName(name));
                }

                mixinInfo = new ModuleMixinInfo
                    {
                        MixinGenericName = shaderName,
                        Macros = macros, 
                        MixinAst = fakeAst, 
                        ShaderSource =  shaderSource,
                        SourceHash = ObjectId.FromBytes(Encoding.UTF8.GetBytes(shaderName)), 
                        Instanciated = true
                    };
            }

            return mixinInfo;
        }
Example #25
0
 protected LightShaderGroup(ShaderSource mixin)
 {
     ShaderSource = mixin;
 }
Example #26
0
 public DefaultEffectMixinProvider(string name)
 {
     shaderSource = new ShaderClassSource(name);
 }
        /// <summary>
        /// Get the ModuleMixinInfo based on the ShaderSource and the macros. Creates the needed shader if necessary
        /// </summary>
        /// <param name="shaderSource">the ShaderSource</param>
        /// <param name="macros">the macros</param>
        /// <param name="macrosString">the name of the macros</param>
        /// <returns>ModuleMixinInfo.</returns>
        private ModuleMixinInfo GetModuleMixinInfo(ShaderSource shaderSource, SiliconStudio.Shaders.Parser.ShaderMacro[] macros, string macrosString = null)
        {
            if (macros == null)
                macros = new SiliconStudio.Shaders.Parser.ShaderMacro[0];

            if (macrosString == null)
            {
                macrosString =  string.Join(",", macros.OrderBy(x => x.Name));
            }

            List<ModuleMixinInfo> context;
            if (!mapMacrosToMixins.TryGetValue(macrosString, out context))
            {
                context = new List<ModuleMixinInfo>();
                mapMacrosToMixins.Add(macrosString, context);
            }

            var mixinInfo = context.FirstOrDefault(x => x.AreEqual(shaderSource, macros));
            if (mixinInfo == null)
            {
                mixinInfo = BuildMixinInfo(shaderSource, macros);

                if (mixinInfo.Instanciated)
                {
                    MixinInfos.Add(mixinInfo);
                    mapMacrosToMixins[macrosString].Add(mixinInfo);

                    mixinInfo.MinimalContext.Add(mixinInfo);

                    if (!mixinInfo.Log.HasErrors)
                    {
                        LoadNecessaryShaders(mixinInfo, macros, macrosString);
                    }
                    mixinInfo.MinimalContext = new HashSet<ModuleMixinInfo>(mixinInfo.MinimalContext.Distinct());
                }
            }

            return mixinInfo;
        }
Example #28
0
 public static void InitGL_2_0(OpenGLContext ctx)
 {
     glBlendEquationSeparate = ctx.GetProc<BlendEquationSeparate>("glBlendEquationSeparate");
     glDrawBuffers = ctx.GetProc<DrawBuffers>("glDrawBuffers");
     glStencilOpSeparate = ctx.GetProc<StencilOpSeparate>("glStencilOpSeparate");
     glStencilFuncSeparate = ctx.GetProc<StencilFuncSeparate>("glStencilFuncSeparate");
     glStencilMaskSeparate = ctx.GetProc<StencilMaskSeparate>("glStencilMaskSeparate");
     glAttachShader = ctx.GetProc<AttachShader>("glAttachShader");
     glBindAttribLocation = ctx.GetProc<BindAttribLocation>("glBindAttribLocation");
     glCompileShader = ctx.GetProc<CompileShader>("glCompileShader");
     glCreateProgram = ctx.GetProc<CreateProgram>("glCreateProgram");
     glCreateShader = ctx.GetProc<CreateShader>("glCreateShader");
     glDeleteProgram = ctx.GetProc<DeleteProgram>("glDeleteProgram");
     glDeleteShader = ctx.GetProc<DeleteShader>("glDeleteShader");
     glDetachShader = ctx.GetProc<DetachShader>("glDetachShader");
     glDisableVertexAttribArray = ctx.GetProc<DisableVertexAttribArray>("glDisableVertexAttribArray");
     glEnableVertexAttribArray = ctx.GetProc<EnableVertexAttribArray>("glEnableVertexAttribArray");
     glGetActiveAttrib = ctx.GetProc<GetActiveAttrib>("glGetActiveAttrib");
     glGetActiveUniform = ctx.GetProc<GetActiveUniform>("glGetActiveUniform");
     glGetAttachedShaders = ctx.GetProc<GetAttachedShaders>("glGetAttachedShaders");
     glGetAttribLocation = ctx.GetProc<GetAttribLocation>("glGetAttribLocation");
     glGetProgramiv = ctx.GetProc<GetProgramiv>("glGetProgramiv");
     glGetProgramInfoLog = ctx.GetProc<GetProgramInfoLog>("glGetProgramInfoLog");
     glGetShaderiv = ctx.GetProc<GetShaderiv>("glGetShaderiv");
     glGetShaderInfoLog = ctx.GetProc<GetShaderInfoLog>("glGetShaderInfoLog");
     glGetShaderSource = ctx.GetProc<GetShaderSource>("glGetShaderSource");
     glGetUniformLocation = ctx.GetProc<GetUniformLocation>("glGetUniformLocation");
     glGetUniformfv = ctx.GetProc<GetUniformfv>("glGetUniformfv");
     glGetUniformiv = ctx.GetProc<GetUniformiv>("glGetUniformiv");
     glGetVertexAttribdv = ctx.GetProc<GetVertexAttribdv>("glGetVertexAttribdv");
     glGetVertexAttribfv = ctx.GetProc<GetVertexAttribfv>("glGetVertexAttribfv");
     glGetVertexAttribiv = ctx.GetProc<GetVertexAttribiv>("glGetVertexAttribiv");
     glGetVertexAttribPointerv = ctx.GetProc<GetVertexAttribPointerv>("glGetVertexAttribPointerv");
     glIsProgram = ctx.GetProc<IsProgram>("glIsProgram");
     glIsShader = ctx.GetProc<IsShader>("glIsShader");
     glLinkProgram = ctx.GetProc<LinkProgram>("glLinkProgram");
     glShaderSource = ctx.GetProc<ShaderSource>("glShaderSource");
     glUseProgram = ctx.GetProc<UseProgram>("glUseProgram");
     glUniform1f = ctx.GetProc<Uniform1f>("glUniform1f");
     glUniform2f = ctx.GetProc<Uniform2f>("glUniform2f");
     glUniform3f = ctx.GetProc<Uniform3f>("glUniform3f");
     glUniform4f = ctx.GetProc<Uniform4f>("glUniform4f");
     glUniform1i = ctx.GetProc<Uniform1i>("glUniform1i");
     glUniform2i = ctx.GetProc<Uniform2i>("glUniform2i");
     glUniform3i = ctx.GetProc<Uniform3i>("glUniform3i");
     glUniform4i = ctx.GetProc<Uniform4i>("glUniform4i");
     glUniform1fv = ctx.GetProc<Uniform1fv>("glUniform1fv");
     glUniform2fv = ctx.GetProc<Uniform2fv>("glUniform2fv");
     glUniform3fv = ctx.GetProc<Uniform3fv>("glUniform3fv");
     glUniform4fv = ctx.GetProc<Uniform4fv>("glUniform4fv");
     glUniform1iv = ctx.GetProc<Uniform1iv>("glUniform1iv");
     glUniform2iv = ctx.GetProc<Uniform2iv>("glUniform2iv");
     glUniform3iv = ctx.GetProc<Uniform3iv>("glUniform3iv");
     glUniform4iv = ctx.GetProc<Uniform4iv>("glUniform4iv");
     glUniformMatrix2fv = ctx.GetProc<UniformMatrix2fv>("glUniformMatrix2fv");
     glUniformMatrix3fv = ctx.GetProc<UniformMatrix3fv>("glUniformMatrix3fv");
     glUniformMatrix4fv = ctx.GetProc<UniformMatrix4fv>("glUniformMatrix4fv");
     glValidateProgram = ctx.GetProc<ValidateProgram>("glValidateProgram");
     glVertexAttrib1d = ctx.GetProc<VertexAttrib1d>("glVertexAttrib1d");
     glVertexAttrib1dv = ctx.GetProc<VertexAttrib1dv>("glVertexAttrib1dv");
     glVertexAttrib1f = ctx.GetProc<VertexAttrib1f>("glVertexAttrib1f");
     glVertexAttrib1fv = ctx.GetProc<VertexAttrib1fv>("glVertexAttrib1fv");
     glVertexAttrib1s = ctx.GetProc<VertexAttrib1s>("glVertexAttrib1s");
     glVertexAttrib1sv = ctx.GetProc<VertexAttrib1sv>("glVertexAttrib1sv");
     glVertexAttrib2d = ctx.GetProc<VertexAttrib2d>("glVertexAttrib2d");
     glVertexAttrib2dv = ctx.GetProc<VertexAttrib2dv>("glVertexAttrib2dv");
     glVertexAttrib2f = ctx.GetProc<VertexAttrib2f>("glVertexAttrib2f");
     glVertexAttrib2fv = ctx.GetProc<VertexAttrib2fv>("glVertexAttrib2fv");
     glVertexAttrib2s = ctx.GetProc<VertexAttrib2s>("glVertexAttrib2s");
     glVertexAttrib2sv = ctx.GetProc<VertexAttrib2sv>("glVertexAttrib2sv");
     glVertexAttrib3d = ctx.GetProc<VertexAttrib3d>("glVertexAttrib3d");
     glVertexAttrib3dv = ctx.GetProc<VertexAttrib3dv>("glVertexAttrib3dv");
     glVertexAttrib3f = ctx.GetProc<VertexAttrib3f>("glVertexAttrib3f");
     glVertexAttrib3fv = ctx.GetProc<VertexAttrib3fv>("glVertexAttrib3fv");
     glVertexAttrib3s = ctx.GetProc<VertexAttrib3s>("glVertexAttrib3s");
     glVertexAttrib3sv = ctx.GetProc<VertexAttrib3sv>("glVertexAttrib3sv");
     glVertexAttrib4Nbv = ctx.GetProc<VertexAttrib4Nbv>("glVertexAttrib4Nbv");
     glVertexAttrib4Niv = ctx.GetProc<VertexAttrib4Niv>("glVertexAttrib4Niv");
     glVertexAttrib4Nsv = ctx.GetProc<VertexAttrib4Nsv>("glVertexAttrib4Nsv");
     glVertexAttrib4Nub = ctx.GetProc<VertexAttrib4Nub>("glVertexAttrib4Nub");
     glVertexAttrib4Nubv = ctx.GetProc<VertexAttrib4Nubv>("glVertexAttrib4Nubv");
     glVertexAttrib4Nuiv = ctx.GetProc<VertexAttrib4Nuiv>("glVertexAttrib4Nuiv");
     glVertexAttrib4Nusv = ctx.GetProc<VertexAttrib4Nusv>("glVertexAttrib4Nusv");
     glVertexAttrib4bv = ctx.GetProc<VertexAttrib4bv>("glVertexAttrib4bv");
     glVertexAttrib4d = ctx.GetProc<VertexAttrib4d>("glVertexAttrib4d");
     glVertexAttrib4dv = ctx.GetProc<VertexAttrib4dv>("glVertexAttrib4dv");
     glVertexAttrib4f = ctx.GetProc<VertexAttrib4f>("glVertexAttrib4f");
     glVertexAttrib4fv = ctx.GetProc<VertexAttrib4fv>("glVertexAttrib4fv");
     glVertexAttrib4iv = ctx.GetProc<VertexAttrib4iv>("glVertexAttrib4iv");
     glVertexAttrib4s = ctx.GetProc<VertexAttrib4s>("glVertexAttrib4s");
     glVertexAttrib4sv = ctx.GetProc<VertexAttrib4sv>("glVertexAttrib4sv");
     glVertexAttrib4ubv = ctx.GetProc<VertexAttrib4ubv>("glVertexAttrib4ubv");
     glVertexAttrib4uiv = ctx.GetProc<VertexAttrib4uiv>("glVertexAttrib4uiv");
     glVertexAttrib4usv = ctx.GetProc<VertexAttrib4usv>("glVertexAttrib4usv");
     glVertexAttribPointer = ctx.GetProc<VertexAttribPointer>("glVertexAttribPointer");
 }
Example #29
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form();

            form.ClientSize = new Size(800, 600);

            using (var device = LightDevice.Create(form))
            {
                var target = new RenderTargetList(device.GetDefaultTarget());
                target.Apply();

                Pipeline pipeline = device.CompilePipeline(InputTopology.Triangle,
                                                           ShaderSource.FromResource("Shader.fx", ShaderType.Vertex | ShaderType.Pixel));
                pipeline.Apply();

                var inputGroup = pipeline.CreateVertexDataProcessors(new[] {
                    typeof(VertexP),
                    typeof(VertexC),
                });
                var input1 = inputGroup.GetVertexDataProcessor <VertexP>();
                var input2 = inputGroup.GetVertexDataProcessor <VertexC>();

                var buffer1       = input1.CreateDynamicBuffer(3);
                var vertexPosData = new[] {
                    new VertexP {
                        Position = new Vector4(0, 0, 0.5f, 1)
                    },
                    new VertexP {
                        Position = new Vector4(0, 0, 0.5f, 1)
                    },
                    new VertexP {
                        Position = new Vector4(0, 0, 0.5f, 1)
                    },
                };
                var buffer2 = input2.CreateImmutableBuffer(new[] {
                    new VertexC {
                        Color = Color.Green.WithAlpha(1)
                    },
                    new VertexC {
                        Color = Color.Red.WithAlpha(1)
                    },
                    new VertexC {
                        Color = Color.Blue.WithAlpha(1)
                    },
                });
                var bufferGroup = new[] { buffer1, buffer2 };

                var indexBuffer = pipeline.CreateImmutableIndexBuffer(new uint[] { 0, 1, 2 });

                var constantBuffer = pipeline.CreateConstantBuffer <ConstantBuffer>();
                pipeline.SetConstant(ShaderType.Vertex, 0, constantBuffer);
                pipeline.SetConstant(ShaderType.Pixel, 0, constantBuffer);

                constantBuffer.Value.GlobalAlpha = new Vector4(1, 1, 1, 1);

                form.Show();

                var i    = 0;
                var rand = new Random();

                var clock = Stopwatch.StartNew();
                device.RunMultithreadLoop(delegate()
                {
                    var angle    = -clock.Elapsed.TotalSeconds * Math.PI / 3;
                    var distance = Math.PI * 2 / 3;

                    SetCoordinate(device, ref vertexPosData[0].Position, angle);
                    SetCoordinate(device, ref vertexPosData[1].Position, angle - distance);
                    SetCoordinate(device, ref vertexPosData[2].Position, angle + distance);
                    buffer1.Update(vertexPosData);

                    constantBuffer.Value.Time = ((float)clock.Elapsed.TotalSeconds % 2) / 2;

                    if (++i == 60)
                    {
                        i = 0;
                        constantBuffer.Value.GlobalAlpha.X = (float)rand.NextDouble() * 0.5f + 0.5f;
                        constantBuffer.Value.GlobalAlpha.Y = (float)rand.NextDouble() * 0.5f + 0.5f;
                        constantBuffer.Value.GlobalAlpha.Z = (float)rand.NextDouble() * 0.5f + 0.5f;
                    }
                    constantBuffer.Update();

                    target.ClearAll();
                    indexBuffer.DrawAll(inputGroup, bufferGroup);

                    device.Present(true);
                });
            }
        }
Example #30
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form
            {
                ClientSize = new Size(800, 600),
                Text       = "Tutorial 4: Buffers, Shaders, and HLSL",
            };

            using (var device = LightDevice.Create(form))
            {
                //---------------------
                // Target & Pipeline
                //---------------------

                var target = new RenderTarget(device.GetDefaultTarget());
                target.Apply();

                Pipeline pipeline = device.CompilePipeline(InputTopology.Triangle,
                                                           ShaderSource.FromResource("Color_vs.fx", ShaderType.Vertex),
                                                           ShaderSource.FromResource("Color_ps.fx", ShaderType.Pixel));
                pipeline.Apply();

                //---------------------
                // Vertex buffer
                //---------------------

                var vertexDataProcessor = pipeline.CreateVertexDataProcessor <Vertex>();
                var vertexBuffer        = vertexDataProcessor.CreateImmutableBuffer(new[] {
                    new Vertex {
                        Position = new Vector4(-1, -1, 0, 1), Color = new Vector4(0, 1, 0, 1)
                    },
                    new Vertex {
                        Position = new Vector4(0, 1, 0, 1), Color = new Vector4(0, 1, 0, 1)
                    },
                    new Vertex {
                        Position = new Vector4(1, -1, 0, 1), Color = new Vector4(0, 1, 0, 1)
                    },
                });

                //---------------------
                // Index buffer
                //---------------------

                var indexBuffer = pipeline.CreateImmutableIndexBuffer(new uint[] { 0, 1, 2 });

                //---------------------
                // Constant buffer (VS)
                //---------------------

                var constantBuffer = pipeline.CreateConstantBuffer <Constants>();
                pipeline.SetConstant(ShaderType.Vertex, 0, constantBuffer);

                void SetupProjMatrix()
                {
                    constantBuffer.Value.Projection =
                        device.CreatePerspectiveFieldOfView((float)Math.PI / 4).Transpose();
                }

                device.ResolutionChanged += (sender, e) => SetupProjMatrix();

                constantBuffer.Value.World = Matrix4x4.Identity.Transpose();
                SetupProjMatrix();

                //---------------------
                // Camera
                //---------------------

                var camera = new Camera();

                //---------------------
                // Start main loop
                //---------------------

                form.Show();

                device.RunMultithreadLoop(delegate()
                {
                    // Update matrix

                    constantBuffer.Value.View = camera.GetViewMatrix().Transpose();
                    constantBuffer.Update();

                    // Clear and draw

                    target.ClearAll();
                    indexBuffer.DrawAll(vertexBuffer);

                    device.Present(true);
                });
            }
        }
 /// <inheritdoc/>
 public override String Process(ContentManager manager, IContentProcessorMetadata metadata, String input)
 {
     return(ShaderSource.ProcessRawSource(manager, metadata, input)?.Source ?? String.Empty);
 }
Example #32
0
        public void SetStream(MaterialShaderStage stage, string stream, MaterialStreamType streamType, ShaderSource classSource)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            // Blend stream is not part of the stream used
            if (stream != MaterialBlendLayer.BlendStream)
            {
                GetContextPerStage(stage).Streams.Add(stream);
            }

            string channel;

            switch (streamType)
            {
            case MaterialStreamType.Float:
                channel = "r";
                break;

            case MaterialStreamType.Float2:
                channel = "rg";
                break;

            case MaterialStreamType.Float3:
                channel = "rgb";
                break;

            case MaterialStreamType.Float4:
                channel = "rgba";
                break;

            default:
                throw new NotSupportedException("StreamType [{0}] is not supported".ToFormat(streamType));
            }

            var mixin = new ShaderMixinSource();

            mixin.Mixins.Add(new ShaderClassSource("MaterialSurfaceSetStreamFromComputeColor", stream, channel));
            mixin.AddComposition("computeColorSource", classSource);

            GetContextPerStage(stage).ShaderSources.Add(mixin);
        }
Example #33
0
        static void Main(string[] args)
        {
            Engine.AppName          = "Test";
            Engine.EnableValidation = true;
            Engine.RebuildShaders   = true;
            Engine.Initialize();

            var graph = new FrameGraph(0);

            Engine.RenderGraph = graph;

            int trace_side       = 1024;
            var objLoaderFactory = new ObjLoaderFactory();
            var objLoader        = objLoaderFactory.Create();

            using (var fs = File.OpenRead("sponza.obj"))
            {
                var obj_loaded = objLoader.Load(fs);

                ulong idxCount = 0;
                for (int i = 0; i < obj_loaded.Groups.Count; i++)
                {
                    idxCount += (ulong)obj_loaded.Groups[i].Faces.Count * 3;
                }

                vertexBuffer     = new StreamableBuffer("vbo", (ulong)obj_loaded.Vertices.Count * 3 * sizeof(float), BufferUsage.Storage);
                indexBuffer      = new StreamableBuffer("ibo", idxCount * sizeof(uint), BufferUsage.Index | BufferUsage.Storage);
                rayIntersections = new RayIntersections("rayInter", (uint)trace_side * (uint)trace_side, 0);
                geometry         = new RayGeometry("rayGeom", (uint)obj_loaded.Vertices.Count);
                unsafe
                {
                    float *fp = (float *)vertexBuffer.BeginBufferUpdate();
                    for (int i = 0; i < obj_loaded.Vertices.Count; i++)
                    {
                        fp[0] = obj_loaded.Vertices[i].X;
                        fp[1] = obj_loaded.Vertices[i].Y;
                        fp[2] = obj_loaded.Vertices[i].Z;

                        fp += 3;
                    }
                    vertexBuffer.EndBufferUpdate();

                    uint *ui = (uint *)indexBuffer.BeginBufferUpdate();
                    for (int i = 0; i < obj_loaded.Groups.Count; i++)
                    {
                        for (int j = 0; j < obj_loaded.Groups[i].Faces.Count; j++)
                        {
                            ui[0] = (uint)(obj_loaded.Groups[i].Faces[j][0].VertexIndex - 1);
                            ui[1] = (uint)(obj_loaded.Groups[i].Faces[j][1].VertexIndex - 1);
                            ui[2] = (uint)(obj_loaded.Groups[i].Faces[j][2].VertexIndex - 1);

                            ui += 3;
                        }
                    }
                    indexBuffer.EndBufferUpdate();

                    float *rp = (float *)rayIntersections.RayBuffer.BeginBufferUpdate();
                    for (uint x = 0; x < trace_side; x++)
                    {
                        for (uint y = 0; y < trace_side; y++)
                        {
                            //uint i = 0;
                            //for(int j = 0; j < 15; j++)
                            //{
                            //    i |= ((x & (1u << j)) << j) | ((y & (1u << j)) << (j + 1));
                            //}

                            //i *= 8;
                            uint i = ((uint)trace_side * y + x) * 8;
                            rp[i + 0] = 0.0f;
                            rp[i + 1] = 15.0f;
                            rp[i + 2] = 0.0f;

                            rp[i + 4] = -1.0f;
                            rp[i + 5] = -1.0f + (2.0f / trace_side) * y;
                            rp[i + 6] = -1.0f + (2.0f / trace_side) * x;

                            rp[i + 3] = 0.001f;
                            rp[i + 7] = 100000.0f;
                        }
                    }
                    rayIntersections.RayBuffer.EndBufferUpdate();

                    geometry.SetupBuild(0, (uint)(idxCount / 3), vertexBuffer.LocalBuffer, 0, indexBuffer.LocalBuffer, 0, false);
                }
            }


            vertS = new SpecializedShader()
            {
                Name               = "FST_Vert",
                Shader             = ShaderSource.Load(ShaderType.VertexShader, "FullScreenTriangle/vertex.glsl"),
                SpecializationData = null
            };

            fragS = new SpecializedShader()
            {
                Name               = "UVR_Frag",
                Shader             = ShaderSource.Load(ShaderType.FragmentShader, "FullScreenTriangle/clear_frag.glsl"),
                SpecializationData = null,
            };

            depthImages     = new Image[GraphicsDevice.MaxFramesInFlight];
            depthImageViews = new ImageView[GraphicsDevice.MaxFramesInFlight];
            for (int i = 0; i < GraphicsDevice.MaxFramesInFlight; i++)
            {
                depthImages[i] = new Image($"depthImage_{i}")
                {
                    Cubemappable  = false,
                    Width         = GraphicsDevice.Width,
                    Height        = GraphicsDevice.Height,
                    Depth         = 1,
                    Dimensions    = 2,
                    InitialLayout = ImageLayout.Undefined,
                    Layers        = 1,
                    Levels        = 1,
                    MemoryUsage   = MemoryUsage.GpuOnly,
                    Usage         = ImageUsage.DepthAttachment | ImageUsage.Sampled,
                    Format        = ImageFormat.Depth32f,
                };
                depthImages[i].Build(0);

                depthImageViews[i] = new ImageView($"depthImageView_{i}")
                {
                    BaseLayer  = 0,
                    BaseLevel  = 0,
                    Format     = ImageFormat.Depth32f,
                    LayerCount = 1,
                    LevelCount = 1,
                    ViewType   = ImageViewType.View2D,
                };
                depthImageViews[i].Build(depthImages[i]);
            }

            Engine.OnRebuildGraph += Engine_OnRebuildGraph;
            Engine.OnRender       += Engine_OnRender;
            Engine.OnUpdate       += Engine_OnUpdate;
            Engine.Start(0);
        }
 public LightVoxelShaderGroup(ShaderSource mixin) : base(mixin)
 {
     HasEffectPermutations = true;
     traceAttribute        = null;
 }
Example #35
0
        internal GL_Shader(GL_Graphics graphics, ShaderSource source)
        {
            this.graphics = graphics;

            if (graphics.MainThreadId != Thread.CurrentThread.ManagedThreadId)
            {
                lock (graphics.BackgroundContext)
                {
                    graphics.System.SetCurrentGLContext(graphics.BackgroundContext);

                    Create();
                    GL.Flush();

                    graphics.System.SetCurrentGLContext(null);
                }
            }
            else
            {
                Create();
            }

            void Create()
            {
                ID = GL.CreateProgram();

                Span <uint> shaders = stackalloc uint[2];

                // vertex shader
                if (source.Vertex != null)
                {
                    uint shaderId = GL.CreateShader(GLEnum.VERTEX_SHADER);
                    shaders[0] = shaderId;

                    string glsl = Encoding.UTF8.GetString(source.Vertex);

                    GL.ShaderSource(shaderId, 1, new[] { glsl }, new int[] { glsl.Length });
                    GL.CompileShader(shaderId);

                    string?errorMessage = GL.GetShaderInfoLog(shaderId);
                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        throw new Exception(errorMessage);
                    }

                    GL.AttachShader(ID, shaderId);
                }

                // fragment shader
                if (source.Fragment != null)
                {
                    uint shaderId = GL.CreateShader(GLEnum.FRAGMENT_SHADER);
                    shaders[1] = shaderId;

                    string glsl = Encoding.UTF8.GetString(source.Fragment);

                    GL.ShaderSource(shaderId, 1, new[] { glsl }, new int[] { glsl.Length });
                    GL.CompileShader(shaderId);

                    string?errorMessage = GL.GetShaderInfoLog(shaderId);
                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        throw new Exception(errorMessage);
                    }

                    GL.AttachShader(ID, shaderId);
                }

                GL.LinkProgram(ID);

                string?programError = GL.GetProgramInfoLog(ID);

                if (!string.IsNullOrEmpty(programError))
                {
                    throw new Exception(programError);
                }

                // get attributes
                GL.GetProgramiv(ID, GLEnum.ACTIVE_ATTRIBUTES, out int attributeCount);
                for (int i = 0; i < attributeCount; i++)
                {
                    GL.GetActiveAttrib(ID, (uint)i, out _, out _, out string name);
                    int location = GL.GetAttribLocation(ID, name);
                    if (location >= 0)
                    {
                        Attributes.Add(name, new ShaderAttribute(name, (uint)location));
                    }
                }

                // get uniforms
                GL.GetProgramiv(ID, GLEnum.ACTIVE_UNIFORMS, out int uniformCount);
                for (int i = 0; i < uniformCount; i++)
                {
                    GL.GetActiveUniform(ID, (uint)i, out int size, out GLEnum type, out string name);
                    int location = GL.GetUniformLocation(ID, name);
                    if (location >= 0)
                    {
                        if (size > 1 && name.EndsWith("[0]"))
                        {
                            name = name.Substring(0, name.Length - 3);
                        }

                        Uniforms.Add(name, new GL_Uniform(this, name, size, location, type));
                    }
                }

                // dispose shaders
                for (int i = 0; i < shaders.Length; i++)
                {
                    if (shaders[i] != 0)
                    {
                        GL.DetachShader(ID, shaders[i]);
                        GL.DeleteShader(shaders[i]);
                    }
                }
            }
        }
Example #36
0
 public void UseStreamWithCustomBlend(MaterialShaderStage stage, string stream, ShaderSource blendStream)
 {
     if (stream == null)
     {
         throw new ArgumentNullException(nameof(stream));
     }
     UseStream(stage, stream);
     registeredStreamBlend[stream] = blendStream;
 }
Example #37
0
        static void Main()
        {
            const float BlockSize = 0.02f;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var form = new Form();

            form.ClientSize = new Size(800, 600);

            var func          = MakeFunction(1 / BlockSize);
            var meshGenerator = new DCSolver(func, (int)(4 / BlockSize));
            var rawMesh       = meshGenerator.Solve();

            rawMesh = new MeshSimplifier(rawMesh, ClusterSizeHelper.GetSampleAverage(rawMesh, 3)).Run();
            var m = NormalMesh.MakeNormal(rawMesh);

            using (var device = LightDevice.Create(form))
            {
                var target = new RenderTargetList(device.GetDefaultTarget(Color.AliceBlue.WithAlpha(1)), device.CreateDepthStencilTarget());
                target.Apply();

                Pipeline pipeline = device.CompilePipeline(InputTopology.Triangle,
                                                           ShaderSource.FromResource("Viewer.Shader.fx", ShaderType.Vertex | ShaderType.Pixel));
                pipeline.Apply();

                var vertexConstant = pipeline.CreateConstantBuffer <Matrix4x4>();
                pipeline.SetConstant(ShaderType.Vertex, 0, vertexConstant);

                var input = pipeline.CreateVertexDataProcessor <Vertex>();
                var vb    = input.CreateImmutableBuffer(m.Vertices.Select(vv => new Vertex {
                    Position = new Vector4(m.Positions[vv.Position] * BlockSize, 1),
                    Normal   = new Vector4(vv.Normal, 0),
                }).ToArray());

                var ib = pipeline.CreateImmutableIndexBuffer(m.Triangles.SelectMany(tt => new[] { tt.Va, tt.Vb, tt.Vc }).ToArray());

                var camera = new Camera(new Vector3(10, 0, 0));
                camera.SetForm(form);
                var proj = device.CreatePerspectiveFieldOfView((float)Math.PI / 4).Transpose();

                vertexConstant.Value = proj * camera.GetViewMatrix();
                var pt = new Vector4(0, 0, 0, 0);
                var r  = Vector4.Transform(pt, vertexConstant.Value);

                form.Show();
                device.RunMultithreadLoop(delegate()
                {
                    target.ClearAll();

                    camera.Step();
                    var view             = camera.GetViewMatrix();
                    vertexConstant.Value = proj * view;
                    vertexConstant.Update();

                    ib.DrawAll(vb);
                    device.Present(true);
                });
            }
        }
Example #38
0
 public void SetStream(MaterialShaderStage stage, string stream, MaterialStreamType streamType, ShaderSource shaderSource)
 {
     currentLayerContext.SetStream(stage, stream, streamType, shaderSource);
 }
Example #39
0
 public bool AreEqual(ShaderSource shaderSource, SiliconStudio.Shaders.Parser.ShaderMacro[] macros)
 {
     return ShaderSource.Equals(shaderSource) && macros.All(macro => Macros.Any(x => x.Name == macro.Name && x.Definition == macro.Definition)) && Macros.All(macro => macros.Any(x => x.Name == macro.Name && x.Definition == macro.Definition));
 }
Example #40
0
        /// <summary>
        /// create the context for each composition by cloning their dependencies
        /// </summary>
        /// <param name="shaderSource">the entry ShaderSource (root)</param>
        /// <param name="dictionary">the ouputed compositions</param>
        /// <param name="compilationContext">the compilation context</param>
        /// <param name="cloneContext">The clone context.</param>
        /// <returns>a list of all the needed mixins</returns>
        private List <ModuleMixin> BuildCompositionsDictionary(ShaderSource shaderSource, Dictionary <Variable, List <ModuleMixin> > dictionary, ShaderCompilationContext compilationContext, CloneContext cloneContext)
        {
            if (shaderSource is ShaderMixinSource)
            {
                var shaderMixinSource = shaderSource as ShaderMixinSource;

                var finalModule = compilationContext.GetModuleMixinFromShaderSource(shaderSource);

                //PerformanceLogger.Start(PerformanceStage.DeepClone);
                finalModule = finalModule.DeepClone(new CloneContext(cloneContext));
                //PerformanceLogger.Pause(PerformanceStage.DeepClone);

                foreach (var composition in shaderMixinSource.Compositions)
                {
                    //look for the key
                    var foundVars = finalModule.FindAllVariablesByName(composition.Key).Where(value => value.Variable.Qualifiers.Contains(ParadoxStorageQualifier.Compose)).ToList();

                    if (foundVars.Count > 0)
                    {
                        Variable foundVar     = foundVars[0].Variable;
                        var      moduleMixins = BuildCompositionsDictionary(composition.Value, dictionary, compilationContext, cloneContext);
                        if (moduleMixins == null)
                        {
                            return(null);
                        }

                        dictionary.Add(foundVar, moduleMixins);
                    }
                    else
                    {
                        // TODO: log an error?
                    }
                }
                return(new List <ModuleMixin> {
                    finalModule
                });
            }


            if (shaderSource is ShaderClassSource)
            {
                var finalModule = compilationContext.GetModuleMixinFromShaderSource(shaderSource);

                //PerformanceLogger.Start(PerformanceStage.DeepClone);
                finalModule = finalModule.DeepClone(new CloneContext(cloneContext));
                //PerformanceLogger.Pause(PerformanceStage.DeepClone);

                return(new List <ModuleMixin> {
                    finalModule
                });
            }

            if (shaderSource is ShaderArraySource)
            {
                var shaderArraySource = shaderSource as ShaderArraySource;
                var compositionArray  = new List <ModuleMixin>();
                foreach (var shader in shaderArraySource.Values)
                {
                    var mixin = BuildCompositionsDictionary(shader, dictionary, compilationContext, cloneContext);
                    if (mixin == null)
                    {
                        return(null);
                    }
                    compositionArray.AddRange(mixin);
                }
                return(compositionArray);
            }

            return(null);
        }