Exemplo n.º 1
0
        public unsafe Texture
            (GL gl, string name, int width, int height, IntPtr data, bool generateMipmaps = false, bool srgb = false)
        {
            _gl = gl;
            MaxAniso ??= gl.GetFloat(GLEnum.MaxTextureMaxAnisotropy);
            Name           = name;
            Width          = (uint)width;
            Height         = (uint)height;
            InternalFormat = srgb ? Srgb8Alpha8 : GLEnum.Rgba8;
            MipmapLevels   =
                (uint)(generateMipmaps == false ? 1 : (int)Math.Floor(Math.Log(Math.Max(Width, Height), 2)));

            _gl.CreateTexture(TextureTarget.Texture2D, Name, out GlTexture);
            _gl.TextureStorage2D(GlTexture, MipmapLevels, InternalFormat, Width, Height);

            _gl.TextureSubImage2D(GlTexture, 0, 0, 0, Width, Height, PixelFormat.Bgra, PixelType.UnsignedByte,
                                  (void *)data);

            if (generateMipmaps)
            {
                _gl.GenerateTextureMipmap(GlTexture);
            }

            SetWrap(TextureCoordinate.S, TextureWrapMode.Repeat);
            SetWrap(TextureCoordinate.T, TextureWrapMode.Repeat);

            _gl.TextureParameter(GlTexture, TextureParameterName.TextureMaxLevel, MipmapLevels - 1);
        }
Exemplo n.º 2
0
 static void SetFilter(uint id, GLEnum f)
 {
     GL.ActiveTexture((uint)GLEnum.TEXTURE0);
     GL.BindTexture(GLEnum.TEXTURE_2D, id);
     GL.TexParameteri(GLEnum.TEXTURE_2D, GLEnum.TEXTURE_MIN_FILTER, (int)f);
     GL.TexParameteri(GLEnum.TEXTURE_2D, GLEnum.TEXTURE_MAG_FILTER, (int)f);
 }
Exemplo n.º 3
0
 protected void AssignTextureParameters(GLEnum wrapMode, GLEnum filterMode)
 {
     GL.TextureParameter(Handle, TextureParameterName.TextureWrapS, (int)wrapMode);
     GL.TextureParameter(Handle, TextureParameterName.TextureWrapT, (int)wrapMode);
     GL.TextureParameter(Handle, TextureParameterName.TextureMinFilter, (int)filterMode);
     GL.TextureParameter(Handle, TextureParameterName.TextureMagFilter, (int)filterMode);
 }
Exemplo n.º 4
0
            static void UploadBufferData(ref uint id, GLEnum type, ReadOnlySequence <T> data, ref long currentBufferSize)
            {
                if (id == 0)
                {
                    id = GL.GenBuffer();
                }

                GL.BindBuffer(type, id);

                var structSize = Marshal.SizeOf <T>();

                // resize the buffer
                var neededBufferSize = data.Length * structSize;

                if (currentBufferSize < neededBufferSize)
                {
                    currentBufferSize = neededBufferSize;
                    GL.BufferData(type, new IntPtr(structSize * currentBufferSize), IntPtr.Zero, GLEnum.STATIC_DRAW);
                }

                // upload the data
                var offset = 0;

                foreach (var memory in data)
                {
                    using var pinned = memory.Pin();
                    GL.BufferSubData(type, new IntPtr(structSize * offset), new IntPtr(structSize * memory.Length), new IntPtr(pinned.Pointer));
                    offset += memory.Length;
                }

                GL.BindBuffer(type, 0);
            }
Exemplo n.º 5
0
        private void GenerateEnum(IndentedTextWriter writer, GLEnum glEnum, GLFeature feature, HashSet <GLChangeReference> collected)
        {
            bool any = false;

            using (var sb = new StringBuilderTextWriter(new StringBuilder()))
                using (var tempWriter = new IndentedTextWriter(sb))
                {
                    tempWriter.Indent = writer.Indent;
                    tempWriter.WriteLine("enum " + glEnum.Name + " : uint");
                    tempWriter.WriteLine("{");

                    using (tempWriter.Indentation())
                    {
                        foreach (var entry in glEnum.Entries)
                        {
                            var reference = new GLChangeReference("enum", entry.Value.Name);

                            if (!collected.Contains(reference))
                            {
                                continue;
                            }
                            any = true;

                            tempWriter.WriteLine(entry.Value.Name + " = " + entry.Value.Value + ",");
                        }
                    }

                    tempWriter.WriteLine("}");

                    if (any)
                    {
                        writer.WriteLine(sb.StringBuilder.ToString());
                    }
                }
        }
Exemplo n.º 6
0
 public Blend(GLEnum srcRgb, GLEnum dstRgb, GLEnum srcAlpha, GLEnum dstAlpha)
 {
     _srcRgb   = srcRgb;
     _dstRgb   = dstRgb;
     _srcAlpha = srcAlpha;
     _dstAlpha = dstAlpha;
 }
Exemplo n.º 7
0
 private static void OnDebug(GLEnum source, GLEnum type, int id, GLEnum severity, int length, IntPtr message, IntPtr userparam)
 {
     Console.WriteLine
     (
         $"|{severity.ToString().Substring(13)}| {type.ToString().Substring(9)}/{id}: {Marshal.PtrToStringAnsi(message)}"
     );
 }
Exemplo n.º 8
0
        public LayerBuffer(bool staticData)
        {
            index = State.Gl.GenBuffer();

            if (staticData)
            {
                usageHint = GLEnum.StaticDraw;
            }
        }
Exemplo n.º 9
0
        public static void CheckGlError(this GL gl, string title)
        {
            GLEnum error = gl.GetError();

            if (error != GLEnum.NoError)
            {
                Debug.Print($"{title}: {error}");
            }
        }
Exemplo n.º 10
0
        public ColorBuffer(bool staticData)
        {
            _index = State.Gl.GenBuffer();

            if (staticData)
            {
                _usageHint = GLEnum.StaticDraw;
            }
        }
Exemplo n.º 11
0
 public void GetFloat(GLEnum pname, out Vector4 vector)
 {
     unsafe
     {
         fixed(Vector4 *ptr = &vector)
         {
             GetFloat(pname, (float *)ptr);
         }
     }
 }
Exemplo n.º 12
0
 public void GetFloat(GLEnum pname, out Matrix4x4 matrix)
 {
     unsafe
     {
         fixed(Matrix4x4 *ptr = &matrix)
         {
             GetFloat(pname, (float *)ptr);
         }
     }
 }
Exemplo n.º 13
0
        protected BufferObject(State state, bool staticData)
        {
            this.state = state;
            index      = state.Gl.GenBuffer();

            if (staticData)
            {
                usageHint = GLEnum.StaticDraw;
            }
        }
Exemplo n.º 14
0
        public string GetActiveAttrib(uint program, uint index, out int size, out GLEnum type)
        {
            uint length;

            GetProgram(program, GLEnum.ActiveAttributeMaxLength, out var lengthTmp);
            length = (uint)lengthTmp;

            GetActiveAttrib(program, index, (uint)(length == 0 ? 1 : length * 2), out length, out size, out type, out string str);

            return(str.Substring(0, (int)length));
        }
        public unsafe BufferObject(GL gl, Span <TDataType> data, GLEnum bufferType, GLEnum StaticOrDynamic)
        {
            _gl         = gl;
            _bufferType = bufferType;

            _handle = _gl.GenBuffer();
            Bind();
            fixed(void *d = data)
            {
                _gl.BufferData(bufferType, (nuint)(data.Length * sizeof(TDataType)), d, StaticOrDynamic);
            }
        }
Exemplo n.º 16
0
        public void BindTexture(Texture texture, GLEnum attachment = GLEnum.ColorAttachment0, GLEnum target = GLEnum.Texture2D, bool dispose = true)
        {
            Use();

            if (dispose && createdTexture && BoundTexture != null)
            {
                createdTexture = false;
                BoundTexture.Dispose();
            }

            BoundTexture = texture;
            gl.FramebufferTexture2D(GLEnum.Framebuffer, attachment, target, texture != null ? texture.ID : 0, 0);
        }
Exemplo n.º 17
0
        public void LoadPart(IGLSpecification context, XElement rootNode)
        {
            const string UNKNOWN_GROUP_NAME = "UNKNOWN_GROUP";
            var          enumTypes          = context.Enums;

            var unknownEnumGroup = new GLEnum(UNKNOWN_GROUP_NAME, null);

            enumTypes.Add(UNKNOWN_GROUP_NAME, unknownEnumGroup);

            foreach (var e in rootNode.Elements("enums"))
            {
                var vendorName   = e.Attribute("vendor")?.Value;
                var parentGroups = e.Attribute("group");
                foreach (var enumEntry in e.Elements("enum"))
                {
                    var enumEntryName               = enumEntry.Attribute("name")?.Value;
                    var enumEntryValue              = enumEntry.Attribute("value")?.Value;
                    var parentGroupValue            = parentGroups?.Value;
                    var enumGroupValue              = enumEntry.Attribute("group")?.Value;
                    IEnumerable <string> enumGroups = (enumGroupValue)?.Split(',');
                    if (enumGroups != null)
                    {
                        if (parentGroupValue != null && !enumGroups.Contains(parentGroupValue))
                        {
                            enumGroups = enumGroups.Append(parentGroupValue);
                        }
                    }
                    else
                    {
                        enumGroups = new[] { parentGroupValue ?? UNKNOWN_GROUP_NAME };
                    }

                    if (enumEntryName == null || enumEntryValue == null)
                    {
                        throw new ArgumentNullException();
                    }

                    foreach (var enumGroup in enumGroups)
                    {
                        if (!enumTypes.TryGetValue(enumGroup, out var enumType))
                        {
                            enumType = new GLEnum(enumGroup, vendorName);
                            enumTypes.Add(enumGroup, enumType);
                        }

                        enumType.AddEntry(enumEntryName, ConvertToUInt64(enumEntryValue));
                    }
                }
            }
        }
Exemplo n.º 18
0
        internal void CheckError(string str)
        {
            if (!Debug)
            {
                return;
            }

            GLEnum err = Gl.GetError();

            if (err != GLEnum.NoError)
            {
                Console.Error.WriteLine("Error " + err + " after" + Environment.NewLine + str);
                return;
            }
        }
Exemplo n.º 19
0
        private static UniformType ToFosterType(GLEnum type)
        {
            return(type switch
            {
                GLEnum.INT => UniformType.Int,
                GLEnum.FLOAT => UniformType.Float,
                GLEnum.FLOAT_VEC2 => UniformType.Float2,
                GLEnum.FLOAT_VEC3 => UniformType.Float3,
                GLEnum.FLOAT_VEC4 => UniformType.Float4,
                GLEnum.FLOAT_MAT3x2 => UniformType.Matrix3x2,
                GLEnum.FLOAT_MAT4 => UniformType.Matrix4x4,
                GLEnum.SAMPLER_2D => UniformType.Sampler,

                _ => throw new InvalidOperationException("Unknown Enum Type"),
            });
Exemplo n.º 20
0
        /// <summary>
        ///     Manually query OpenGL for errors.
        /// </summary>
        /// <remarks>
        ///     <p>
        ///         This function is very simple, and offers little-to-no debug information.
        ///     </p>
        ///     <p>
        ///         Thus, try to rely on the default debug context exception handling. This should
        ///         only be used when that functionality is insufficient or failing.
        ///     </p>
        /// </remarks>
        /// <param name="checkForErrors"></param>
        /// <exception cref="OpenGLException"></exception>
        public static void CheckForErrorsAndThrow(bool checkForErrors)
        {
            if (!checkForErrors)
            {
                return;
            }

            GLEnum glError = Instance.GL.GetError();

            switch (glError)
            {
            case GLEnum.NoError: break;

            default: throw new OpenGLException(glError);
            }
        }
Exemplo n.º 21
0
        public unsafe void StoreData <T>(T[] data, uint slot, int dimensions, GLEnum dataType)
            where T : unmanaged
        {
            Bind();
            uint vboID = _gl.GenBuffer();

            _vbos.Add(vboID);
            _gl.BindBuffer(BufferTargetARB.ArrayBuffer, vboID);
            fixed(T *d = data)
            {
                _gl.BufferData(BufferTargetARB.ArrayBuffer, (uint)(sizeof(T) * data.Length), d, BufferUsageARB.StaticDraw);
            }

            _gl.VertexAttribPointer(slot, dimensions, dataType, false, (uint)(dimensions * sizeof(T)), null);
            _gl.BindBuffer(BufferTargetARB.ArrayBuffer, 0);
            Unbind();
        }
Exemplo n.º 22
0
        private unsafe void UploadBuffer <T>(ref uint id, GLEnum type, ReadOnlySequence <T> data, ref long currentBufferSize)
        {
            if (graphics.MainThreadId != Thread.CurrentThread.ManagedThreadId)
            {
                lock (graphics.BackgroundContext)
                {
                    graphics.System.SetCurrentGLContext(graphics.BackgroundContext);

                    UploadBufferData(ref id, type, data, ref currentBufferSize);
                    GL.Flush();

                    graphics.System.SetCurrentGLContext(null);
                }
            }
            else
            {
                UploadBufferData(ref id, type, data, ref currentBufferSize);
            }
Exemplo n.º 23
0
        protected override void SetFilter(TextureFilter filter)
        {
            GLEnum f = (filter == TextureFilter.Nearest ? GLEnum.NEAREST : GLEnum.LINEAR);

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

                    SetFilter(ID, f);
                    GL.Flush();

                    graphics.System.SetCurrentGLContext(graphics.BackgroundContext);
                }
            }
            else
            {
                SetFilter(ID, f);
            }
Exemplo n.º 24
0
        private void PrintGLError(GLEnum source, GLEnum type, int id, GLEnum severity, int length, nint message, nint userparam)
        {
            var buf = new byte[length];

            Marshal.Copy(message, buf, 0, buf.Length);

            var messageString = Encoding.UTF8.GetString(buf);

            var logLevel = severity switch
            {
                GLEnum.DebugSeverityLow => LogLevel.Warning,
                GLEnum.DebugSeverityMedium => LogLevel.Error,
                GLEnum.DebugSeverityHigh => LogLevel.Fatal,
                _ => LogLevel.Trace
            };

            if (logLevel != LogLevel.Trace)
            {
                App.Logger.Log(messageString, logLevel);
            }
        }
Exemplo n.º 25
0
        public Blend(CompositeOperationState compositeOperation, OpenGLRenderer renderer)
        {
            GLEnum srcRgb   = ConvertBlend(compositeOperation.SrcRgb);
            GLEnum dstRgb   = ConvertBlend(compositeOperation.DstRgb);
            GLEnum srcAlpha = ConvertBlend(compositeOperation.SrcAlpha);
            GLEnum dstAlpha = ConvertBlend(compositeOperation.DstAlpha);

            if (srcRgb == GLEnum.InvalidEnum || dstRgb == GLEnum.InvalidEnum ||
                srcAlpha == GLEnum.InvalidEnum || dstAlpha == GLEnum.InvalidEnum)
            {
                srcRgb   = GLEnum.One;
                dstRgb   = GLEnum.OneMinusSrcAlpha;
                srcAlpha = GLEnum.One;
                dstAlpha = GLEnum.OneMinusDstAlpha;
            }
            _srcRgb   = srcRgb;
            _dstRgb   = dstRgb;
            _srcAlpha = srcAlpha;
            _dstAlpha = dstAlpha;

            _renderer = renderer;
        }
Exemplo n.º 26
0
        private void GenerateSpecialNumbers(IndentedTextWriter writer, GLEnum glEnum, GLFeature feature, HashSet <GLChangeReference> collected)
        {
            bool any = false;

            using (var sb = new StringBuilderTextWriter(new StringBuilder()))
                using (var tempWriter = new IndentedTextWriter(sb))
                {
                    tempWriter.Indent = writer.Indent;
                    tempWriter.WriteLine("public static class " + glEnum.Name + "");
                    tempWriter.WriteLine("{");

                    using (tempWriter.Indentation())
                    {
                        foreach (var entry in glEnum.Entries)
                        {
                            var reference = new GLChangeReference("enum", entry.Value.Name);

                            if (!collected.Contains(reference))
                            {
                                continue;
                            }
                            any = true;
                            string dataType = entry.Value.Value <= byte.MaxValue ? "byte" :
                                              entry.Value.Value <= ushort.MaxValue ? "ushort" :
                                              entry.Value.Value <= uint.MaxValue ? "uint" : "ulong";
                            tempWriter.WriteLine($"public static {dataType} {entry.Value.Name} = {entry.Value.Value};");
                        }
                    }

                    tempWriter.WriteLine("}");

                    if (any)
                    {
                        writer.WriteLine(sb.StringBuilder.ToString());
                    }
                }
        }
Exemplo n.º 27
0
        protected override void Init(Texture texture)
        {
            this.texture = texture;

            glInternalFormat = texture.Format switch
            {
                TextureFormat.Red => GLEnum.RED,
                TextureFormat.RG => GLEnum.RG,
                TextureFormat.RGB => GLEnum.RGB,
                TextureFormat.Color => GLEnum.RGBA,
                TextureFormat.DepthStencil => GLEnum.DEPTH24_STENCIL8,
                _ => throw new Exception("Invalid Texture Format"),
            };

            glFormat = texture.Format switch
            {
                TextureFormat.Red => GLEnum.RED,
                TextureFormat.RG => GLEnum.RG,
                TextureFormat.RGB => GLEnum.RGB,
                TextureFormat.Color => GLEnum.RGBA,
                TextureFormat.DepthStencil => GLEnum.DEPTH_STENCIL,
                _ => throw new Exception("Invalid Texture Format"),
            };

            glType = texture.Format switch
            {
                TextureFormat.Red => GLEnum.UNSIGNED_BYTE,
                TextureFormat.RG => GLEnum.UNSIGNED_BYTE,
                TextureFormat.RGB => GLEnum.UNSIGNED_BYTE,
                TextureFormat.Color => GLEnum.UNSIGNED_BYTE,
                TextureFormat.DepthStencil => GLEnum.UNSIGNED_INT_24_8,
                _ => throw new Exception("Invalid Texture Format"),
            };

            Initialize();
        }
Exemplo n.º 28
0
 private static void DebugOutputCallback(GLEnum source, GLEnum type, int id, GLEnum severity, int length, nint messagePtr, nint userParamPtr)
 {
Exemplo n.º 29
0
 public unsafe void DrawElements(GLEnum mode, uint count, GLEnum type, int offset)
 {
     DrawElements((GLEnum)mode, count, type, (void *)(offset));
 }
Exemplo n.º 30
0
 public unsafe void VertexAttribPointer(uint index, int size, GLEnum type, bool normalized, uint stride, int offset)
 {
     VertexAttribPointer(index, size, type, normalized, stride, (void *)offset);
 }