Beispiel #1
0
        public Shader(string[] vs, string[] fs)
        {
            if (!compile(ref verterxId_, ShaderType.VertexShader, vs))
            {
                Console.WriteLine("ERROR: while compiling vertex shader");
            }
            if (!compile(ref fragmentId_, ShaderType.FragmentShader, fs))
            {
                Console.WriteLine("ERROR: while compiling fragment shader");
            }

            programId_ = Gl.CreateProgram();

            Gl.AttachShader(programId_, verterxId_);
            Gl.AttachShader(programId_, fragmentId_);

            Gl.BindAttribLocation(programId_, ATTRIB_VERTICES_POS, "in_vertex");

            Gl.LinkProgram(programId_);

            int errorlk = 0;

            Gl.GetProgram(programId_, ProgramProperty.LinkStatus, out errorlk);
            if (errorlk != Gl.TRUE)
            {
                Console.WriteLine("ERROR: while linking Shader :");
                int errorSize = 0;
                Gl.GetProgram(programId_, ProgramProperty.InfoLogLength, out errorSize);
                StringBuilder error = new StringBuilder(1024);
                Gl.GetShaderInfoLog(programId_, errorSize, out errorSize, error);
                Console.WriteLine(error.ToString());
                error.Clear();
                Gl.DeleteProgram(programId_);
            }
        }
        public static ShaderProgram Link(params Shader[] shaders)
        {
            if (shaders == null || shaders.Length == 0 || shaders.Any(s => s == null))
            {
                throw new ArgumentException("'shaders' can not be null or empty");
            }

            //Create new blank shader program
            uint program = Gl.CreateProgram();

            //Attach all shaders to the new program
            foreach (Shader shader in shaders)
            {
                Gl.AttachShader(program, shader.Id);
            }

            //Link program, merging the list of shaders into one program
            Gl.LinkProgram(program);

            //Check for link errors
            Gl.GetProgram(program, ProgramProperty.LinkStatus, out var linkStatus);
            if (linkStatus == Gl.FALSE)
            {
                StringBuilder logBuilder = new StringBuilder(2048);
                Gl.GetProgramInfoLog(program, logBuilder.Capacity, out var programLogLength, logBuilder);
                string log = logBuilder.ToString(0, programLogLength);
                throw new ArgumentException("Shader program failed to link:\n" + log);
            }

            return(new ShaderProgram(program));
        }
Beispiel #3
0
        public void Load()
        {
            if (ShaderContainer.Shaders.Any(s => s.fragShaderAsset.MountPath == fragShaderAsset.MountPath && s.vertShaderAsset.MountPath == vertShaderAsset.MountPath))
            {
                var cachedShader = ShaderContainer.Shaders.First(s => s.fragShaderAsset.MountPath == fragShaderAsset.MountPath && s.vertShaderAsset.MountPath == vertShaderAsset.MountPath);
                Id = cachedShader.Id;
                return;
            }

            var fragGlslContents = fragShaderAsset.AsString();
            var vertGlslContents = vertShaderAsset.AsString();

            var fragId = Gl.CreateShader(ShaderType.FragmentShader);
            Gl.ShaderSource(fragId, new[] { fragGlslContents });
            Gl.CompileShader(fragId);

            CheckForErrors(fragId);

            var vertId = Gl.CreateShader(ShaderType.VertexShader);
            Gl.ShaderSource(vertId, new[] { vertGlslContents });
            Gl.CompileShader(vertId);

            CheckForErrors(vertId);

            Id = Gl.CreateProgram();
            Gl.AttachShader(Id, fragId);
            Gl.AttachShader(Id, vertId);
            Gl.LinkProgram(Id);

            Gl.DeleteShader(fragId);
            Gl.DeleteShader(vertId);
        }
Beispiel #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OpenGLShader"/> class.
        /// </summary>
        /// <param name="name">The shader name.</param>
        /// <param name="vertexShaderPath">The vertex shader path.</param>
        /// <param name="fragmentShaderPath">The fragment shader path.</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="FileNotFoundException"></exception>
        public OpenGLShader(string name, string vertexShaderPath, string fragmentShaderPath)
        {
            if (string.IsNullOrWhiteSpace(name) ||
                string.IsNullOrWhiteSpace(vertexShaderPath) ||
                string.IsNullOrWhiteSpace(fragmentShaderPath))
            {
                throw new ArgumentNullException();
            }

            if (!File.Exists(vertexShaderPath) || !File.Exists(fragmentShaderPath))
            {
                throw new FileNotFoundException();
            }

            Name = name;

            var vertexSource   = new[] { File.ReadAllText(vertexShaderPath) };
            var fragmentSource = new[] { File.ReadAllText(fragmentShaderPath) };

            _uniforms = new Dictionary <string, int>();
            var vertexShader   = CreateShader(vertexSource, ShaderType.VertexShader);
            var fragmentShader = CreateShader(fragmentSource, ShaderType.FragmentShader);

            _id = Gl.CreateProgram();

            Gl.AttachShader(_id, vertexShader);
            Gl.AttachShader(_id, fragmentShader);
            Gl.LinkProgram(_id);

            Gl.DetachShader(_id, vertexShader);
            Gl.DetachShader(_id, fragmentShader);
            Gl.DeleteShader(vertexShader);
            Gl.DeleteShader(fragmentShader);
        }
Beispiel #5
0
        public Shader(string fragGlslPath, string vertGlslPath)
        {
            var fragGlslContents = File.ReadAllText(fragGlslPath);
            var vertGlslContents = File.ReadAllText(vertGlslPath);

            var fragId = Gl.CreateShader(ShaderType.FragmentShader);

            Gl.ShaderSource(fragId, new[] { fragGlslContents });
            Gl.CompileShader(fragId);

            CheckForErrors(fragId);

            var vertId = Gl.CreateShader(ShaderType.VertexShader);

            Gl.ShaderSource(vertId, new[] { vertGlslContents });
            Gl.CompileShader(vertId);

            CheckForErrors(vertId);

            Id = Gl.CreateProgram();
            Gl.AttachShader(Id, fragId);
            Gl.AttachShader(Id, vertId);
            Gl.LinkProgram(Id);

            Gl.DeleteShader(fragId);
            Gl.DeleteShader(vertId);
        }
Beispiel #6
0
        public Shader BuildShader()
        {
            uint programHandle = Gl.CreateProgram();

            Gl.ProgramParameter(programHandle, ProgramParameterPName.ProgramSeparable, Gl.TRUE);

            foreach (var stage in shaderStages)
            {
                Gl.AttachShader(programHandle, stage.Handle);
            }

            Gl.LinkProgram(programHandle);

            Gl.GetProgram(programHandle, ProgramProperty.LinkStatus, out int linked);
            if (linked != Gl.TRUE)
            {
                Gl.GetProgram(programHandle, ProgramProperty.InfoLogLength, out int logLength);
                var errorLog = new StringBuilder(logLength);
                Gl.GetProgramInfoLog(programHandle, logLength, out int _, errorLog);
                throw new Exception("Shader Linking Errors: \n" + errorLog);
            }

            foreach (var stage in shaderStages)
            {
                Gl.DetachShader(programHandle, stage.Handle);
            }

            ClearCurrentBuild();
            return(new Shader(programHandle));
        }
Beispiel #7
0
        private static uint CreateProgram(uint vertexShader, uint fragmentShader)
        {
            uint program = Gl.CreateProgram();

            Gl.AttachShader(program, vertexShader);
            Gl.AttachShader(program, fragmentShader);
            Gl.LinkProgram(program);

            int linked;

            Gl.GetProgram(program, ProgramProperty.LinkStatus, out linked);
            if (linked == 0)
            {
                const int     logMaxLength = 1024;
                StringBuilder infoLog      = new StringBuilder(logMaxLength);
                int           infoLogLength;

                Gl.GetProgramInfoLog(program, logMaxLength, out infoLogLength, infoLog);
                throw new InvalidOperationException($"unable to link shader program: {infoLog}");
            }

            Gl.DeleteShader(vertexShader);
            Gl.DeleteShader(fragmentShader);

            return(program);
        }
        protected void UploadShaders(ShaderResource[] shaders)
        {
            Verify.VerifyShaders(shaders);

            foreach (var shader in shaders)
            {
                Gl.AttachShader(Handle, shader.Handle);
            }

            Gl.LinkProgram(Handle);

            foreach (var shader in shaders)
            {
                Gl.DetachShader(Handle, shader.Handle);
            }

            Gl.GetProgram(Handle, ProgramProperty.LinkStatus, out int linked);

            if (linked == 0)
            {
                var log = ReadProgramLog(Handle);

                throw new InvalidOperationException($"Shader linking failed: {log}");
            }
        }
Beispiel #9
0
            public ShaderProgram(string[] vertexSource, string[] fragmentSource)
            {
                //create vertex and fragment shaders
                //create the objects in a way that will call the Dispose function when GC cleans them up
                using (ShaderObject vertex = new ShaderObject(ShaderType.VertexShader, vertexSource))
                    using (ShaderObject fragment = new ShaderObject(ShaderType.FragmentShader, fragmentSource))
                    {
                        //tell the gpu to create a shader program, and give us the ID number for it
                        ProgramID = Gl.CreateProgram();
                        //connect the vertex and fragment shaders to it
                        Gl.AttachShader(ProgramID, vertex.ShaderID);
                        Gl.AttachShader(ProgramID, fragment.ShaderID);
                        //link program, not sure what this means
                        Gl.LinkProgram(ProgramID);

                        //check for errors
                        Gl.GetProgram(ProgramID, ProgramProperty.LinkStatus, out int linked);
                        if (linked == 0)
                        {
                            //it f****d up
                        }

                        //get the location of the uniform variables in the shaders
                        attribUniformLoc = Gl.GetUniformLocation(ProgramID, "uMVP");
                        //get the location of the position and color attributes in the shaders
                        attribPositionLoc = Gl.GetAttribLocation(ProgramID, "aPosition");
                        attribColorLoc    = Gl.GetAttribLocation(ProgramID, "aColor");
                        //you should probably check to make sure those worked too, but im lazy
                    }
            }
Beispiel #10
0
        private void CreateShaders()
        {
            var fragmentShader = Gl.CreateShader(ShaderType.FragmentShader);
            var vertexShader   = Gl.CreateShader(ShaderType.VertexShader);

            var sb = new StringBuilder(1000);

            void CompileShader(uint id, string file)
            {
                var source = LoadShaderFromResource(file);

                Gl.ShaderSource(id, new[] { source });
                Gl.CompileShader(id);

                Gl.GetShader(id, ShaderParameterName.CompileStatus, out int compileStatus);
                Debug.WriteLine($"Compile status: {compileStatus == Gl.TRUE}");
                Gl.GetShaderInfoLog(id, sb.Capacity, out int _, sb);
                Debug.WriteLine(sb.ToString());
            }

            CompileShader(fragmentShader, "FragmentShader.glsl");
            CompileShader(vertexShader, "VertexShader.glsl");

            _program = Gl.CreateProgram();
            Gl.AttachShader(_program, fragmentShader);
            Gl.AttachShader(_program, vertexShader);
            Gl.LinkProgram(_program);

            Gl.GetProgram(_program, ProgramProperty.LinkStatus, out int linkResult);
            Debug.WriteLine($"Link status: {linkResult == Gl.TRUE}");
            Gl.GetProgramInfoLog(_program, sb.Capacity, out int _, sb);
        }
Beispiel #11
0
        private bool CreateDeviceObjects()
        {
            // Backup GL state
            // but why??
            Gl.GetInteger(GetPName.TextureBinding2d, out int lastTexture);
            Gl.GetInteger(GetPName.ArrayBufferBinding, out int lastArrayBuffer);
            Gl.GetInteger(GetPName.VertexArrayBinding, out int lastVertexArray);

            // Create shaders
            string shaderSource;

            var assembly = Assembly.GetExecutingAssembly();

            using (var data = assembly.GetManifestResourceStream("imgui-vertex.glsl"))
                using (var stream = new StreamReader(data))
                {
                    shaderSource = stream.ReadToEnd();
                }

            _vertHandle = Gl.CreateShader(ShaderType.VertexShader);
            Gl.ShaderSource(_vertHandle, new string[] { shaderSource });
            Gl.CompileShader(_vertHandle);
            CheckShader(_vertHandle, "vertex shader");

            using (var data = assembly.GetManifestResourceStream("imgui-frag.glsl"))
                using (var stream = new StreamReader(data))
                {
                    shaderSource = stream.ReadToEnd();
                }

            _fragHandle = Gl.CreateShader(ShaderType.FragmentShader);
            Gl.ShaderSource(_fragHandle, new string[] { shaderSource });
            Gl.CompileShader(_fragHandle);
            CheckShader(_fragHandle, "fragment shader");

            _shaderHandle = Gl.CreateProgram();
            Gl.AttachShader(_shaderHandle, _vertHandle);
            Gl.AttachShader(_shaderHandle, _fragHandle);
            Gl.LinkProgram(_shaderHandle);
            CheckProgram(_shaderHandle, "shader program");

            _attribLocationTex      = Gl.GetUniformLocation(_shaderHandle, "Texture");
            _attribLocationProjMtx  = Gl.GetUniformLocation(_shaderHandle, "ProjMtx");
            _attribLocationVtxPos   = Gl.GetAttribLocation(_shaderHandle, "Position");
            _attribLocationVtxUV    = Gl.GetAttribLocation(_shaderHandle, "UV");
            _attribLocationVtxColor = Gl.GetAttribLocation(_shaderHandle, "Color");

            _vboHandle      = Gl.GenBuffer();
            _elementsHandle = Gl.GenBuffer();

            CreateFontsTexture();

            // Restore modified GL state
            Gl.BindTexture(TextureTarget.Texture2d, (uint)lastTexture);
            Gl.BindBuffer(BufferTarget.ArrayBuffer, (uint)lastArrayBuffer);
            Gl.BindVertexArray((uint)lastVertexArray);

            return(true);
        }
Beispiel #12
0
 public ShaderProgram(params Shader[] shaders)
 {
     _handle = Gl.CreateProgram();
     foreach (var shader in shaders)
     {
         Gl.AttachShader(_handle, (uint)shader);
     }
 }
Beispiel #13
0
        public ShaderProgram(Shader[] shaders, string[] uniformNames, string[] attributeNames)
        {
            Uniforms   = _uniforms;
            Attributes = _attributes;

            ID = Gl.CreateProgram();
            foreach (var shader in shaders)
            {
                Gl.AttachShader(ID, shader.ID);
            }
            Gl.LinkProgram(ID);

            int linked;

            Gl.GetProgram(ID, ProgramProperty.LinkStatus, out linked);

            if (linked == 0)
            {
                const int maxLogLength = 1024;
                var       infoLog      = new System.Text.StringBuilder(maxLogLength);
                int       infoLogLength;
                Gl.GetProgramInfoLog(ID, maxLogLength, out infoLogLength, infoLog);
                string message = $"Unable to link program: {infoLog}";
                Trace.TraceError(message);
                throw new InvalidOperationException(message);
            }

            foreach (var shader in shaders)
            {
                Gl.DetachShader(ID, shader.ID);
            }

            foreach (var uniformName in uniformNames)
            {
                int uniformId = Gl.GetUniformLocation(ID, uniformName);
                if (uniformId < 0)
                {
                    string message = $"Could not locate uniform {uniformName}";
                    Trace.TraceError(message);
                    throw new InvalidOperationException(message);
                }
                _uniforms.Add(uniformName, uniformId);
            }

            foreach (var attributeName in attributeNames)
            {
                int attributeId = Gl.GetAttribLocation(ID, attributeName);
                if (attributeId < 0)
                {
                    string message = $"Could not locate attribute '{attributeName}'";
                    Trace.TraceError(message);
                    throw new InvalidOperationException(message);
                }
                _attributes.Add(attributeName, attributeId);
            }
        }
Beispiel #14
0
        public GlImage(Bitmap bitmap)
        {
            Width  = bitmap.Width;
            Height = bitmap.Height;

            m_tex = new uint[1];

            var d = bitmap.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

            bitmap.UnlockBits(d);

            Gl.GenTextures(1, m_tex);
            Gl.BindTexture(Gl.GL_TEXTURE_2D, m_tex[0]);

            Gl.TexImage2D(Gl.GL_TEXTURE_2D, 0, Gl.GL_RGB, Width, Height, 0, Gl.GL_BGR, Gl.GL_UNSIGNED_BYTE, d.Scan0);
            Gl.TexParameter(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_NEAREST);
            Gl.TexParameter(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_NEAREST);
            Gl.BindTexture(Gl.GL_TEXTURE_2D, 0);

            ShaderProgram = Gl.CreateProgram();

            Gl.AttachShader(ShaderProgram, CreateShader(Gl.GL_VERTEX_SHADER, @"
                #version 330
                in vec3 vert;
                in vec2 vertTexCoord;
                out vec2 fragTexCoord;
    
                uniform mat4 projectionMatrix;

                void main()
                {
                    fragTexCoord = vertTexCoord;

                    gl_Position = projectionMatrix * vec4(vert.xy, 0, 1);
                }
            "));

            Gl.AttachShader(ShaderProgram, CreateShader(Gl.GL_FRAGMENT_SHADER, @"
                #version 330
                uniform sampler2D tex; 
                in vec2 fragTexCoord;
                out vec4 finalColor;

                void main() {
                    finalColor = texture2D(tex, fragTexCoord);
                }
                "));

            Gl.LinkProgram(ShaderProgram);
            var success = new int[1];

            Gl.GetProgram(ShaderProgram, Gl.GL_LINK_STATUS, success);

            Gl.ValidateProgram(ShaderProgram);
            Gl.GetProgram(ShaderProgram, Gl.GL_LINK_STATUS, success);
        }
Beispiel #15
0
        private uint CreateProgramUniform(string[] srcVertex, string[] srcFragment)
        {
            uint shaderVertex = 0, shaderFragment = 0, program = 0;

            try {
                int compileStatus;

                shaderVertex = Gl.CreateShader(ShaderType.VertexShader);
                Gl.ShaderSource(shaderVertex, srcVertex);
                Gl.CompileShader(shaderVertex);
                Gl.GetShader(shaderVertex, ShaderParameterName.CompileStatus, out compileStatus);
                if (compileStatus == 0)
                {
                    throw new InvalidOperationException("unable to compiler vertex shader: " + GetShaderInfoLog(shaderVertex));
                }

                shaderFragment = Gl.CreateShader(ShaderType.FragmentShader);
                Gl.ShaderSource(shaderFragment, srcFragment);
                Gl.CompileShader(shaderFragment);
                Gl.GetShader(shaderFragment, ShaderParameterName.CompileStatus, out compileStatus);
                if (compileStatus == 0)
                {
                    throw new InvalidOperationException("unable to compiler fragment shader: " + GetShaderInfoLog(shaderFragment));
                }

                program = Gl.CreateProgram();
                Gl.AttachShader(program, shaderVertex);
                Gl.AttachShader(program, shaderFragment);
                Gl.LinkProgram(program);
                Gl.GetProgram(program, ProgramProperty.LinkStatus, out compileStatus);
                if (compileStatus == 0)
                {
                    throw new InvalidOperationException("unable to link program");
                }

                Gl.UseProgram(program);
            } catch {
                if (shaderVertex != 0)
                {
                    Gl.DeleteShader(shaderVertex);
                }
                if (shaderFragment != 0)
                {
                    Gl.DeleteShader(shaderFragment);
                }
                if (shaderFragment != 0)
                {
                    Gl.DeleteProgram(program);
                }

                throw;
            }


            return(program);
        }
 public ShaderProgram(string[] vertexShader, string[] fragmentShader)
 {
     vertexShaderID   = loadShader(vertexShader, ShaderType.VertexShader);
     fragmentShaderID = loadShader(fragmentShader, ShaderType.FragmentShader);
     programID        = Gl.CreateProgram();
     Gl.AttachShader(programID, vertexShaderID);
     Gl.AttachShader(programID, fragmentShaderID);
     bindAttributes();
     Gl.LinkProgram(programID);
     Gl.ValidateProgram(programID);
 }
Beispiel #17
0
 private void Link(string[] vertexShaderSource, string[] fragmentShaderSource)
 {
     using (var vertexShader = new Shader(ShaderType.VertexShader, vertexShaderSource))
         using (var fragmentShader = new Shader(ShaderType.FragmentShader, fragmentShaderSource))
         {
             Id = Gl.CreateProgram();
             Gl.AttachShader(Id, vertexShader.Id);
             Gl.AttachShader(Id, fragmentShader.Id);
             Gl.LinkProgram(Id);
         }
 }
Beispiel #18
0
        public ParticleEmitter(ParticleResourceModel _md, int _maxRenderTime)
        {
            md = _md;
            //zIndex = _zIndex;
            maxRenderTime = _maxRenderTime;

            attrBufferId = Gl.GenBuffer();
            //bufferId = Gl.GenVertexArray();
            texId = Gl.GenTexture();
            //texFraBufferId = Gl.GenFramebuffer();

            string[] vetex    = ComUtil.loadEmbedShader("vParticleEmitter.glsl");
            string[] fragment = ComUtil.loadEmbedShader("fParticleEmitter.glsl");

            using (GlObject vObject = new GlObject(ShaderType.VertexShader, vetex))
                using (GlObject fObject = new GlObject(ShaderType.FragmentShader, fragment)) {
                    // Create program
                    ProgramName = Gl.CreateProgram();
                    // Attach shaders
                    Gl.AttachShader(ProgramName, vObject.ShaderName);
                    Gl.AttachShader(ProgramName, fObject.ShaderName);
                    // Link program
                    Gl.LinkProgram(ProgramName);

                    // Check linkage status
                    Gl.GetProgram(ProgramName, ProgramProperty.LinkStatus, out int linked);

                    if (linked == 0)
                    {
                        const int logMaxLength = 1024;

                        StringBuilder infolog = new StringBuilder(logMaxLength);
                        int           infologLength;

                        Gl.GetProgramInfoLog(ProgramName, 1024, out infologLength, infolog);

                        throw new InvalidOperationException($"unable to link program: {infolog}");
                    }

                    LocationMVP     = getUniformId("uMVP");
                    LocationIndex   = getAttrId("index");
                    LocationCoord   = getAttrId("vCoord");
                    LocationTex     = getUniformId("tex");
                    LocationNowTime = getUniformId("nowTime");
                    //LocationZIndex = getUniformId("zIndex");
                    LocationTotalLifeTime = getUniformId("totalLifeTime");
                    LocationParticleCount = getUniformId("particleCount");
                    LocationStartPos      = getUniformId("startPos");
                }

            updateImage();
            updateAttr();
        }
Beispiel #19
0
        protected override GPUProgramData OnRegister(GPUProgram key)
        {
            GPUProgramData shaderData = new GPUProgramData();

            shaderData.program = Gl.CreateProgram();
            shaderData.vs      = Compile(OpenGL.ShaderType.VertexShader, key.vertexShaderSourceCode);
            shaderData.fs      = Compile(OpenGL.ShaderType.FragmentShader, key.fragmentShaderSourceCode);
            Gl.AttachShader(shaderData.program, shaderData.vs);
            Gl.AttachShader(shaderData.program, shaderData.fs);
            Gl.LinkProgram(shaderData.program);
            return(shaderData);
        }
Beispiel #20
0
        /// <summary>
        /// Create a shader program by linking compiled shaders.
        /// </summary>
        /// <param name="vertShader">The vert shader to attach.</param>
        /// <param name="fragShader">The frag shader to attach.</param>
        /// <returns></returns>
        public static ShaderProgram CreateFromShaders(uint vertShader, uint fragShader)
        {
            Debug.Assert(GLThread.IsGLThread());

            uint pointer = Gl.CreateProgram();

            Gl.AttachShader(pointer, vertShader);
            Gl.AttachShader(pointer, fragShader);

            // Set default parameter locations.
            Gl.BindAttribLocation(pointer, VertexLocation, "vertPos");
            Gl.BindAttribLocation(pointer, UvLocation, "uv");
            Gl.BindAttribLocation(pointer, ColorLocation, "color");

            Gl.LinkProgram(pointer);
            if (Engine.Configuration.GlDebugMode)
            {
                Gl.ValidateProgram(pointer);
            }

            // Check linking status.
            var programCompileStatusReader = new StringBuilder(1024);

            Gl.GetProgramInfoLog(pointer, 1024, out int length, programCompileStatusReader);
            if (length > 0)
            {
                var programStatus = programCompileStatusReader.ToString(0, length);
                if (programStatus != "")
                {
                    Engine.Log.Warning($"Log for linking shaders (v:{vertShader} f:{fragShader}) is {programStatus}", MessageSource.GL);
                }
            }

            var valid = false;

            Gl.GetProgram(pointer, ProgramProperty.LinkStatus, out int state);
            if (state == 0)
            {
                Engine.Log.Warning($"Couldn't link shader program {pointer}.", MessageSource.GL);
            }
            else
            {
                valid = true;
            }

            var newProgram = new ShaderProgram
            {
                Pointer = pointer,
                Valid   = valid
            };

            return(newProgram);
        }
Beispiel #21
0
        public bool AddShader(ShaderType shaderType, string fileName)
        {
            var shader = new Shader(shaderType, fileName);

            if (!shader.Init())
            {
                return(false);
            }
            Shaders.Add(shader);
            Gl.AttachShader(ProgramId, shader.ShaderId);
            return(true);
        }
Beispiel #22
0
        private void RenderControl_ContextCreated(object sender, GlControlEventArgs e)
        {
            // Update Form caption
            Text = String.Format("Hello triangle with ANGLE (Version: {0})", Gl.GetString(StringName.Version));

            // Create resources
            StringBuilder infolog = new StringBuilder(1024);
            int           infologLength;
            int           compiled;

            infolog.EnsureCapacity(1024);

            // Vertex shader
            uint vertexShader = Gl.CreateShader(ShaderType.VertexShader);

            Gl.ShaderSource(vertexShader, _Es2_ShaderVertexSource);
            Gl.CompileShader(vertexShader);
            Gl.GetShader(vertexShader, ShaderParameterName.CompileStatus, out compiled);
            if (compiled == 0)
            {
                Gl.GetShaderInfoLog(vertexShader, 1024, out infologLength, infolog);
            }

            // Fragment shader
            uint fragmentShader = Gl.CreateShader(ShaderType.FragmentShader);

            Gl.ShaderSource(fragmentShader, _Es2_ShaderFragmentSource);
            Gl.CompileShader(fragmentShader);
            Gl.GetShader(fragmentShader, ShaderParameterName.CompileStatus, out compiled);
            if (compiled == 0)
            {
                Gl.GetShaderInfoLog(fragmentShader, 1024, out infologLength, infolog);
            }

            // Program
            _Es2_Program = Gl.CreateProgram();
            Gl.AttachShader(_Es2_Program, vertexShader);
            Gl.AttachShader(_Es2_Program, fragmentShader);
            Gl.LinkProgram(_Es2_Program);

            int linked;

            Gl.GetProgram(_Es2_Program, ProgramProperty.LinkStatus, out linked);

            if (linked == 0)
            {
                Gl.GetProgramInfoLog(_Es2_Program, 1024, out infologLength, infolog);
            }

            _Es2_Program_Location_uMVP      = Gl.GetUniformLocation(_Es2_Program, "uMVP");
            _Es2_Program_Location_aPosition = Gl.GetAttribLocation(_Es2_Program, "aPosition");
            _Es2_Program_Location_aColor    = Gl.GetAttribLocation(_Es2_Program, "aColor");
        }
Beispiel #23
0
        private void Es2_ContextCreated()
        {
            int compilationStatus;

            // Vertex shader
            uint vertexShader = Gl.CreateShader(ShaderType.VertexShader);

            Gl.ShaderSource(vertexShader, _Es2_ShaderVertexSource);
            Gl.CompileShader(vertexShader);

            // Fragment shader
            uint fragmentShader = Gl.CreateShader(ShaderType.FragmentShader);

            Gl.ShaderSource(fragmentShader, _Es2_ShaderFragmentSource);
            Gl.CompileShader(fragmentShader);

            // Program
            _Es2_Program = Gl.CreateProgram();
            Gl.AttachShader(_Es2_Program, vertexShader);
            Gl.AttachShader(_Es2_Program, fragmentShader);
            Gl.LinkProgram(_Es2_Program);

            // Check for linking errors
            int lStatus;

            Gl.GetProgram(_Es2_Program, Gl.LINK_STATUS, out lStatus);

            if (lStatus != Gl.TRUE)
            {
                const int MaxInfoLength = 4096;

                StringBuilder logInfo = new StringBuilder(MaxInfoLength);
                int           logLength;

                // Obtain compilation log
                Gl.GetProgramInfoLog(_Es2_Program, MaxInfoLength, out logLength, logInfo);

                // Stop link process
                StringBuilder sb = new StringBuilder(logInfo.Capacity);

                string[] compilerLogLines = logInfo.ToString().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string logLine in compilerLogLines)
                {
                    sb.AppendLine("  $ " + logLine);
                }

                throw new InvalidOperationException(sb.ToString());
            }
            _Es2_Program_Location_uMVP      = Gl.GetUniformLocation(_Es2_Program, "uMVP");
            _Es2_Program_Location_aPosition = Gl.GetAttribLocation(_Es2_Program, "aPosition");
            _Es2_Program_Location_aColor    = Gl.GetAttribLocation(_Es2_Program, "aColor");
        }
        /// <summary>
        /// Creates the shader and returns the handle to it
        /// </summary>
        /// <param name="vertexSource"></param>
        /// <param name="fragmentSource"></param>
        /// <returns></returns>
        private static uint CreateShader(string[] vertexSource, string[] fragmentSource)
        {
            StringBuilder infolog = new StringBuilder(1024);
            int           infoLogLength;

            // Create a shader id
            uint programid  = Gl.CreateProgram();
            uint vertexId   = Gl.CreateShader(ShaderType.VertexShader);
            uint fragmentId = Gl.CreateShader(ShaderType.FragmentShader);

            // Create shader from source
            Gl.ShaderSource(vertexId, vertexSource);
            Gl.ShaderSource(fragmentId, fragmentSource);

            int compileStatus = 0;

            // Compile the shaders
            Gl.CompileShader(vertexId);
            Gl.GetShader(vertexId, ShaderParameterName.CompileStatus, out compileStatus);

            if (compileStatus == 0)
            {
                Gl.GetShaderInfoLog(vertexId, 1024, out infoLogLength, infolog);
            }

            Gl.CompileShader(fragmentId);
            Gl.GetShader(fragmentId, ShaderParameterName.CompileStatus, out compileStatus);

            if (compileStatus == 0)
            {
                Gl.GetShaderInfoLog(fragmentId, 1024, out infoLogLength, infolog);
            }

            if (infolog.Length > 0)
            {
                Debug.Log("Could not compile shaders " + infolog, Debug.DebugLayer.Shaders, Debug.DebugLevel.Warning);
            }

            // Attach the shaders to the shader program
            Gl.AttachShader(programid, vertexId);
            Gl.AttachShader(programid, fragmentId);

            // Link the shaders
            Gl.LinkProgram(programid);

            // Validate the shader program
            Gl.ValidateProgram(programid);

            Debug.Log("Shaders Compiled: Id " + vertexId + ":" + fragmentId, Debug.DebugLayer.Shaders, Debug.DebugLevel.Information);

            return(programid);
        }
        public ShadingProgram()
        {
            _program = Gl.CreateProgram();

            var vertexShader   = new Shader(ShaderType.VertexShader, "./Shaders/InstanceShader.vs");
            var fragmentShader = new Shader(ShaderType.FragmentShader, "./Shaders/InstanceShader.fs");

            Gl.AttachShader(_program, vertexShader.GlShader);
            Gl.AttachShader(_program, fragmentShader.GlShader);
            Gl.LinkProgram(_program);

            Validate();
        }
Beispiel #26
0
        /// <summary>
        /// Links a vertex and fragment shader together to create a shader program.
        /// </summary>
        /// <param name="vertexShader">Specifies the vertex shader.</param>
        /// <param name="fragmentShader">Specifies the fragment shader.</param>
        public ShaderProgram(Shader vertexShader, Shader fragmentShader)
        {
            this.VertexShader    = vertexShader;
            this.FragmentShader  = fragmentShader;
            this.ProgramID       = Gl.CreateProgram();
            this.DisposeChildren = false;

            Gl.AttachShader(ProgramID, vertexShader.ShaderID);
            Gl.AttachShader(ProgramID, fragmentShader.ShaderID);
            Gl.LinkProgram(ProgramID);

            GetParams();
        }
Beispiel #27
0
        uint LinkProgramInternal()
        {
            CheckCurrent();

            // Create shader program.
            var programHandle = Gl.CreateProgram();

            // Attach shaders
            Gl.AttachShader(programHandle, _vertexShader.ShaderHandle);
            Gl.AttachShader(programHandle, _fragmentShader.ShaderHandle);

            // Link the program
            Gl.LinkProgram(programHandle);

            // Get the log
            int logLen;

            Gl.GetProgram(programHandle, ProgramProperty.InfoLogLength, out logLen);

            // Anything in the log?
            string log = "n/a";

            if (logLen > 0)
            {
                var infolog = new StringBuilder(logLen + 10);
                int infologLength;
                Gl.GetProgramInfoLog(programHandle, logLen + 10, out infologLength, infolog);

                log = infolog.ToString();

                if (!string.IsNullOrEmpty(log))
                {
                    Console.WriteLine("Program link log:\n{0}", log);
                }
            }

            // Detach shaders now that we've linked the program
            Gl.DetachShader(programHandle, _vertexShader.ShaderHandle);
            Gl.DetachShader(programHandle, _fragmentShader.ShaderHandle);


            int status;

            Gl.GetProgram(programHandle, ProgramProperty.LinkStatus, out status);
            if (status == 0)
            {
                throw new InvalidOperationException(string.Format("Failed to link shader program: {0}", log));
            }

            return(programHandle);
        }
Beispiel #28
0
        private void RenderControl_ContextCreated_ES(object sender, GlControlEventArgs e)
        {
            StringBuilder infolog = new StringBuilder(1024);
            int           infologLength;
            int           compiled;

            infolog.EnsureCapacity(1024);

            // Vertex shader
            uint vertexShader = Gl.CreateShader(Gl.VERTEX_SHADER);

            Gl.ShaderSource(vertexShader, _Es2_ShaderVertexSource);
            Gl.CompileShader(vertexShader);
            Gl.GetShader(vertexShader, Gl.COMPILE_STATUS, out compiled);
            if (compiled == 0)
            {
                Gl.GetShaderInfoLog(vertexShader, 1024, out infologLength, infolog);
            }

            // Fragment shader
            uint fragmentShader = Gl.CreateShader(Gl.FRAGMENT_SHADER);

            Gl.ShaderSource(fragmentShader, _Es2_ShaderFragmentSource);
            Gl.CompileShader(fragmentShader);
            Gl.GetShader(fragmentShader, Gl.COMPILE_STATUS, out compiled);
            if (compiled == 0)
            {
                Gl.GetShaderInfoLog(fragmentShader, 1024, out infologLength, infolog);
            }

            // Program
            Program_Shader = Gl.CreateProgram();
            Gl.AttachShader(Program_Shader, vertexShader);
            Gl.AttachShader(Program_Shader, fragmentShader);
            Gl.LinkProgram(Program_Shader);

            int linked;

            Gl.GetProgram(Program_Shader, Gl.LINK_STATUS, out linked);

            if (linked == 0)
            {
                Gl.GetProgramInfoLog(Program_Shader, 1024, out infologLength, infolog);
            }

            Program_Location_uProjection = Gl.GetUniformLocation(Program_Shader, "uProjection");
            Program_Location_uView       = Gl.GetUniformLocation(Program_Shader, "uView");
            Program_Location_uModel      = Gl.GetUniformLocation(Program_Shader, "uModel");
            Program_Location_aPosition   = Gl.GetAttribLocation(Program_Shader, "aPosition");
            Program_Location_aColor      = Gl.GetAttribLocation(Program_Shader, "aColor");
        }
Beispiel #29
0
        private void CompileShaders(string vertexCode, string fragmentCode)
        {
            uint          vertex, fragment;
            int           success;
            StringBuilder infoLog = new StringBuilder(512);

            // Vertex Shader
            vertex = Gl.CreateShader(Gl.VERTEX_SHADER);
            Gl.ShaderSource(vertex, new[] { vertexCode });
            Gl.CompileShader(vertex);
            // Print compile errors if any
            Gl.GetShader(vertex, Gl.COMPILE_STATUS, out success);
            if (success == 0)
            {
                int length;
                Gl.GetShaderInfoLog(vertex, 512, out length, infoLog);
                MessageBox.Show(Render.Program.bithack3D, "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" + infoLog.ToString());
                Render.Program.bithack3D.BeginInvoke(new MethodInvoker(Render.Program.bithack3D.Close));
            }
            // Fragment Shader
            fragment = Gl.CreateShader(Gl.FRAGMENT_SHADER);
            Gl.ShaderSource(fragment, new[] { fragmentCode });
            Gl.CompileShader(fragment);
            // Print compile errors if any
            Gl.GetShader(fragment, Gl.COMPILE_STATUS, out success);
            if (success == 0)
            {
                int length;
                Gl.GetShaderInfoLog(vertex, 512, out length, infoLog);
                MessageBox.Show(Render.Program.bithack3D, "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" + infoLog.ToString());
                Render.Program.bithack3D.BeginInvoke(new MethodInvoker(Render.Program.bithack3D.Close));
            }
            // Shader Program
            this.Program = Gl.CreateProgram();
            Gl.AttachShader(this.Program, vertex);
            Gl.AttachShader(this.Program, fragment);
            Gl.LinkProgram(this.Program);
            // Print linking errors if any
            Gl.GetProgram(this.Program, Gl.LINK_STATUS, out success);
            if (success == 0)
            {
                int length;
                Gl.GetProgramInfoLog(this.Program, 512, out length, infoLog);
                MessageBox.Show(Render.Program.bithack3D, "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" + infoLog.ToString());
                Render.Program.bithack3D.BeginInvoke(new MethodInvoker(Render.Program.bithack3D.Close));
            }
            // Delete the shaders as they're linked into our program now and no longer necessery
            Gl.DeleteShader(vertex);
            Gl.DeleteShader(fragment);
        }
Beispiel #30
0
        public Program(string[] vertexSource, string[] fragmentSource)
        {
            // Create vertex and frament shaders
            // Note: they can be disposed after linking to program; resources are freed when deleting the program
            using (Object vObject = new Object(ShaderType.VertexShader, vertexSource))
                using (Object fObject = new Object(ShaderType.FragmentShader, fragmentSource))
                {
                    // Create program
                    ProgramName = Gl.CreateProgram();
                    // Attach shaders
                    Gl.AttachShader(ProgramName, vObject.ShaderName);
                    Gl.AttachShader(ProgramName, fObject.ShaderName);
                    // Link program
                    Gl.LinkProgram(ProgramName);

                    // Check linkage status
                    int linked;

                    Gl.GetProgram(ProgramName, ProgramProperty.LinkStatus, out linked);

                    if (linked == 0)
                    {
                        const int logMaxLength = 1024;

                        StringBuilder infolog = new StringBuilder(logMaxLength);
                        int           infologLength;

                        Gl.GetProgramInfoLog(ProgramName, 1024, out infologLength, infolog);

                        throw new InvalidOperationException($"unable to link program: {infolog}");
                    }

                    // Get uniform locations
                    if ((LocationResolution = Gl.GetUniformLocation(ProgramName, "iResolution")) < 0)
                    {
                        throw new InvalidOperationException("no uniform iResolution");
                    }

                    if ((LocationTime = Gl.GetUniformLocation(ProgramName, "iTime")) < 0)
                    {
                        throw new InvalidOperationException("no uniform iTime");
                    }

                    // Get attributes locations
                    if ((LocationPosition = Gl.GetAttribLocation(ProgramName, "a_position")) < 0)
                    {
                        throw new InvalidOperationException("no attribute a_position");
                    }
                }
        }