Example #1
0
        public Sun(string dataBaseName, PlanetParameters param, Planet parent, MeshVBOs vbos, Texture t, ShaderProgram shader, ShaderProgram lineShader)
            : base(dataBaseName, param, parent, vbos, t, shader, lineShader)
        {
            bufferVerts = new VBO<float>(new float[] { -1, 1, 0, 1, 1, 0, 1, -1, 0, -1, -1, 0 }, BufferTarget.ArrayBuffer, VBO<float>.PointerType.vertex);
            bufferElems = new VBO<ushort>(new ushort[] { 0, 1, 2, 3 }, BufferTarget.ElementArrayBuffer, VBO<ushort>.PointerType.element);

            squareUvs = new VBO<float>(new float[] { 0, 1, 1, 1, 1, 0, 0, 0 }, BufferTarget.ArrayBuffer, VBO<float>.PointerType.texCoord);
            squareVerts = new VBO<float>(new float[] { -2, 2, 0, 2f, 2f, 0, 2f, -2f, 0, -2f, -2f, 0 }, BufferTarget.ArrayBuffer, VBO<float>.PointerType.vertex);
            squareElems = new VBO<ushort>(new ushort[] { 0, 1, 2, 3 }, BufferTarget.ElementArrayBuffer, VBO<ushort>.PointerType.element);

            this.coronaShader = new ShaderProgram(File.ReadAllText("content/shaders/coronaShader.vert"), File.ReadAllText("content/shaders/coronaShader.frag"), "coronaShader");
            Console.WriteLine(coronaShader.ProgramInfoLog);
            coronaShader.setUniform("proj", Form1.projectionMatrix);
            coronaShader.setUniform("model", Matrix4.Identity);

            this.billboardShader = new ShaderProgram(File.ReadAllText("content/shaders/billboardShader.vert"), File.ReadAllText("content/shaders/billboardShader.frag"), "billboardShader");
            Console.WriteLine(billboardShader.ProgramInfoLog);
            billboardShader.setUniform("proj", Form1.projectionMatrix);
            billboardShader.setUniform("model", Matrix4.Identity);

            frameBufferTime = 0;
            bufferResolution = new Vector2(1024, 1024);

            bufferTexture = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2D, bufferTexture);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, (int)bufferResolution.X, (int)bufferResolution.Y, 0, PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);

            frameBuffer = GL.GenFramebuffer();
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, frameBuffer);
            GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, bufferTexture, 0);
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0); // make sure to set the framebuffer back to the default, or else bugs,
            //bugs that take two hours to debug
        }
        protected override void DoInitialize()
        {
            {
                // particleSimulator-fountain.comp is also OK.
                var shaderCode = new ShaderCode(File.ReadAllText(@"shaders\ParticleSimulatorRenderer\particleSimulator.comp"), ShaderType.ComputeShader);
                this.computeProgram = shaderCode.CreateProgram();
            }
            {
                Buffer buffer = this.positionBuffer;
                Texture texture = buffer.DumpBufferTexture(OpenGL.GL_RGBA32F, autoDispose: false);
                texture.Initialize();
                this.positionTexture = texture;
            }
            {
                Buffer buffer = this.velocityBuffer;
                Texture texture = buffer.DumpBufferTexture(OpenGL.GL_RGBA32F, autoDispose: false);
                texture.Initialize();
                this.velocityTexture = texture;
            }
            {
                const int length = 64;
                UniformBuffer buffer = UniformBuffer.Create(typeof(vec4), length, BufferUsage.DynamicCopy);
                buffer.Bind();
                OpenGL.BindBufferBase((BindBufferBaseTarget)BufferTarget.UniformBuffer, 0, buffer.BufferId);
                buffer.Unbind();
                this.attractorBuffer = buffer;

                OpenGL.CheckError();
            }
        }
Example #3
0
        public Viewport(Resolution resolution, Vector2? position = null, Camera camera = null)
        {
            this.Resolution = resolution;
            this.Position = position ?? Vector2.Zero;

            var pos = new Vector3[] {
                new Vector3 (this.Resolution.Width, 0, 0),
                new Vector3 (this.Resolution.Width, this.Resolution.Height, 0),
                new Vector3 (0, this.Resolution.Height, 0),
                new Vector3 (0, 0, 0),
            };

            var tex = new Vector2[] {
                new Vector2 (1.0f, 0.0f),
                new Vector2 (1.0f, 1.0f),
                new Vector2 (0.0f, 1.0f),
                new Vector2 (0.0f, 0.0f),
            };

            ViewportShader = Game.ContentManager.Load<ShaderProgram> ("viewport");

            this.ViewportTarget = new Model (new Geometry (BeginMode.Quads)
                                                    .AddBuffer ("v_pos", new GLBuffer<Vector3> (GLBufferSettings.StaticDraw3FloatArray, pos))
                                                    .AddBuffer ("v_tex", new GLBuffer<Vector2> (GLBufferSettings.StaticDraw2FloatArray, tex)));

            Matrix = Matrix4.CreateOrthographicOffCenter (0, this.Resolution.Width, 0, this.Resolution.Height, 0, 16);
        }
Example #4
0
        public Grid(Renderer renderer, ShaderProgram shader)
        {
            // Render state for grid
            RenderState = renderer.RenderFactory.CreateRenderState();
            RenderState.DepthTest = true;
            RenderState.DepthMask = true;
            this.Shader = shader;
            // Define the format of the control point to render the line
            VertexDeclaration vd = new VertexDeclaration();
            vd.AddField(VertexFieldDataType.FVector3, VertexFieldSemantic.Position);
            // and create a vertex buffer for storing this kind of data
            this.VertexBuffer = renderer.RenderFactory.CreateVertexBuffer(vd);
            // Draw the primitive as lines
            this.DrawOperation = DrawOperation.Lines;
            this.RenderGroup = RenderQueueGroupId.Geometries;

            List<FVector3> lines = new List<FVector3>();
            for (int i = -10; i <= 10; i++)
            {
                // Draw - line
                lines.Add(new FVector3(i, 0, -10));
                lines.Add(new FVector3(i,0, 10));


                // Draw | line
                lines.Add(new FVector3(-10, 0, i));
                lines.Add(new FVector3(10, 0, i));
            }
            // Put it to vertex buffer
            VertexBuffer.LoadData(lines.ToArray());
        }
Example #5
0
 /// <summary>
 /// Set uniform's value to GPU.(And maybe alsoe reset <see cref="Updated"/> property.)
 /// </summary>
 /// <param name="program"></param>
 public void SetUniform(ShaderProgram program)
 {
     if (this.Updated)
     {
         this.DoSetUniform(program);
     }
 }
Example #6
0
 /// シェーダのセット
 public static void Init( string vshName, string fshName )
 {
     // vertex color shader
     debShader = new ShaderProgram( vshName, fshName );
     debShader.SetAttributeBinding( 0, "a_Position" );
     debUIdWVP = debShader.FindUniform( "WorldViewProj" );
 }
Example #7
0
        public DebugString(GraphicsContext graphics, Texture2D texture, int charaWidth, int charaHeight)
        {
            if(shaderProgram == null)
            {
                shaderProgram=CreateSimpleSpriteShader();
            }

            this.graphics = graphics;

            this.texture = texture;

            this.charaWidth = charaWidth;
            this.charaHeight = charaHeight;

            charaPositions = new float[maxNumOfCharactor * 4 * 3];
            charaTexcoords = new float[maxNumOfCharactor * 4 * 2];
            charaColors = new float[maxNumOfCharactor * 4 * 4];
            charaIndices = new ushort[maxNumOfCharactor * indexSize];

            vertices = new VertexBuffer(maxNumOfCharactor * 4, maxNumOfCharactor * indexSize,
                VertexFormat.Float3, VertexFormat.Float2, VertexFormat.Float4);

            PixelScreenPosition = new Vector3(0.0f, 0.0f, 0.0f);

            ImageRect rectPixelScreen = graphics.GetViewport();

            //@j ピクセルの座標系をスクリーンの座標系に変換する行列。
            //@e Line to convert a pixel coordinate system into a screen coordinate system.
            unitScreenMatrix = new Matrix4(
                 2.0f/rectPixelScreen.Width,	0.0f,	0.0f, 0.0f,
                 0.0f, -2.0f/rectPixelScreen.Height,	0.0f, 0.0f,
                 0.0f,	0.0f, 1.0f, 0.0f,
                -1.0f, 1.0f, 0.0f, 1.0f
            );
        }
        public static void init()
        {
            if (shaderUniversal == null){
                shaderUniversal = new ShaderProgram("/Application/shaders/Universal.cgx");

                shaderUniversal.SetAttributeBinding(0, "a_Position");
                shaderUniversal.SetAttributeBinding(1, "a_VertexColor");
                shaderUniversal.SetAttributeBinding(2, "a_TexCoord");

                shaderUniversal.SetUniformBinding(0, "u_SceneMatrix");
                shaderUniversal.SetUniformBinding(1, "u_ScreenMatrix");
                shaderUniversal.SetUniformBinding(2, "u_Alpha");

                texture = new Texture2D("/Application/assets/texturepack/rymdkapsel-hd.png", false);
                texture.SetFilter(TextureFilterMode.Disabled);
                texture.SetWrap(TextureWrapMode.ClampToEdge);
                texture.SetMaxAnisotropy(0);
            }

            if (shaderColored == null){
                shaderColored = new ShaderProgram("/Application/shaders/Colored.cgx");

                shaderColored.SetAttributeBinding(0, "a_Position");
                shaderColored.SetAttributeBinding(1, "a_VertexColor");

                shaderColored.SetUniformBinding(0, "u_SceneMatrix");
                shaderColored.SetUniformBinding(1, "u_ScreenMatrix");
                shaderColored.SetUniformBinding(2, "u_Alpha");
            }
        }
Example #9
0
 /// シェーダの解放
 public static void Term()
 {
     if( debShader != null ){
     debShader.Dispose();
     }
     debShader	= null;
 }
Example #10
0
        public PatternGrid(GraphicsContext graphics, Texture2D texture, Vector2 position, Vector2 size)
        {
            if(shaderProgram == null)
            {
                //shaderProgram=CreateSimpleSpriteShader();
                shaderProgram = new ShaderProgram("/Application/shaders/Sprite.cgx");
                shaderProgram.SetUniformBinding(0, "u_WorldMatrix");
            }

            //if (texture == null)
            //{
            //	throw new Exception("ERROR: texture is null.");
            //}

            this.graphics = graphics;
            //this.texture = texture;
            this.texture = new Texture2D("/Application/resources/textures512.png", false);
            this.width = size.X;
            this.height = size.Y;
            this.origin = position;

            //@e                                                Vertex coordinate,               Texture coordinate,     Vertex color
            //vertexBuffer = new VertexBuffer(4, indexSize, VertexFormat.Float3, VertexFormat.Float2, VertexFormat.Float4);
            vertexBuffer = new VertexBuffer(NUMVERTICES, VertexFormat.Float3, VertexFormat.Float2, VertexFormat.Float4);
        }
        internal void SetConstantBuffers(GraphicsDevice device, ShaderProgram shaderProgram)
#endif
        {
            // If there are no constant buffers then skip it.
            if (_valid == 0)
                return;

            var valid = _valid;

            for (var i = 0; i < _buffers.Length; i++)
            {
                var buffer = _buffers[i];
                if (buffer != null && !buffer.IsDisposed)
                {
#if DIRECTX
                    buffer.PlatformApply(device, _stage, i);
#elif OPENGL || WEB
                    buffer.PlatformApply(device, shaderProgram);
#endif
                }

                // Early out if this is the last one.
                valid &= ~(1 << i);
                if (valid == 0)
                    return;
            }
        }
Example #12
0
        /// <summary>
        /// Initialises the scene.
        /// </summary>
        /// <param name="gl">The OpenGL instance.</param>
        /// <param name="width">The width of the screen.</param>
        /// <param name="height">The height of the screen.</param>
        public void Initialise(OpenGL gl, float width, float height)
        {
            //  Set a blue clear colour.
            gl.ClearColor(0.4f, 0.6f, 0.9f, 0.0f);

            //  Create the shader program.
            var vertexShaderSource = ManifestResourceLoader.LoadTextFile("Shader.vert");
            var fragmentShaderSource = ManifestResourceLoader.LoadTextFile("Shader.frag");
            shaderProgram = new ShaderProgram();
            shaderProgram.Create(gl, vertexShaderSource, fragmentShaderSource, null);
            shaderProgram.BindAttributeLocation(gl, attributeIndexPosition, "in_Position");
            shaderProgram.BindAttributeLocation(gl, attributeIndexColour, "in_Color");
            shaderProgram.AssertValid(gl);

            //  Create a perspective projection matrix.
            const float rads = (60.0f / 360.0f) * (float)Math.PI * 2.0f;
            projectionMatrix = glm.perspective(rads, width / height, 0.1f, 100.0f);

            //  Create a view matrix to move us back a bit.
            viewMatrix = glm.translate(new mat4(1.0f), new vec3(0.0f, 0.0f, -5.0f));

            //  Create a model matrix to make the model a little bigger.
            modelMatrix = glm.scale(new mat4(1.0f), new vec3(2.5f));

            //  Now create the geometry for the square.
            CreateVerticesForSquare(gl);
        }
Example #13
0
        /// <summary>コンストラクタ。</summary>
        public SimpleSprite(GraphicsContext graphics, Texture2D texture)
        {
            if(shaderProgram == null)
            {
                shaderProgram=CreateSimpleSpriteShader();
            }

            if (texture == null)
            {
                throw new Exception("ERROR: texture is null.");
            }

            this.graphics = graphics;
            this.texture = texture;
            this.width = texture.Width;
            this.height = texture.Height;

            indices = new ushort[indexSize];
            indices[0] = 0;
            indices[1] = 1;
            indices[2] = 2;
            indices[3] = 3;

            //@e                                                Vertex coordinate,               Texture coordinate,     Vertex color
            //@j                                                頂点座標,                テクスチャ座標,     頂点色
            vertexBuffer = new VertexBuffer(4, indexSize, VertexFormat.Float3, VertexFormat.Float2, VertexFormat.Float4);
        }
Example #14
0
		public static void Initialize ()
		{
			// Set up the graphics system
			graphics = new GraphicsContext ();
#if BUILD_FOR_PSV
			program = new ShaderProgram("/Application/shaders/Texture.cgx");
#else
			program = new ShaderProgram("/Application/shaders/Texture_sim.cgx");
#endif
			program.SetUniformBinding(0, "WorldViewProj");
			program.SetAttributeBinding(0, "a_Position");
			program.SetAttributeBinding(1, "a_TexCoord");
			vertices = new VertexBuffer(4, VertexFormat.Float3, VertexFormat.Float2);

			float[] positions = {
				-1.0f, 1.0f, 0.0f,
				-1.0f, -1.0f, 0.0f,
				1.0f, 1.0f, 0.0f,
				1.0f, -1.0f, 0.0f,
			};
			float[] texcoords = {
				0.0f, 0.0f,
				0.0f, 1.0f,
				1.0f, 0.0f,
				1.0f, 1.0f,
			};
			vertices.SetVertices(0, positions);
			vertices.SetVertices(1, texcoords);
			texture = new Texture2D(256, 224, false, PixelFormat.Rgb565);
			
			SampleDraw.Init(graphics);
			
		}
Example #15
0
        public virtual void Load(int width, int height)
        {
            Width = width;
            Height = height;
            _page = new Texture();
            GUIShader = Assets.Fetch<ShaderProgram>("GUI");
            GUIShader.AddUniform("scale");
            VBO = new VBO<VertexPositionNormalTexture>();
            VAO = new VAO<VertexPositionNormalTexture>();
            VBO.Buffer(new[]{
                new VertexPositionNormalTexture{Position = new Vector3(0, Height, 0f),Normal = Vector3.UnitZ,TexCoord = new Vector2(0, Height)},
                new VertexPositionNormalTexture{Position = new Vector3(Width, Height, 0f),Normal = Vector3.UnitZ,TexCoord = new Vector2(Width, Height)},
                new VertexPositionNormalTexture{Position = new Vector3(Width, 0, 0f),Normal = Vector3.UnitZ,TexCoord = new Vector2(Width, 0)},
                new VertexPositionNormalTexture{Position = new Vector3(0, 0, 0),Normal = Vector3.UnitZ,TexCoord = new Vector2(0,0)}
            });
            VAO.Setup(GUIShader, VBO);
            _webView = WebCore.CreateWebView(Width, Height);
            WebCore.BaseDirectory = Path.Combine(Directory.GetCurrentDirectory(), "GUI");
            _webView.FlushAlpha = false;
            _webView.IsTransparent = true;
            _webView.CreateObject("console");
            _webView.SetObjectCallback("console", "log", (sender, e) => Bus.Add(new DebugMessage(Timer.LastTickTime, e.Arguments[0].ToString())));

            _webView.CreateObject("GUI");
            _webView.CreateObject("Bus");

            _webView.LoadFile("index.htm");
        }
        protected override void DoInitialize()
        {
            {
                // Initialize our compute program
                var shaderCode = new ShaderCode(File.ReadAllText(@"shaders\SimpleComputeRenderer\compute.comp"), ShaderType.ComputeShader);
                this.computeProgram = shaderCode.CreateProgram();
            }
            {
                // Initialize our resetProgram
                var shaderCode = new ShaderCode(File.ReadAllText(@"shaders\SimpleComputeRenderer\computeReset.comp"), ShaderType.ComputeShader);
                this.computeResetProgram = shaderCode.CreateProgram();
            }
            {
                // This is the texture that the compute program will write into
                var texture = new Texture(TextureTarget.Texture2D,
                    new TexStorage2DImageFiller(8, OpenGL.GL_RGBA32F, 256, 256),
                    new NullSampler());
                texture.Initialize();
                this.outputImage = texture;
            }
            {
                this.GroupX = 1;
                this.GroupY = 1;
                this.GroupZ = 1;
            }
            base.DoInitialize();

            this.SetUniform("output_image", this.outputImage);
        }
Example #17
0
        public Sprite(GraphicsContext graphics, Texture2D texture)
        {
            if(shaderProgram == null)
            {
                shaderProgram = new ShaderProgram("/Application/shaders/Sprite.cgx");
                shaderProgram.SetUniformBinding(0, "u_WorldMatrix");
            }

            if (texture == null)
            {
                throw new Exception("ERROR: texture is null.");
            }

            this.graphics = graphics;
            this.texture = texture;
            this.width = texture.Width;
            this.height = texture.Height;

            indices = new ushort[indexSize];
            indices[0] = 0;
            indices[1] = 1;
            indices[2] = 2;
            indices[3] = 3;

            vertexBuffer = new VertexBuffer(4, indexSize, VertexFormat.Float3,
                                            VertexFormat.Float2, VertexFormat.Float4);
        }
Example #18
0
        public Planet(string dataBaseName, PlanetParameters param, Planet parent, MeshVBOs vbos, Texture t, ShaderProgram shader, ShaderProgram lineShader)
            : base(vbos, t, shader)
        {
            this.parent = parent;
            this.lineShader = lineShader;
            this.RevolutionOrientation = -1;
            this.AxisTilt = Matrix4.Identity;
            this.DrawAxisTilt = true;

            this.ScenicDistance = param.DFSScenic[dataBaseName];
            this.HoursPerRotation = param.RotationPeriod[dataBaseName];
            this.AxisTilt = Matrix4.CreateFromAxisAngle(new Vector3(0, 0, -1), (float)MathHelper.DegreesToRadians(param.AxialTilt[dataBaseName]));
            this.RealisticRadius = param.RadiusRealistic[dataBaseName];
            this.ScenicRadius = param.RadiusScenic[dataBaseName];
            this.Scale = (float)ScenicRadius;
            this.OrbitalPeriod = param.OrbitalPeriod[dataBaseName];
            this.inclinationAngle = param.InclinationAngle[dataBaseName];
            this.longitudeAscendingNode = param.LongitudeAscendingNode[dataBaseName];
            this.longitudePerihelion = param.LongitudePerihelion[dataBaseName];
            this.eccentricity = param.Eccentricity[dataBaseName];
            this.longitudeAscendingNodeRadians = MathHelper.DegreesToRadians(longitudeAscendingNode);
            this.longitudePerihelionRadians = MathHelper.DegreesToRadians(longitudePerihelion);
            this.inclinationAngleRadians = MathHelper.DegreesToRadians(inclinationAngle);
            this.newRadius = 0;
            this.PeriodAngle = longitudePerihelionRadians;
            this.eccentricAnomaly = 0;
            this.createTransform();
            if (parent != null)
                this.Orbit = new Orbit(this, parent.Position, this.ScenicDistance, 360, lineShader, this.inclinationAngle, this.longitudeAscendingNode, this.longitudePerihelion, this.eccentricity);
            float[] axisVerts = { 0, -2, 0, 0, 2, 0 };
            this.axisLine = new VBO<float>(axisVerts, BufferTarget.ArrayBuffer, VBO<float>.PointerType.vertex);
        }
Example #19
0
        /// コンストラクタ
        public TextureRenderer()
        {
            shaderTexture = new ShaderProgram( "/Application/shaders/Texture.cgx" );
            shaderTexture.SetAttributeBinding( 0, "a_Position" );
            shaderTexture.SetAttributeBinding( 1, "a_TexCoord" );
            idWVP = shaderTexture.FindUniform( "WorldViewProj" );
            shaderCurrent = shaderTexture;

            vertices = new VertexBuffer( 4, VertexFormat.Float3, VertexFormat.Float2 );

            float[] positions = {
            0.0f, 0.0f, 0.0f,
            0.0f, -1.0f, 0.0f,
            1.0f, 0.0f, 0.0f,
            1.0f, -1.0f, 0.0f,
            };
            float[] texcoords = {
            0.0f, 1.0f,
            0.0f, 0.0f,
            1.0f, 1.0f,
            1.0f, 0.0f,
            };

            vertices.SetVertices( 0, positions );
            vertices.SetVertices( 1, texcoords );
        }
Example #20
0
        //@e Initialization of shader program
        //@j シェーダープログラムの初期化。
        public static ShaderProgram CreateLineShader()
        {
            Byte[] dataBuffer=Utility.ReadEmbeddedFile("TutoLib.shaders.Line.cgx");
            ShaderProgram shaderProgram = new ShaderProgram(dataBuffer);
            shaderProgram.SetUniformBinding(0, "u_WorldMatrix");

            return shaderProgram;
        }
        protected override void DoInitialize()
        {
            var shaderCode = new ShaderCode(File.ReadAllText(
            @"shaders\ImageProcessingRenderer\ImageProcessing.comp"), ShaderType.ComputeShader);
            ShaderProgram computeProgram = shaderCode.CreateProgram();

            this.computeProgram = computeProgram;
        }
Example #22
0
        protected void InitializeShader(out ShaderProgram shaderProgram)
        {
            var vertexShaderSource = ManifestResourceLoader.LoadTextFile(@"Renderers.Cloud.vert");
            var fragmentShaderSource = ManifestResourceLoader.LoadTextFile(@"Renderers.Cloud.frag");

            shaderProgram = new ShaderProgram();
            shaderProgram.Create(vertexShaderSource, fragmentShaderSource, null);
        }
Example #23
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="graphics">Handle to the GraphicsContext.</param>
 public SolidColorBrush(GraphicsContext graphics)
     : base(graphics)
 {
     this.shader = typeof(SolidColorBrush).Assembly.LoadShaderProgram(
         graphics,
         "Samurai.Graphics.Canvas2D.BasicCanvasShader.vert",
         "Samurai.Graphics.Canvas2D.SolidColorBrush.frag");
 }
Example #24
0
        public Orbit(Planet parent, Vector3 center, double radius, int sides, ShaderProgram shader, double ia, double lan, double lp, double ecc)
        {
            this.eccentricAnomaly = 0;
            this.shader = shader;
            this.parent = parent;
            this.Positon = center;
            this.Radius = (float)radius;
            this.Sides = sides;

            this.inclinationAngleRadians = MathHelper.DegreesToRadians(ia);
            this.longitudeAscendingNodeRadians = MathHelper.DegreesToRadians(lan);
            this.longitudePerihelionRadians = MathHelper.DegreesToRadians(lp);
            this.eccentricity = ecc;

            float step = MathHelper.DegreesToRadians(360f / sides);

            List<float> verts = new List<float>();
            List<float> angles = new List<float>();
            List<ushort> elements = new List<ushort>();

            float alpha = (float)longitudePerihelionRadians;
            ushort count = 0;
            while (alpha < Math.PI * 2f + longitudePerihelionRadians)
            {
                if (alpha < Math.PI + longitudePerihelionRadians)
                    this.eccentricAnomaly += step;
                if (alpha > Math.PI + longitudePerihelionRadians)
                    this.eccentricAnomaly -= step;
                this.newRadius = (float)((radius / (1 - this.eccentricity)) * (1 - (this.eccentricity * Math.Cos(this.eccentricAnomaly))));
                //verts.Add((float)Math.Cos(alpha) * Radius + center.X);
                //verts.Add(0f + center.Y);
                //verts.Add((float)Math.Sin(alpha) * Radius + center.Z);
                //verts.Add(Radius * ((float)Math.Cos(alpha + longitudeAscendingNodeRadians) - (float)Math.Sin(alpha + longitudeAscendingNodeRadians) * (float)Math.Cos(inclinationAngleRadians)) + center.Z);
                //verts.Add(Radius * ((float)Math.Sin(alpha + longitudeAscendingNodeRadians) * (float)Math.Sin(inclinationAngleRadians)) + center.Y);
                //verts.Add(Radius * ((float)Math.Sin(alpha + longitudeAscendingNodeRadians) + (float)Math.Cos(alpha + longitudeAscendingNodeRadians) * (float)Math.Cos(inclinationAngleRadians)) + center.X);

                //verts.Add(newRadius * ((float)Math.Cos(alpha) * (float)Math.Cos(longitudeAscendingNodeRadians) - (float)Math.Sin(longitudeAscendingNodeRadians) * (float)Math.Sin(alpha) * (float)Math.Sin(inclinationAngleRadians) ) + center.X);
                //verts.Add(newRadius * ((float)Math.Sin(alpha) * (float)Math.Sin(inclinationAngleRadians)) + center.Y);
                //verts.Add(newRadius * ((float)Math.Sin(alpha) * (float)Math.Cos(longitudeAscendingNodeRadians) + (float)Math.Cos(longitudeAscendingNodeRadians) * (float)Math.Sin(alpha) * (float)Math.Cos(inclinationAngleRadians)) + center.Z);

                verts.Add(newRadius * (float)Math.Cos(alpha) + center.X);
                verts.Add(newRadius * (float)inclinationAngleRadians * (float)Math.Sin(alpha - longitudeAscendingNodeRadians) + center.Y);
                verts.Add(newRadius * (float)Math.Sin(alpha) + center.Z);

                elements.Add(count);
                angles.Add(alpha);
                alpha += step;
                count++;
            }

            float[] vertsf = verts.ToArray();
            float[] anglesf = angles.ToArray();
            ushort[] elementsf = elements.ToArray();

            this.vertsBuffer = new VBO<float>(vertsf, BufferTarget.ArrayBuffer, VBO<float>.PointerType.vertex);
            this.anglesBuffer = new VBO<float>(anglesf, BufferTarget.ArrayBuffer, VBO<float>.PointerType.color);
            this.elementsBuffer = new VBO<ushort>(elementsf, BufferTarget.ElementArrayBuffer, VBO<ushort>.PointerType.element);
        }
Example #25
0
        public ShaderVariable(ShaderProgram program, int index, string name)
        {
            this.program = program;
            this.index = index;
            this.Name = name;

            Apply = setNothing;
            valueArrayObject = new WeakReference(null);
        }
Example #26
0
        public override void Dispose()
        {
            if( shaderGaussianY != null ){
            shaderGaussianY.Dispose();
            shaderGaussianY = null;
            }

            gaussianWeightTable = null;
        }
Example #27
0
 public static void Add(string name, string[] uniformBindings, string[] attributeBindings)
 {
     ShaderProgram sp=new ShaderProgram("/Application/shaders/"+name+".cgx");
     for (int i = 0; i < uniformBindings.Length; i++)
         sp.SetUniformBinding(i, uniformBindings[i]);
     for (int i = 0; i < attributeBindings.Length; i++)
         sp.SetAttributeBinding(i, uniformBindings[i]);
     _shaders[name]=sp;
 }
Example #28
0
        /// コンストラクタ
        public GaussianYFilter()
        {
            texRenderer = new TextureRenderer();

            // gaussian y
            shaderGaussianY = new ShaderProgram( "/Application/shaders/GaussianY.cgx" );
            shaderGaussianY.SetAttributeBinding( 0, "a_Position" );
            shaderGaussianY.SetAttributeBinding( 1, "a_TexCoord" );
        }
Example #29
0
 //[MethodImpl(MethodImplOptions.AggressiveInlining)]
 private void SetUniformValues(ShaderProgram program)
 {
     //var updatedUniforms = (from item in this.uniformVariables where item.Updated select item).ToArray();
     //foreach (var item in updatedUniforms) { item.DoSetUniform(program); uniformVariableStack.Push(item); }
     UniformVariable[] array = this.uniformVariables.ToArray();
     foreach (UniformVariable item in array)
     {
         item.SetUniform(program);
     }
 }
Example #30
0
 public override void Dispose()
 {
     disposeChilderen();
     if (program != null)
     {
         program.Dispose();
         program = null;
     }
     base.Dispose();
 }
Example #31
0
        /// <summary>
        /// Translates the binary Maxwell shader code to something that the host API accepts.
        /// </summary>
        /// <param name="state">Current GPU state</param>
        /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
        /// <param name="localSizeX">Local group size X of the computer shader</param>
        /// <param name="localSizeY">Local group size Y of the computer shader</param>
        /// <param name="localSizeZ">Local group size Z of the computer shader</param>
        /// <param name="localMemorySize">Local memory size of the compute shader</param>
        /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
        /// <returns>Compiled compute shader code</returns>
        private CachedShader TranslateComputeShader(
            GpuState state,
            ulong gpuVa,
            int localSizeX,
            int localSizeY,
            int localSizeZ,
            int localMemorySize,
            int sharedMemorySize)
        {
            if (gpuVa == 0)
            {
                return null;
            }

            int index = 0;

            for (int stage = 0; stage < programs.Length; stage++)
            {
                ShaderProgram program = programs[stage];

                if (program != null)
                {

                    QueryInfoName.ComputeLocalSizeX
                        => localSizeX,
                    QueryInfoName.ComputeLocalSizeY
                        => localSizeY,
                    QueryInfoName.ComputeLocalSizeZ
                        => localSizeZ,
                    QueryInfoName.ComputeLocalMemorySize
                        => localMemorySize,
                    QueryInfoName.ComputeSharedMemorySize
                        => sharedMemorySize,
                    QueryInfoName.IsTextureBuffer
                        => Convert.ToInt32(QueryIsTextureBuffer(state, 0, index, compute: true)),
                    QueryInfoName.IsTextureRectangle
                        => Convert.ToInt32(QueryIsTextureRectangle(state, 0, index, compute: true)),
                    QueryInfoName.TextureFormat
                        => (int)QueryTextureFormat(state, 0, index, compute: true),
                    _
                        => QueryInfoCommon(info)
                };

                    shaders[index++] = _context.Renderer.CompileShader(program);
                }
            }

            IProgram hostProgram = _context.Renderer.CreateProgram(shaders);

            ShaderProgramInfo[] info = programs.Select(x => x?.Info).ToArray();

            gs = new Shader(hostProgram, new ShaderMeta(hostProgram, info));

            int insertIndex = _cache.Add(hash, gs, pack);

            if (Configuration.Enabled)
            {
                ShaderCacheFile.Save(Configuration.ShaderPath, info, pack, hostProgram.GetGpuBinary(), hash, insertIndex);
            }

            return gs;
        }
Example #32
0
        static void Main(string[] args)
        {
            Glut.glutInit();
            Glut.glutInitDisplayMode(Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH);
            Glut.glutInitWindowSize(width, height);
            Glut.glutCreateWindow("OpenGL Tutorial");

            Glut.glutIdleFunc(OnRenderFrame);
            Glut.glutDisplayFunc(OnDisplay);

            Glut.glutKeyboardFunc(OnKeyboardDown);
            Glut.glutKeyboardUpFunc(OnKeyboardUp);

            Glut.glutCloseFunc(OnClose);
            Glut.glutReshapeFunc(OnReshape);

            // enable blending and set to accumulate the star colors
            Gl.Enable(EnableCap.DepthTest);
            Gl.Enable(EnableCap.Blend);

            // create our shader program
            program = new ShaderProgram(VertexShader, FragmentShader);

            // set up the projection and view matrix
            program.Use();
            program["projection_matrix"].SetValue(Matrix4.CreatePerspectiveFieldOfView(0.45f, (float)width / height, 0.1f, 1000f));
            program["view_matrix"].SetValue(Matrix4.LookAt(new Vector3(0, 0, 20), Vector3.Zero, new Vector3(0, 1, 0)));
            program["model_matrix"].SetValue(Matrix4.Identity);

            // load the flag texture
            flagTexture = new Texture("flag.png");

            // create the flag, which is just a plane with a certain number of segments
            List <Vector3> vertices  = new List <Vector3>();
            List <Vector2> uvs       = new List <Vector2>();
            List <int>     triangles = new List <int>();

            for (int x = 0; x < 40; x++)
            {
                for (int y = 0; y < 40; y++)
                {
                    vertices.Add(new Vector3((x - 20) / 5.0f, (y - 20) / 10.0f, 0));
                    uvs.Add(new Vector2(x / 39.0f, 1 - y / 39.0f));

                    if (y == 39 || x == 39)
                    {
                        continue;
                    }

                    triangles.Add(x * 40 + y);
                    triangles.Add((x + 1) * 40 + y);
                    triangles.Add((x + 1) * 40 + y + 1);

                    triangles.Add(x * 40 + y);
                    triangles.Add((x + 1) * 40 + y + 1);
                    triangles.Add(x * 40 + y + 1);
                }
            }

            flagVertices  = new VBO <Vector3>(vertices.ToArray());
            flagUVs       = new VBO <Vector2>(uvs.ToArray());
            flagTriangles = new VBO <int>(triangles.ToArray(), BufferTarget.ElementArrayBuffer);

            // load the bitmap font for this tutorial
            font        = new BMFont("font24.fnt", "font24.png");
            fontProgram = new ShaderProgram(BMFont.FontVertexSource, BMFont.FontFragmentSource);

            fontProgram.Use();
            fontProgram["ortho_matrix"].SetValue(Matrix4.CreateOrthographic(width, height, 0, 1000));
            fontProgram["color"].SetValue(new Vector3(1, 1, 1));

            information = font.CreateString(fontProgram, "OpenGL  C#  Tutorial  11");

            watch = System.Diagnostics.Stopwatch.StartNew();

            Glut.glutMainLoop();
        }
Example #33
0
        public string GetGeoShader(int ProgramIndex, string[] VtxShaderOutputs, out ShaderNameBlock Names)
        {
            ShaderProgram Program = SHBin.Programs[ProgramIndex];

            Initialize(Program);

            StringBuilder Output = new StringBuilder();

            Output.AppendLine("//SPICA auto-generated code");
            Output.AppendLine("//This code was translated from a MAESTRO Geometry Shader");
            Output.AppendLine("#version 330 core");

            Output.AppendLine();

            GenVec4Uniforms(Output, Program.Vec4Uniforms);
            GenIVec4Uniforms(Output, Program.IVec4Uniforms);
            GenBoolUniforms(Output, Program.BoolUniforms);

            Output.AppendLine();

            Output.AppendLine($"vec4 {TempRegName}[16];");
            Output.AppendLine($"bvec2 {CmpRegName};");
            Output.AppendLine($"ivec2 {A0RegName};");
            Output.AppendLine($"int {ALRegName};");
            Output.AppendLine("int geo_i;");

            Output.AppendLine();

            Output.AppendLine("layout(triangles) in;");
            Output.AppendLine("layout(triangle_strip, max_vertices = 12) out;");

            Output.AppendLine();

            for (int i = 0; i < VtxShaderOutputs.Length; i++)
            {
                if (VtxShaderOutputs[i] != null)
                {
                    InputNames[i] = $"{VtxShaderOutputs[i]}[geo_i]";

                    Output.AppendLine($"in vec4 {VtxShaderOutputs[i]}[];");
                }
            }

            Output.AppendLine();

            GenOutputs(Output, Program.OutputRegs);

            int FuncStart = Output.Length;

            while (Procs.Count > 0)
            {
                SB = new StringBuilder(Environment.NewLine);

                GenProc(Program, Procs.Dequeue());

                Output.Insert(FuncStart, SB.ToString());
            }

            Names = GetNameBlock();

            return(Output.ToString());
        }
Example #34
0
 public BlockModel(EnumBlock block, ShaderProgram shader, AxisAlignedBB bb, bool canBeInteractedWith) : this(block, shader, canBeInteractedWith)
 {
     boundingBox = bb;
 }
Example #35
0
 public override void Draw(Camera cam, ShaderProgram shader)
 {
     base.Draw(cam, shader);
 }
Example #36
0
        static void Main(string[] args)
        {
            Glut.glutInit();
            Glut.glutInitDisplayMode(Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH | Glut.GLUT_MULTISAMPLE);   // multisampling makes things beautiful!
            Glut.glutInitWindowSize(width, height);
            Glut.glutCreateWindow("OpenGL Tutorial");

            Glut.glutIdleFunc(OnRenderFrame);
            Glut.glutDisplayFunc(OnDisplay);

            Glut.glutKeyboardFunc(OnKeyboardDown);
            Glut.glutKeyboardUpFunc(OnKeyboardUp);

            Glut.glutCloseFunc(OnClose);
            Glut.glutReshapeFunc(OnReshape);

            // add our mouse callbacks for this tutorial
            Glut.glutMouseFunc(OnMouse);
            Glut.glutMotionFunc(OnMove);

            Gl.Enable(EnableCap.DepthTest);
            Gl.Enable(EnableCap.Blend);
            Gl.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);

            // create our shader program
            program = new ShaderProgram(VertexShader, FragmentShader);

            // create our camera
            camera = new Camera(new Vector3(0, 0, 0), Quaternion.Identity);
            camera.SetDirection(new Vector3(0, 0, -1));

            // set up the projection and view matrix
            program.Use();
            program["projection_matrix"].SetValue(Matrix4.CreatePerspectiveFieldOfView(0.45f, (float)width / height, 0.1f, 1000f));
            //program["view_matrix"].SetValue(Matrix4.LookAt(new Vector3(0, 0, 10), Vector3.Zero, Vector3.Up));

            program["light_direction"].SetValue(new Vector3(0, 0, 1));

            program["normalTexture"].SetValue(1);

            brickDiffuse = new Texture("333.jpg");


            var sphereCoordinates = CoordinatesManager.GetSphereCoordinates().ToArray();

            var UVcoordinates = new List <Vector2>();

            for (int i = 0; i < sphereCoordinates.Length / 4; i++)
            {
                UVcoordinates.Add(new Vector2(0, 0));
                UVcoordinates.Add(new Vector2(1, 0));
                UVcoordinates.Add(new Vector2(1, 1));
                UVcoordinates.Add(new Vector2(0, 1));
            }
            var sphereUV = new VBO <Vector2>(UVcoordinates.ToArray());


            Vector3[] vertices = new Vector3[] {
                new Vector3(1, 1, -1), new Vector3(-1, 1, -1), new Vector3(-1, 1, 1), new Vector3(1, 1, 1),         // top
                new Vector3(1, -1, 1), new Vector3(-1, -1, 1), new Vector3(-1, -1, -1), new Vector3(1, -1, -1),     // bottom
                new Vector3(1, 1, 1), new Vector3(-1, 1, 1), new Vector3(-1, -1, 1), new Vector3(1, -1, 1),         // front face
                new Vector3(1, -1, -1), new Vector3(-1, -1, -1), new Vector3(-1, 1, -1), new Vector3(1, 1, -1),     // back face
                new Vector3(-1, 1, 1), new Vector3(-1, 1, -1), new Vector3(-1, -1, -1), new Vector3(-1, -1, 1),     // left
                new Vector3(1, 1, -1), new Vector3(1, 1, 1), new Vector3(1, -1, 1), new Vector3(1, -1, -1)
            };
            cube = new VBO <Vector3>(sphereCoordinates);

            Vector2[] uvs = new Vector2[] {
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1)
            };
            cubeUV = CoordinatesManager.GetSphereUVCoordinates();

            List <uint> triangles = new List <uint>();

            for (uint i = 0; i < 6; i++)
            {
                triangles.Add(i * 4);
                triangles.Add(i * 4 + 1);
                triangles.Add(i * 4 + 2);
                triangles.Add(i * 4);
                triangles.Add(i * 4 + 2);
                triangles.Add(i * 4 + 3);
            }
            //cubeTriangles = new VBO<uint>(triangles.ToArray(), BufferTarget.ElementArrayBuffer);
            cubeTriangles =
                new VBO <uint>(Enumerable.Range(0, sphereCoordinates.Length * 4).Select(t => (uint)t).ToArray(),
                               BufferTarget.ElementArrayBuffer);

            // Vector3[] normals = Geometry.CalculateNormals(vertices, triangles.ToArray());
            //cubeNormals = new VBO<Vector3>(normals);



            // load the bitmap font for this tutorial
            font        = new BMFont("font24.fnt", "font24.png");
            fontProgram = new ShaderProgram(BMFont.FontVertexSource, BMFont.FontFragmentSource);

            fontProgram.Use();
            fontProgram["ortho_matrix"].SetValue(Matrix4.CreateOrthographic(width, height, 0, 1000));
            fontProgram["color"].SetValue(new Vector3(1, 1, 1));

            information = font.CreateString(fontProgram, "OpenGL C# Tutorial 15");

            watch = System.Diagnostics.Stopwatch.StartNew();

            Glut.glutMainLoop();
        }
Example #37
0
 public void AddGeometry(ShaderProgram program)
 {
     _GeometryInstances.Add(new Geometry(program));
 }
Example #38
0
        protected override void DoInitialize()
        {
            this.shaderProgram = InitializeShader();

            InitVAO();
        }
Example #39
0
        static void Main(string[] args)
        {
            //Open GL init
            #region
            Glut.glutInit();
            Glut.glutInitDisplayMode(Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH);
            Glut.glutInitWindowSize(1280, 720);
            Glut.glutCreateWindow("Tu mama es maraca");

            Glut.glutIdleFunc(OnRenderFrame);
            Glut.glutDisplayFunc(OnDisplay);
            Glut.glutCloseFunc(OnClose);
            Glut.glutReshapeFunc(OnReshape);
            //Keyboard functions
            Glut.glutKeyboardFunc(OnKeyboardDown);
            Glut.glutKeyboardUpFunc(OnKeyboardUp);

            //Gl.ClearColor(0,0,0,1);

            //Alpha enabled
            Gl.Disable(EnableCap.DepthTest);
            Gl.Enable(EnableCap.Blend);
            Gl.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.One);

            #endregion

            //Load shader
            program = new ShaderProgram(VertexShader, FragmentShader);

            //Create perspective
            program.Use();
            program["projection_matrix"].SetValue(
                Matrix4.CreatePerspectiveFieldOfView(0.45f,
                                                     (float)width / height, 0.1f, 1000f));
            program["view_matrix"].SetValue(
                Matrix4.LookAt(new Vector3(0, 0, 10),
                               new Vector3(0, 0, 0),
                               new Vector3(0, 1, 0)));

            starTexture   = new Texture("star.bmp");
            playerTexture = new Texture("crate.jpg");
            enemyTexture  = new Texture("tile.jpg");
            playerColor   = new Vector3(1, 1, 1);
            //start vertices and uv
            #region
            start = new VBO <Vector3>(
                new Vector3[] {
                new Vector3(-1, 1, 0), new Vector3(1, 1, 0),
                new Vector3(1, -1, 0), new Vector3(-1, -1, 0)
            }
                );
            startElements = new VBO <int>(
                new int[] { 0, 1, 2, 3 },
                BufferTarget.ElementArrayBuffer
                );
            startUV = new VBO <Vector2>(
                new Vector2[] {
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1)
            }
                );
            #endregion

            //Player

            player = new VBO <Vector3>(
                new Vector3[] {
                new Vector3(0, 0.7, 0), new Vector3(1, 0, 0), new Vector3(0, -0.7, 0), new Vector3(-0.5, 0, 0)
            }
                );
            playerElements = new VBO <int>(
                new int[] { 0, 1, 2, 3 },
                BufferTarget.ElementArrayBuffer
                );
            playerUV = new VBO <Vector2>(
                new Vector2[] {
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1)
            }
                );



            watch = System.Diagnostics.Stopwatch.StartNew();

            Glut.glutMainLoop();
        }
Example #40
0
 public Mesh GetMesh(ShaderProgram shader) =>
 mesh ?? (mesh = new Mesh(BuildMesh(), shader));
Example #41
0
 public static void Unbind()
 {
     ShaderProgram.Unbind();
     GL.BindTexture(GL.TEXTURE_2D_ARRAY, 0);
 }
Example #42
0
 private void SetRenderSettings(ShaderProgram shader)
 {
     shader.SetBoolToInt("renderVertColor", Runtime.renderVertColor);
     GL.Uniform1(defaultShaderProgram["renderType"], (int)Runtime.viewportShading);
 }
Example #43
0
        //static OpenGLDevice NuklearDev;

        static void Main(string[] args)
        {
            /*IBWFile F = IBWLoader.Load("dataset/ibw/Image0018.ibw");
             *
             * for (int i = 0; i < F.Depth; i++) {
             *      Bitmap Bmp = new Bitmap(F.Width, F.Height);
             *
             *      int D_Dim = i;
             *
             *      float Min = float.MaxValue;
             *      float Max = float.MinValue;
             *
             *      for (int y = 0; y < F.Height; y++) {
             *              for (int x = 0; x < F.Width; x++) {
             *                      float Flt = (float)F.GetData(x, y, D_Dim) * 1000000000;
             *
             *                      Min = Math.Min(Min, Flt);
             *                      Max = Math.Max(Max, Flt);
             *              }
             *      }
             *
             *      float Offset = -Min;
             *      float OffsetMax = Max + Offset;
             *      float ScaleVal = 255.0f / OffsetMax;
             *
             *      Min = float.MaxValue;
             *      Max = float.MinValue;
             *
             *      for (int y = 0; y < F.Height; y++) {
             *              for (int x = 0; x < F.Width; x++) {
             *                      float Flt = ((float)F.GetData(x, y, D_Dim) * 1000000000 + Offset) * ScaleVal;
             *
             *                      int Clr = (int)Flt;
             *                      Bmp.SetPixel(x, F.Height - y - 1, System.Drawing.Color.FromArgb(255, Clr, Clr, Clr));
             *              }
             *      }
             *
             *      Bmp.Save("test_" + i + ".png");
             * }
             *
             *
             * File.WriteAllText("text_data.txt", F.NoteData);
             *
             *
             * Console.WriteLine("Done!");
             * Console.ReadLine();
             * return;//*/



            const float Scale = 0.9f;

            ClearColor = new FishGfx.Color(60, 80, 100);

            RenderAPI.GetDesktopResolution(out int W, out int H);
            RWind = new RenderWindow((int)(W * Scale), (int)(H * Scale), "Vector PFM");

            Console.WriteLine("OpenGL {0}", RenderAPI.Version);
            Console.WriteLine("Running on {0}", RenderAPI.Renderer);

            // Load shader programs
            Shader_DrawRayCast = new ShaderProgram(new ShaderStage(ShaderType.VertexShader, "data/default3d.vert"),
                                                   new ShaderStage(ShaderType.FragmentShader, "data/defaultRayCast.frag"));
            Shader_DrawRayCast.Uniforms.Camera.SetPerspective(RWind.GetWindowSizeVec());
            Shader_DrawRayCast.Uniforms.Camera.Position   = new Vector3(0, 300, 0);
            Shader_DrawRayCast.Uniforms.Camera.PitchClamp = new Vector2(-80, 80);

            Shader_DrawFlat = new ShaderProgram(new ShaderStage(ShaderType.VertexShader, "data/default3d.vert"),
                                                new ShaderStage(ShaderType.FragmentShader, "data/defaultFlatColor.frag"));
            Shader_DrawFlat.Uniforms.Camera = Shader_DrawRayCast.Uniforms.Camera;

            Shader_Screen = new ShaderProgram(new ShaderStage(ShaderType.VertexShader, "data/default.vert"),
                                              new ShaderStage(ShaderType.FragmentShader, "data/default.frag"));
            Shader_Screen.Uniforms.Camera.SetOrthogonal(0, 0, 1, 1);

            Shader_Textured = new ShaderProgram(new ShaderStage(ShaderType.VertexShader, "data/default3d.vert"),
                                                new ShaderStage(ShaderType.FragmentShader, "data/default.frag"));
            Shader_Textured.Uniforms.Camera = Shader_DrawRayCast.Uniforms.Camera;

            //NuklearDev = new OpenGLDevice(RWind.GetWindowSizeVec());
            //NuklearAPI.Init(NuklearDev);

            RWind.OnMouseMoveDelta += (Wnd, X, Y) => Shader_DrawRayCast.Uniforms.Camera.Update(new Vector2(-X, -Y));
            RWind.OnKey            += OnKey;
            //RWind.OnMouseMove += (Wnd, X, Y) => NuklearDev.OnMouseMove((int)X, (int)Y);

            RWind.OnMouseMoveDelta += (Wnd, X, Y) => {
                if (LeftMouse)
                {
                    const float MoveSpeed = 1.0f;

                    if (X != 0 || Y != 0)
                    {
                        Camera Cam = Shader_DrawRayCast.Uniforms.Camera;

                        if (X != 0)
                        {
                            Cam.Position -= Cam.WorldRightNormal * MoveSpeed * -X;
                        }

                        if (Y != 0)
                        {
                            Cam.Position += Cam.WorldUpNormal * MoveSpeed * -Y;
                        }

                        RecalcCamera();
                    }
                }
                else if (RightMouse)
                {
                    DesiredPivotDistance += Y;
                    RecalcCamera();
                }
            };

            HMap = new Terrain();
            HMap.LoadFromImage(Image.FromFile("dataset/data2/heightmap.png"), 100);
            //HMap.LoadFromImage(Image.FromFile("dataset/height_test.png"), 10);
            //HMap.LoadFromImage(Image.FromFile("dataset/owl.png"), 100);


            DesiredPivotDistance = float.PositiveInfinity;
            CameraPivot          = new Vector3(HMap.Width / 2, HMap.GetHeight(HMap.Width / 2, HMap.Height / 2), HMap.Height / 2);
            RecalcCamera();

            PinMesh = new Mesh3D {
                PrimitiveType = PrimitiveType.Triangles
            };
            PinMesh.SetVertices(GfxUtils.LoadObj("data/models/pin/pin.obj"));

            PinTexture = Texture.FromFile("data/models/pin/pin_mat.png");

            Mesh3D Vectors = new Mesh3D {
                PrimitiveType = PrimitiveType.Lines
            };

            {
                //Vertex3[] Verts = new Vertex3[HMap.Width * HMap.Height * 2];
                List <Vertex3> Verts = new List <Vertex3>();

                for (int i = 0; i < HMap.Width * HMap.Height * 2; i += 2)
                {
                    int X = (i / 2) % HMap.Width;
                    int Y = (i / 2) / HMap.Width;

                    const int Density = 2;
                    if (X % Density != 0 || Y % Density != 0)
                    {
                        continue;
                    }

                    float Height = HMap.GetHeight(X, Y);

                    Verts.Add(new Vertex3(new Vector3(X, Height - 0.5f, Y), FishGfx.Color.Black));
                    Verts.Add(new Vertex3(new Vector3(X, Height + 20, Y), FishGfx.Color.White));
                }

                Vectors.SetVertices(Verts.ToArray());
            }

            RWind.GetWindowSize(out int WindowWidth, out int WindowHeight);
            RenderTexture Screen = new RenderTexture(WindowWidth, WindowHeight);

            RayCastingTexture = Screen.CreateNewColorAttachment(1);

            Background = Texture.FromFile("data/background.png");

            Mesh2D ScreenQuad = new Mesh2D();

            ScreenQuad.SetVertices(new Vertex2[] {
                new Vertex2(new Vector2(0, 0), new Vector2(0, 0)),
                new Vertex2(new Vector2(0, 1), new Vector2(0, 1)),
                new Vertex2(new Vector2(1, 1), new Vector2(1, 1)),
                new Vertex2(new Vector2(1, 0), new Vector2(1, 0))
            });
            ScreenQuad.SetElements(new uint[] { 0, 1, 2, 0, 2, 3 }.Reverse().ToArray());

            Stopwatch SWatch = Stopwatch.StartNew();
            float     Dt     = 0;

            while (!RWind.ShouldClose)
            {
                Update(Dt);

                // Draw the world onto a render texture including the ray casting buffer
                Screen.Bind(0, 1);
                {
                    Shader_DrawRayCast.Bind();
                    Gfx.Clear(FishGfx.Color.Transparent);

                    /*Gfx.EnableCullFace(false);
                     * HMap.Draw();
                     * Gfx.EnableCullFace(true);*/

                    // Draw back face
                    Gfx.CullFront();
                    Texture Orig = HMap.OverlayTexture;
                    HMap.OverlayTexture = Background;
                    HMap.Draw();

                    // Draw front face
                    Gfx.CullBack();
                    HMap.OverlayTexture = Orig;
                    HMap.Draw();

                    Shader_DrawRayCast.Unbind();
                }
                Screen.Unbind();

                // Draw other stuff
                Screen.Bind(0);
                {
                    Shader_DrawFlat.Bind();
                    Vectors.Draw();
                    Shader_DrawFlat.Unbind();

                    Shader_Textured.Bind();
                    Shader_Textured.SetModelMatrix(Matrix4x4.CreateScale(2) * Matrix4x4.CreateTranslation(CameraPivot));
                    PinTexture.BindTextureUnit();
                    PinMesh.Draw();
                    PinTexture.UnbindTextureUnit();
                    Shader_Textured.Unbind();
                }
                Screen.Unbind();

                // Draw render texture and GUI to screen
                Shader_Screen.Bind();
                {
                    Gfx.Clear(ClearColor);
                    Gfx.EnableDepthDest(false);

                    if (FunctionMode == 1)
                    {
                        Screen.Color.BindTextureUnit();
                    }
                    else if (FunctionMode == 2)
                    {
                        RayCastingTexture.BindTextureUnit();
                    }

                    ScreenQuad.Draw();
                    //NuklearAPI.Frame(DrawGUI);
                    Gfx.EnableDepthDest(true);
                }
                Shader_Screen.Unbind();

                // Swap buffers, do magic
                RWind.SwapBuffers();
                Events.Poll();

                while (SWatch.ElapsedMilliseconds / 1000.0f < 1.0f / 60.0f)
                {
                    ;
                }
                Dt = SWatch.ElapsedMilliseconds / 1000.0f;
                SWatch.Restart();
            }
        }
Example #44
0
 /// <summary>
 /// Construct an Geometry.
 /// </summary>
 /// <param name="vertexArray">
 ///
 /// </param>
 /// <param name="state"></param>
 /// <param name="program"></param>
 public Geometry(VertexArrayObject vertexArray, State.GraphicsStateSet state, ShaderProgram program) :
     base(vertexArray, state, program)
 {
 }
Example #45
0
        static void Main(string[] args)
        {
            Glut.glutInit();
            Glut.glutInitDisplayMode(Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH | Glut.GLUT_MULTISAMPLE);   // multisampling makes things beautiful!
            Glut.glutInitWindowSize(width, height);
            Glut.glutCreateWindow("OpenGL Tutorial");

            Glut.glutIdleFunc(OnRenderFrame);
            Glut.glutDisplayFunc(OnDisplay);

            Glut.glutKeyboardFunc(OnKeyboardDown);
            Glut.glutKeyboardUpFunc(OnKeyboardUp);

            Glut.glutCloseFunc(OnClose);
            Glut.glutReshapeFunc(OnReshape);

            Gl.Enable(EnableCap.DepthTest);
            Gl.Enable(EnableCap.Multisample);

            // create our shader program
            program = new ShaderProgram(VertexShader, FragmentShader);

            // set up the projection and view matrix
            program.Use();
            program["projection_matrix"].SetValue(Matrix4.CreatePerspectiveFieldOfView(0.45f, (float)width / height, 0.1f, 1000f));
            program["view_matrix"].SetValue(Matrix4.LookAt(new Vector3(0, 0, 10), Vector3.Zero, new Vector3(0, 1, 0)));

            program["light_direction"].SetValue(new Vector3(0, 0, 1));
            program["enable_lighting"].SetValue(lighting);
            program["normalTexture"].SetValue(1);
            program["enable_mapping"].SetValue(normalMapping);

            brickDiffuse = new Texture("AlternatingBrick-ColorMap.png");
            brickNormals = new Texture("AlternatingBrick-NormalMap.png");

            Vector3[] vertices = new Vector3[] {
                new Vector3(1, 1, -1), new Vector3(-1, 1, -1), new Vector3(-1, 1, 1), new Vector3(1, 1, 1),         // top
                new Vector3(1, -1, 1), new Vector3(-1, -1, 1), new Vector3(-1, -1, -1), new Vector3(1, -1, -1),     // bottom
                new Vector3(1, 1, 1), new Vector3(-1, 1, 1), new Vector3(-1, -1, 1), new Vector3(1, -1, 1),         // front face
                new Vector3(1, -1, -1), new Vector3(-1, -1, -1), new Vector3(-1, 1, -1), new Vector3(1, 1, -1),     // back face
                new Vector3(-1, 1, 1), new Vector3(-1, 1, -1), new Vector3(-1, -1, -1), new Vector3(-1, -1, 1),     // left
                new Vector3(1, 1, -1), new Vector3(1, 1, 1), new Vector3(1, -1, 1), new Vector3(1, -1, -1)
            };
            cube = new VBO <Vector3>(vertices);

            Vector2[] uvs = new Vector2[] {
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1)
            };
            cubeUV = new VBO <Vector2>(uvs);

            List <int> triangles = new List <int>();

            for (int i = 0; i < 6; i++)
            {
                triangles.Add(i * 4);
                triangles.Add(i * 4 + 1);
                triangles.Add(i * 4 + 2);
                triangles.Add(i * 4);
                triangles.Add(i * 4 + 2);
                triangles.Add(i * 4 + 3);
            }
            cubeTriangles = new VBO <int>(triangles.ToArray(), BufferTarget.ElementArrayBuffer);

            Vector3[] normals = Geometry.CalculateNormals(vertices, triangles.ToArray());
            cubeNormals = new VBO <Vector3>(normals);

            Vector3[] tangents = CalculateTangents(vertices, normals, triangles.ToArray(), uvs);
            cubeTangents = new VBO <Vector3>(tangents);

            // load the bitmap font for this tutorial
            font        = new BMFont("font24.fnt", "font24.png");
            fontProgram = new ShaderProgram(BMFont.FontVertexSource, BMFont.FontFragmentSource);

            fontProgram.Use();
            fontProgram["ortho_matrix"].SetValue(Matrix4.CreateOrthographic(width, height, 0, 1000));
            fontProgram["color"].SetValue(new Vector3(1, 1, 1));

            information = font.CreateString(fontProgram, "OpenGL  C#  Tutorial  13");

            watch = System.Diagnostics.Stopwatch.StartNew();

            Glut.glutMainLoop();
        }
Example #46
0
 /// <summary>
 /// Apply this MaterialState
 /// </summary>
 /// <param name="ctx">
 /// A <see cref="GraphicsContext"/> which has defined the shader program <paramref name="shaderProgram"/>.
 /// </param>
 /// <param name="shaderProgram">
 /// The <see cref="ShaderProgram"/> which has the state set.
 /// </param>
 public void ApplyState(GraphicsContext ctx, ShaderProgram shaderProgram, string prefix)
 {
     shaderProgram.SetUniform(ctx, prefix + ".AmbientLighting", AmbientLighting);
 }
Example #47
0
        /// <summary>
        /// Initialize the cache.
        /// </summary>
        internal void Initialize()
        {
            if (GraphicsConfig.EnableShaderCache && GraphicsConfig.TitleId != null)
            {
                _cacheManager = new CacheManager(CacheGraphicsApi.OpenGL, CacheHashType.XxHash128, "glsl", GraphicsConfig.TitleId, ShaderCodeGenVersion);

                bool isReadOnly = _cacheManager.IsReadOnly;

                HashSet <Hash128> invalidEntries = null;

                if (isReadOnly)
                {
                    Logger.Warning?.Print(LogClass.Gpu, "Loading shader cache in read-only mode (cache in use by another program!)");
                }
                else
                {
                    invalidEntries = new HashSet <Hash128>();
                }

                ReadOnlySpan <Hash128> guestProgramList = _cacheManager.GetGuestProgramList();

                for (int programIndex = 0; programIndex < guestProgramList.Length; programIndex++)
                {
                    Hash128 key = guestProgramList[programIndex];

                    Logger.Info?.Print(LogClass.Gpu, $"Compiling shader {key} ({programIndex + 1} / {guestProgramList.Length})");

                    byte[] hostProgramBinary = _cacheManager.GetHostProgramByHash(ref key);
                    bool   hasHostCache      = hostProgramBinary != null;

                    IProgram hostProgram = null;

                    // If the program sources aren't in the cache, compile from saved guest program.
                    byte[] guestProgram = _cacheManager.GetGuestProgramByHash(ref key);

                    if (guestProgram == null)
                    {
                        Logger.Error?.Print(LogClass.Gpu, $"Ignoring orphan shader hash {key} in cache (is the cache incomplete?)");

                        // Should not happen, but if someone messed with the cache it's better to catch it.
                        invalidEntries?.Add(key);

                        continue;
                    }

                    ReadOnlySpan <byte> guestProgramReadOnlySpan = guestProgram;

                    ReadOnlySpan <GuestShaderCacheEntry> cachedShaderEntries = GuestShaderCacheEntry.Parse(ref guestProgramReadOnlySpan, out GuestShaderCacheHeader fileHeader);

                    if (cachedShaderEntries[0].Header.Stage == ShaderStage.Compute)
                    {
                        Debug.Assert(cachedShaderEntries.Length == 1);

                        GuestShaderCacheEntry entry = cachedShaderEntries[0];

                        HostShaderCacheEntry[] hostShaderEntries = null;

                        // Try loading host shader binary.
                        if (hasHostCache)
                        {
                            hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan <byte> hostProgramBinarySpan);
                            hostProgramBinary = hostProgramBinarySpan.ToArray();
                            hostProgram       = _context.Renderer.LoadProgramBinary(hostProgramBinary);
                        }

                        bool isHostProgramValid = hostProgram != null;

                        ShaderProgram     program;
                        ShaderProgramInfo shaderProgramInfo;

                        // Reconstruct code holder.
                        if (isHostProgramValid)
                        {
                            program           = new ShaderProgram(entry.Header.Stage, "", entry.Header.Size, entry.Header.SizeA);
                            shaderProgramInfo = hostShaderEntries[0].ToShaderProgramInfo();
                        }
                        else
                        {
                            IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                            program = Translator.CreateContext(0, gpuAccessor, DefaultFlags | TranslationFlags.Compute).Translate(out shaderProgramInfo);
                        }

                        ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);

                        // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
                        if (hostProgram == null)
                        {
                            Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");

                            // Compile shader and create program as the shader program binary got invalidated.
                            shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
                            hostProgram       = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);

                            // As the host program was invalidated, save the new entry in the cache.
                            hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });

                            if (!isReadOnly)
                            {
                                if (hasHostCache)
                                {
                                    _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
                                }
                                else
                                {
                                    Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");

                                    _cacheManager.AddHostProgram(ref key, hostProgramBinary);
                                }
                            }
                        }

                        _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));
                    }
                    else
                    {
                        Debug.Assert(cachedShaderEntries.Length == Constants.ShaderStages);

                        ShaderCodeHolder[]   shaders        = new ShaderCodeHolder[cachedShaderEntries.Length];
                        List <ShaderProgram> shaderPrograms = new List <ShaderProgram>();

                        TransformFeedbackDescriptor[] tfd = CacheHelper.ReadTransformationFeedbackInformations(ref guestProgramReadOnlySpan, fileHeader);

                        TranslationFlags flags = DefaultFlags;

                        if (tfd != null)
                        {
                            flags = TranslationFlags.Feedback;
                        }

                        TranslationCounts counts = new TranslationCounts();

                        HostShaderCacheEntry[] hostShaderEntries = null;

                        // Try loading host shader binary.
                        if (hasHostCache)
                        {
                            hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan <byte> hostProgramBinarySpan);
                            hostProgramBinary = hostProgramBinarySpan.ToArray();
                            hostProgram       = _context.Renderer.LoadProgramBinary(hostProgramBinary);
                        }

                        bool isHostProgramValid = hostProgram != null;

                        // Reconstruct code holder.
                        for (int i = 0; i < cachedShaderEntries.Length; i++)
                        {
                            GuestShaderCacheEntry entry = cachedShaderEntries[i];

                            if (entry == null)
                            {
                                continue;
                            }

                            ShaderProgram program;

                            if (entry.Header.SizeA != 0)
                            {
                                ShaderProgramInfo shaderProgramInfo;

                                if (isHostProgramValid)
                                {
                                    program           = new ShaderProgram(entry.Header.Stage, "", entry.Header.Size, entry.Header.SizeA);
                                    shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
                                }
                                else
                                {
                                    IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                    program = Translator.CreateContext((ulong)entry.Header.Size, 0, gpuAccessor, flags, counts).Translate(out shaderProgramInfo);
                                }

                                // NOTE: Vertex B comes first in the shader cache.
                                byte[] code  = entry.Code.AsSpan().Slice(0, entry.Header.Size).ToArray();
                                byte[] code2 = entry.Code.AsSpan().Slice(entry.Header.Size, entry.Header.SizeA).ToArray();

                                shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, code, code2);
                            }
                            else
                            {
                                ShaderProgramInfo shaderProgramInfo;

                                if (isHostProgramValid)
                                {
                                    program           = new ShaderProgram(entry.Header.Stage, "", entry.Header.Size, entry.Header.SizeA);
                                    shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
                                }
                                else
                                {
                                    IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                    program = Translator.CreateContext(0, gpuAccessor, flags, counts).Translate(out shaderProgramInfo);
                                }

                                shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
                            }

                            shaderPrograms.Add(program);
                        }

                        // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
                        if (!isHostProgramValid)
                        {
                            Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");

                            List <IShader> hostShaders = new List <IShader>();

                            // Compile shaders and create program as the shader program binary got invalidated.
                            for (int stage = 0; stage < Constants.ShaderStages; stage++)
                            {
                                ShaderProgram program = shaders[stage]?.Program;

                                if (program == null)
                                {
                                    continue;
                                }

                                IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);

                                shaders[stage].HostShader = hostShader;

                                hostShaders.Add(hostShader);
                            }

                            hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);

                            // As the host program was invalidated, save the new entry in the cache.
                            hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);

                            if (!isReadOnly)
                            {
                                if (hasHostCache)
                                {
                                    _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
                                }
                                else
                                {
                                    Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");

                                    _cacheManager.AddHostProgram(ref key, hostProgramBinary);
                                }
                            }
                        }

                        _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));
                    }
                }

                if (!isReadOnly)
                {
                    // Remove entries that are broken in the cache
                    _cacheManager.RemoveManifestEntries(invalidEntries);
                    _cacheManager.FlushToArchive();
                    _cacheManager.Synchronize();
                }

                Logger.Info?.Print(LogClass.Gpu, "Shader cache loaded.");
            }
        }
Example #48
0
        public static void Initialize()
        {
            if (initialized)
            {
                return;
            }

            //string GetCondition(int row, Vector3 vec)
            //{
            //    if (vec.X != 0)
            //        return $"mtx.M{row}1=={vec.X}";
            //    else if (vec.Y != 0)
            //        return $"mtx.M{row}2=={vec.Y}";
            //    else
            //        return $"mtx.M{row}3=={vec.Z}";
            //}

            //string edgeCases = "";

            //for (float x = -90; x <= 180; x+=90)
            //{
            //    for (float y = -90; y <= 180; y += 90)
            //    {
            //        for (float z = -90; z <= 180; z += 90)
            //        {
            //            var mat = Mat3FromEulerAnglesDeg(new Vector3(x, y, z));

            //            var mat2 = Mat3FromEulerAnglesDeg(mat.ExtractDegreeEulerAngles());

            //            if (mat != mat2)
            //            {
            //                edgeCases += $"if({GetCondition(1,mat.Row0)} && {GetCondition(2, mat.Row1)} && {GetCondition(3, mat.Row2)})\n";
            //                edgeCases += $"    return new Vector3({x},{y},{z});\n";
            //            }
            //        }
            //    }
            //}

            //solid shader
            var solidColorFrag = new FragmentShader(
                @"#version 330
                        uniform vec4 color;
                        void main(){
                            gl_FragColor = color;
                        }");
            var solidColorVert = new VertexShader(
                @"#version 330
                        layout(location = 0) in vec4 position;
                        uniform mat4 mtxMdl;
                        uniform mat4 mtxCam;
                        void main(){
                            gl_Position = mtxCam*mtxMdl*position;
                        }");

            SolidColorShaderProgram = new ShaderProgram(solidColorFrag, solidColorVert);

            //texture sheet
            TextureSheet = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2D, TextureSheet);

            var bmp     = Properties.Resources.TextureSheet;
            var bmpData = bmp.LockBits(
                new Rectangle(0, 0, 128 * 4, 128 * 2),
                System.Drawing.Imaging.ImageLockMode.ReadOnly,
                System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, 128 * 4, 128 * 2, 0, PixelFormat.Bgra, PixelType.UnsignedByte, bmpData.Scan0);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);
            bmp.UnlockBits(bmpData);

            initialized = true;
        }
Example #49
0
 public Geometry(ShaderProgram program) :
     base(program)
 {
 }
Example #50
0
        /// <summary>
        /// Gets a graphics shader program from the shader cache.
        /// This includes all the specified shader stages.
        /// </summary>
        /// <remarks>
        /// This automatically translates, compiles and adds the code to the cache if not present.
        /// </remarks>
        /// <param name="state">Current GPU state</param>
        /// <param name="addresses">Addresses of the shaders for each stage</param>
        /// <returns>Compiled graphics shader code</returns>
        public ShaderBundle GetGraphicsShader(GpuState state, ShaderAddresses addresses)
        {
            bool isCached = _gpPrograms.TryGetValue(addresses, out List <ShaderBundle> list);

            if (isCached)
            {
                foreach (ShaderBundle cachedGpShaders in list)
                {
                    if (IsShaderEqual(cachedGpShaders, addresses))
                    {
                        return(cachedGpShaders);
                    }
                }
            }

            TranslatorContext[] shaderContexts = new TranslatorContext[Constants.ShaderStages];

            TransformFeedbackDescriptor[] tfd = GetTransformFeedbackDescriptors(state);

            TranslationFlags flags = DefaultFlags;

            if (tfd != null)
            {
                flags |= TranslationFlags.Feedback;
            }

            TranslationCounts counts = new TranslationCounts();

            if (addresses.VertexA != 0)
            {
                shaderContexts[0] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Vertex, addresses.Vertex, addresses.VertexA);
            }
            else
            {
                shaderContexts[0] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Vertex, addresses.Vertex);
            }

            shaderContexts[1] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationControl, addresses.TessControl);
            shaderContexts[2] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
            shaderContexts[3] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Geometry, addresses.Geometry);
            shaderContexts[4] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Fragment, addresses.Fragment);

            bool isShaderCacheEnabled  = _cacheManager != null;
            bool isShaderCacheReadOnly = false;

            Hash128 programCodeHash = default;

            GuestShaderCacheEntry[] shaderCacheEntries = null;

            if (isShaderCacheEnabled)
            {
                isShaderCacheReadOnly = _cacheManager.IsReadOnly;

                // Compute hash and prepare data for shader disk cache comparison.
                shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(_context.MemoryManager, shaderContexts);
                programCodeHash    = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries, tfd);
            }

            ShaderBundle gpShaders;

            // Search for the program hash in loaded shaders.
            if (!isShaderCacheEnabled || !_gpProgramsDiskCache.TryGetValue(programCodeHash, out gpShaders))
            {
                if (isShaderCacheEnabled)
                {
                    Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
                }

                // The shader isn't currently cached, translate it and compile it.
                ShaderCodeHolder[] shaders = new ShaderCodeHolder[Constants.ShaderStages];

                shaders[0] = TranslateShader(shaderContexts[0]);
                shaders[1] = TranslateShader(shaderContexts[1]);
                shaders[2] = TranslateShader(shaderContexts[2]);
                shaders[3] = TranslateShader(shaderContexts[3]);
                shaders[4] = TranslateShader(shaderContexts[4]);

                List <IShader> hostShaders = new List <IShader>();

                for (int stage = 0; stage < Constants.ShaderStages; stage++)
                {
                    ShaderProgram program = shaders[stage]?.Program;

                    if (program == null)
                    {
                        continue;
                    }

                    IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);

                    shaders[stage].HostShader = hostShader;

                    hostShaders.Add(hostShader);
                }

                IProgram hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);

                byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);

                gpShaders = new ShaderBundle(hostProgram, shaders);

                if (isShaderCacheEnabled)
                {
                    _gpProgramsDiskCache.Add(programCodeHash, gpShaders);

                    if (!isShaderCacheReadOnly)
                    {
                        _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries, tfd), hostProgramBinary);
                    }
                }
            }

            if (!isCached)
            {
                list = new List <ShaderBundle>();

                _gpPrograms.Add(addresses, list);
            }

            list.Add(gpShaders);

            return(gpShaders);
        }
Example #51
0
        /// <summary>
        /// Apply this TransformState.
        /// </summary>
        /// <param name="ctx">
        /// A <see cref="GraphicsContext"/> which has defined the shader program <paramref name="shaderProgram"/>.
        /// </param>
        /// <param name="shaderProgram">
        /// The <see cref="ShaderProgram"/> which has the state set.
        /// </param>
        public override void Apply(GraphicsContext ctx, ShaderProgram shaderProgram)
        {
            GraphicsResource.CheckCurrentContext(ctx);

            if (!ctx.Extensions.UniformBufferObject_ARB)
            {
                if (shaderProgram == null)
                {
                    // Fixed pipeline rendering requires server state
                    throw new NotImplementedException();
                }
                else
                {
                    // Custom implementation
                    ctx.Bind(shaderProgram);

                    if (shaderProgram.IsActiveUniform("glo_LightModel"))
                    {
                        LightModel.ApplyState(ctx, shaderProgram, "glo_LightModel");
                    }

                    for (int i = 0; i < Lights.Count; i++)
                    {
                        string uniformName = "glo_Light[" + i + "]";

                        if (shaderProgram.IsActiveUniform(uniformName) == false)
                        {
                            break;
                        }

                        Lights[i].ApplyState(ctx, shaderProgram, uniformName);
                    }

                    shaderProgram.SetUniform(ctx, "glo_LightsCount", LightsCount);
                }
            }
            else
            {
                base.Apply(ctx, shaderProgram);                         // Uniform block
            }
            // Dummy shadow map: Texture2d
            // Note: necessary to avoid undefined behavior on glo_ShadowMap2D samplers
            string resourceClassId = "OpenGL.Objects.ShadowMap.DummyTexture2d";

            Texture2d dummyShadowMap = (Texture2d)ctx.GetSharedResource(resourceClassId);

            if (dummyShadowMap == null)
            {
                dummyShadowMap = new Texture2d(1, 1, PixelLayout.Depth16);
                dummyShadowMap.SamplerParams.CompareMode = true;
                dummyShadowMap.SamplerParams.CompareFunc = DepthFunction.Never;
                dummyShadowMap.Create(ctx);

                ctx.SetSharedResource(resourceClassId, dummyShadowMap);
            }

            // Dummy shadow map: TextureCube

            // Apply depth maps
            bool[] tex2dSet = new bool[4];

            for (int i = 0; i < tex2dSet.Length; i++)
            {
                if (i >= Lights.Count || Lights[i].ShadowMap2D == null)
                {
                    continue;
                }

                int shadowMapIndex = Lights[i].ShadowMapIndex;

                shaderProgram.SetUniform(ctx, "glo_ShadowMap2D[" + shadowMapIndex + "]", Lights[i].ShadowMap2D);
                tex2dSet[shadowMapIndex] = true;
            }

            // Avoid undefined behavior
            for (int i = 0; i < tex2dSet.Length; i++)
            {
                if (tex2dSet[i] == false)
                {
                    shaderProgram.SetUniform(ctx, "glo_ShadowMap2D[" + i + "]", dummyShadowMap);
                }
            }
        }
        public static void Initialize(GL_ControlModern control)
        {
            if (DefaultShaderProgram != null && DefaultShaderProgram.programs.ContainsKey(control))
            {
                return;
            }

            if (DefaultShaderProgram == null)
            {
                var solidColorFrag = new FragmentShader(
                    @"#version 330
                uniform vec4 color;
                in vec3 normal;
                in vec3 viewPosition;
                void main(){
                    vec3 xTangent = dFdx( viewPosition );
                    vec3 yTangent = dFdy( viewPosition );
                    vec3 faceNormal = normalize( cross( xTangent, yTangent ) );

                    vec3 displayNormal = (faceNormal.xyz * 0.5) + 0.5;
		            float shading = max(displayNormal.y,0.5);

                    gl_FragColor = color;
                }");
                var solidColorVert = new VertexShader(
                    @"#version 330
                layout(location = 0) in vec3 position;
                layout(location = 1) in vec3 vNormal;
                uniform mat4 mtxMdl;
                uniform mat4 mtxCam;
                out vec3 normal;
                out vec3 viewPosition;
                void main(){
                    normal = vNormal;
                    viewPosition = position;
                    gl_Position = mtxCam*mtxMdl*vec4(position, 1);
                }");

                DefaultShaderProgram = new ShaderProgram(solidColorFrag, solidColorVert, control);

                int buffer = GL.GenBuffer();
                sphereVao = new VertexArrayObject(buffer);
                sphereVao.AddAttribute(0, 3, VertexAttribPointerType.Float, false, 24, 0);
                sphereVao.AddAttribute(1, 3, VertexAttribPointerType.Float, false, 24, 12);
                sphereVao.Initialize(control);

                List <float> list = new List <float>();
                Vertices = GetVertices(10, 2, 15, 32);
                for (int i = 0; i < Vertices.Length; i++)
                {
                    var mat = Matrix4.CreateRotationX(MathHelper.DegreesToRadians(90));
                    Vertices[i].Position = Vector3.TransformPosition(Vertices[i].Position, mat);
                    Vertices[i].Normal   = Vector3.TransformNormal(Vertices[i].Normal, mat);

                    list.Add(Vertices[i].Position.X);
                    list.Add(Vertices[i].Position.Y);
                    list.Add(Vertices[i].Position.Z);
                    list.Add(Vertices[i].Normal.X);
                    list.Add(Vertices[i].Normal.Y);
                    list.Add(Vertices[i].Normal.Z);
                }

                float[] data = list.ToArray();
                GL.BufferData(BufferTarget.ArrayBuffer, sizeof(float) * data.Length, data, BufferUsageHint.StaticDraw);
            }
            else
            {
                sphereVao.Initialize(control);
                DefaultShaderProgram.Link(control);
            }
        }
Example #53
0
 /// <summary>
 /// Construye los Buffers correspondientes de OpenGL para dibujar este objeto.
 /// </summary>
 /// <param name="sProgram"></param>
 public void Build(ShaderProgram sProgram)
 {
     CrearVBOs();
     CrearVAO(sProgram);
 }
Example #54
0
        public void Parse(ShaderProgram prog, string line, bool ignoreMin)
        {
            //Debug.Log("Parsing instruction count: line = " + line);

            // String style:
            // "//   opengl - ALU: 29 to 35"
            // "//   opengl - ALU: 7 to 15, TEX: 1 to 3"

            string[] split = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (split.Length != 7 && split.Length != 11 && split.Length != 15)
            {
                Debug.LogError("Error parsing instruction count. Line did not have 7, 11 or 15 elements [" + line + "]. Length is: " + split.Length);
                return;
            }

            if (split[1] == "flash")
            {
                Debug.LogWarning("Flash is no longer supported by Unity, and was removed from the shader");
                return;
            }

            if (split[1] == "ps3")
            {
                Debug.LogWarning("PS3 is no longer supported by Unity since 5.5, and was removed from the shader");
                return;
            }

            if (split[1] == "xbox360")
            {
                Debug.LogWarning("Xbox 360 is no longer supported by Unity since 5.5, and was removed from the shader");
                return;
            }

            if (split[1] == "opengl")
            {
                split[1] = "glcore";
            }

            bool hasTex = (split.Length == 11);

            object enumObj = Enum.Parse(typeof(RenderPlatform), split[1]);

            int enumID;

            if (enumObj != null)
            {
                enumID = (int)enumObj;
            }
            else
            {
                return;
            }



            if (prog == ShaderProgram.Frag)
            {
                if (!ignoreMin)
                {
                    plats[enumID].frag.min = IntParse(split[4]);
                }
                plats[enumID].frag.max = IntParse(split[6]);
                if (hasTex)
                {
                    if (!ignoreMin)
                    {
                        plats[enumID].fTex.min = IntParse(split[8]);
                    }
                    plats[enumID].fTex.max = IntParse(split[10]);
                }
            }
            else if (prog == ShaderProgram.Vert)
            {
                if (!ignoreMin)
                {
                    plats[enumID].vert.min = IntParse(split[4]);
                }
                plats[enumID].vert.max = IntParse(split[6]);
                if (hasTex)
                {
                    if (!ignoreMin)
                    {
                        plats[enumID].vTex.min = IntParse(split[8]);
                    }
                    plats[enumID].vTex.max = IntParse(split[10]);
                }
            }
            else
            {
                Debug.LogError("Tried to parse things in invalid program [" + prog + "]");
            }

            //Debug.Log("Instr: " + split[1] + " "+ prog + " " + line + " ig: " + ignoreMin);
        }
Example #55
0
        /// <summary>
        /// Initialize the cache.
        /// </summary>
        internal void Initialize()
        {
            if (GraphicsConfig.EnableShaderCache && GraphicsConfig.TitleId != null)
            {
                _cacheManager = new CacheManager(CacheGraphicsApi.OpenGL, CacheHashType.XxHash128, "glsl", GraphicsConfig.TitleId, ShaderCodeGenVersion);

                bool isReadOnly = _cacheManager.IsReadOnly;

                HashSet <Hash128> invalidEntries = null;

                if (isReadOnly)
                {
                    Logger.Warning?.Print(LogClass.Gpu, "Loading shader cache in read-only mode (cache in use by another program!)");
                }
                else
                {
                    invalidEntries = new HashSet <Hash128>();
                }

                ReadOnlySpan <Hash128> guestProgramList = _cacheManager.GetGuestProgramList();

                using AutoResetEvent progressReportEvent = new AutoResetEvent(false);

                _shaderCount      = 0;
                _totalShaderCount = guestProgramList.Length;

                ShaderCacheStateChanged?.Invoke(ShaderCacheState.Start, _shaderCount, _totalShaderCount);
                Thread progressReportThread = null;

                if (guestProgramList.Length > 0)
                {
                    progressReportThread = new Thread(ReportProgress)
                    {
                        Name         = "ShaderCache.ProgressReporter",
                        Priority     = ThreadPriority.Lowest,
                        IsBackground = true
                    };

                    progressReportThread.Start(progressReportEvent);
                }

                // Make sure these are initialized before doing compilation.
                Capabilities caps = _context.Capabilities;

                int maxTaskCount = Math.Min(Environment.ProcessorCount, 8);
                int programIndex = 0;
                List <ShaderCompileTask> activeTasks = new List <ShaderCompileTask>();

                AutoResetEvent taskDoneEvent = new AutoResetEvent(false);

                // This thread dispatches tasks to do shader translation, and creates programs that OpenGL will link in the background.
                // The program link status is checked in a non-blocking manner so that multiple shaders can be compiled at once.

                while (programIndex < guestProgramList.Length || activeTasks.Count > 0)
                {
                    if (activeTasks.Count < maxTaskCount && programIndex < guestProgramList.Length)
                    {
                        // Begin a new shader compilation.
                        Hash128 key = guestProgramList[programIndex];

                        byte[] hostProgramBinary = _cacheManager.GetHostProgramByHash(ref key);
                        bool   hasHostCache      = hostProgramBinary != null;

                        IProgram hostProgram = null;

                        // If the program sources aren't in the cache, compile from saved guest program.
                        byte[] guestProgram = _cacheManager.GetGuestProgramByHash(ref key);

                        if (guestProgram == null)
                        {
                            Logger.Error?.Print(LogClass.Gpu, $"Ignoring orphan shader hash {key} in cache (is the cache incomplete?)");

                            // Should not happen, but if someone messed with the cache it's better to catch it.
                            invalidEntries?.Add(key);

                            _shaderCount = ++programIndex;

                            continue;
                        }

                        ReadOnlySpan <byte> guestProgramReadOnlySpan = guestProgram;

                        ReadOnlySpan <GuestShaderCacheEntry> cachedShaderEntries = GuestShaderCacheEntry.Parse(ref guestProgramReadOnlySpan, out GuestShaderCacheHeader fileHeader);

                        if (cachedShaderEntries[0].Header.Stage == ShaderStage.Compute)
                        {
                            Debug.Assert(cachedShaderEntries.Length == 1);

                            GuestShaderCacheEntry entry = cachedShaderEntries[0];

                            HostShaderCacheEntry[] hostShaderEntries = null;

                            // Try loading host shader binary.
                            if (hasHostCache)
                            {
                                hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan <byte> hostProgramBinarySpan);
                                hostProgramBinary = hostProgramBinarySpan.ToArray();
                                hostProgram       = _context.Renderer.LoadProgramBinary(hostProgramBinary);
                            }

                            ShaderCompileTask task = new ShaderCompileTask(taskDoneEvent);
                            activeTasks.Add(task);

                            task.OnCompiled(hostProgram, (bool isHostProgramValid, ShaderCompileTask task) =>
                            {
                                ShaderProgram program = null;
                                ShaderProgramInfo shaderProgramInfo = null;

                                if (isHostProgramValid)
                                {
                                    // Reconstruct code holder.

                                    program           = new ShaderProgram(entry.Header.Stage, "");
                                    shaderProgramInfo = hostShaderEntries[0].ToShaderProgramInfo();

                                    ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);

                                    _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));

                                    return(true);
                                }
                                else
                                {
                                    // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.

                                    Task compileTask = Task.Run(() =>
                                    {
                                        IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                        var options = CreateTranslationOptions(DefaultFlags | TranslationFlags.Compute);
                                        program     = Translator.CreateContext(0, gpuAccessor, options).Translate(out shaderProgramInfo);
                                    });

                                    task.OnTask(compileTask, (bool _, ShaderCompileTask task) =>
                                    {
                                        ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);

                                        Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");

                                        // Compile shader and create program as the shader program binary got invalidated.
                                        shader.HostShader = CompileShader(shader.Program, shader.Info);
                                        hostProgram       = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);

                                        task.OnCompiled(hostProgram, (bool isNewProgramValid, ShaderCompileTask task) =>
                                        {
                                            // As the host program was invalidated, save the new entry in the cache.
                                            hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });

                                            if (!isReadOnly)
                                            {
                                                if (hasHostCache)
                                                {
                                                    _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
                                                }
                                                else
                                                {
                                                    Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");

                                                    _cacheManager.AddHostProgram(ref key, hostProgramBinary);
                                                }
                                            }

                                            _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));

                                            return(true);
                                        });

                                        return(false); // Not finished: still need to compile the host program.
                                    });

                                    return(false); // Not finished: translating the program.
                                }
                            });
                        }
                        else
                        {
                            Debug.Assert(cachedShaderEntries.Length == Constants.ShaderStages);

                            ShaderCodeHolder[]   shaders        = new ShaderCodeHolder[cachedShaderEntries.Length];
                            List <ShaderProgram> shaderPrograms = new List <ShaderProgram>();

                            TransformFeedbackDescriptor[] tfd = CacheHelper.ReadTransformFeedbackInformation(ref guestProgramReadOnlySpan, fileHeader);

                            TranslationFlags flags = DefaultFlags;

                            if (tfd != null)
                            {
                                flags |= TranslationFlags.Feedback;
                            }

                            HostShaderCacheEntry[] hostShaderEntries = null;

                            // Try loading host shader binary.
                            if (hasHostCache)
                            {
                                hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan <byte> hostProgramBinarySpan);
                                hostProgramBinary = hostProgramBinarySpan.ToArray();
                                hostProgram       = _context.Renderer.LoadProgramBinary(hostProgramBinary);
                            }

                            ShaderCompileTask task = new ShaderCompileTask(taskDoneEvent);
                            activeTasks.Add(task);

                            GuestShaderCacheEntry[] entries = cachedShaderEntries.ToArray();

                            task.OnCompiled(hostProgram, (bool isHostProgramValid, ShaderCompileTask task) =>
                            {
                                Task compileTask = Task.Run(() =>
                                {
                                    // Reconstruct code holder.
                                    for (int i = 0; i < entries.Length; i++)
                                    {
                                        GuestShaderCacheEntry entry = entries[i];

                                        if (entry == null)
                                        {
                                            continue;
                                        }

                                        ShaderProgram program;

                                        if (entry.Header.SizeA != 0)
                                        {
                                            ShaderProgramInfo shaderProgramInfo;

                                            if (isHostProgramValid)
                                            {
                                                program           = new ShaderProgram(entry.Header.Stage, "");
                                                shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
                                            }
                                            else
                                            {
                                                IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                                var options  = CreateTranslationOptions(flags);
                                                var options2 = CreateTranslationOptions(flags | TranslationFlags.VertexA);

                                                TranslatorContext translatorContext  = Translator.CreateContext(0, gpuAccessor, options);
                                                TranslatorContext translatorContext2 = Translator.CreateContext((ulong)entry.Header.Size, gpuAccessor, options2);

                                                program = translatorContext.Translate(out shaderProgramInfo, translatorContext2);
                                            }

                                            // NOTE: Vertex B comes first in the shader cache.
                                            byte[] code  = entry.Code.AsSpan().Slice(0, entry.Header.Size).ToArray();
                                            byte[] code2 = entry.Code.AsSpan().Slice(entry.Header.Size, entry.Header.SizeA).ToArray();

                                            shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, code, code2);
                                        }
                                        else
                                        {
                                            ShaderProgramInfo shaderProgramInfo;

                                            if (isHostProgramValid)
                                            {
                                                program           = new ShaderProgram(entry.Header.Stage, "");
                                                shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
                                            }
                                            else
                                            {
                                                IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                                var options = CreateTranslationOptions(flags);
                                                program     = Translator.CreateContext(0, gpuAccessor, options).Translate(out shaderProgramInfo);
                                            }

                                            shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
                                        }

                                        shaderPrograms.Add(program);
                                    }
                                });

                                task.OnTask(compileTask, (bool _, ShaderCompileTask task) =>
                                {
                                    // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
                                    if (!isHostProgramValid)
                                    {
                                        Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");

                                        List <IShader> hostShaders = new List <IShader>();

                                        // Compile shaders and create program as the shader program binary got invalidated.
                                        for (int stage = 0; stage < Constants.ShaderStages; stage++)
                                        {
                                            ShaderProgram program = shaders[stage]?.Program;

                                            if (program == null)
                                            {
                                                continue;
                                            }

                                            IShader hostShader = CompileShader(program, shaders[stage].Info);;

                                            shaders[stage].HostShader = hostShader;

                                            hostShaders.Add(hostShader);
                                        }

                                        hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);

                                        task.OnCompiled(hostProgram, (bool isNewProgramValid, ShaderCompileTask task) =>
                                        {
                                            // As the host program was invalidated, save the new entry in the cache.
                                            hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);

                                            if (!isReadOnly)
                                            {
                                                if (hasHostCache)
                                                {
                                                    _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
                                                }
                                                else
                                                {
                                                    Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");

                                                    _cacheManager.AddHostProgram(ref key, hostProgramBinary);
                                                }
                                            }

                                            _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));

                                            return(true);
                                        });

                                        return(false); // Not finished: still need to compile the host program.
                                    }
                                    else
                                    {
                                        _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));

                                        return(true);
                                    }
                                });

                                return(false); // Not finished: translating the program.
                            });
                        }

                        _shaderCount = ++programIndex;
                    }

                    // Process the queue.
                    for (int i = 0; i < activeTasks.Count; i++)
                    {
                        ShaderCompileTask task = activeTasks[i];

                        if (task.IsDone())
                        {
                            activeTasks.RemoveAt(i--);
                        }
                    }

                    if (activeTasks.Count == maxTaskCount)
                    {
                        // Wait for a task to be done, or for 1ms.
                        // Host shader compilation cannot signal when it is done,
                        // so the 1ms timeout is required to poll status.

                        taskDoneEvent.WaitOne(1);
                    }
                }

                if (!isReadOnly)
                {
                    // Remove entries that are broken in the cache
                    _cacheManager.RemoveManifestEntries(invalidEntries);
                    _cacheManager.FlushToArchive();
                    _cacheManager.Synchronize();
                }

                progressReportEvent.Set();
                progressReportThread?.Join();

                ShaderCacheStateChanged?.Invoke(ShaderCacheState.Loaded, _shaderCount, _totalShaderCount);

                Logger.Info?.Print(LogClass.Gpu, $"Shader cache loaded {_shaderCount} entries.");
            }
        }
Example #56
0
        public ObjLoader(string filename, ShaderProgram program)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            this.shaderProgram = program;                            //Przypisanie programu(cieniujacego) do programu obecnego w tej klasie

            ObjMaterial defaultMaterial = new ObjMaterial(program);  //Stworzenie materialy na podstawie przekazanego programu

            using (StreamReader stream = new StreamReader(filename)) //dzieki using mamy pewnosc ze po wyjsciu z tego bloku, obiekt stream zostanie zwolniony
            {
                List <string> lines = new List <string>();           //tworzenie listy stringow
                List <string> objLines = new List <string>();        //tworzenie listy stringow
                int           vertexOffset = 1, vertexCount = 0;     //liczniki vertexow
                int           uvOffset = 1, uvCount = 0;             //liczniki uv

                while (!stream.EndOfStream)                          //czytanie pliku az do jego konca
                {
                    string line = stream.ReadLine();                 //kazda kolejna linia
                    if (line.Trim().Length == 0)
                    {
                        continue;                          //jesli w lini po usunieciu bialych znakow, liczba znakow jest rowna 0 to przejdz do nastepnego obrotu petli
                    }
                    if ((line[0] == 'o' && lines.Count != 0) || (line[0] == 'g' && objLines.Count != 0))
                    {
                        List <string> combinedLines = new List <string>(objLines);
                        combinedLines.AddRange(lines);

                        ObjObject newObject = new ObjObject(combinedLines, materials, vertexOffset, uvOffset);
                        if (newObject.VertexCount != 0)
                        {
                            objects.Add(newObject);
                        }

                        if (newObject.Material == null)
                        {
                            newObject.Material = defaultMaterial;
                        }

                        lines.Clear();
                        if (line[0] == 'o')
                        {
                            objLines.Clear();
                            vertexOffset += vertexCount;
                            uvOffset     += uvCount;
                            vertexCount   = 0;
                            uvCount       = 0;
                        }
                    }

                    if (line[0] == 'v') //zliczenie wystapien vertexow lub uv
                    {
                        if (line[1] == ' ')
                        {
                            vertexCount++;
                        }
                        else
                        {
                            uvCount++;
                        }

                        objLines.Add(line);
                    }
                    else if (line[0] != '#')
                    {
                        lines.Add(line);                      //Pomijanie komenatrzy
                    }
                    if (line[0] == 'm' && line[1] == 't')
                    {
                        LoadMaterials(CreateFixedPath(filename, line.Split(' ')[1]));                                   //sprawdzenie czy obiekt korzysta z pliku z materialem
                    }
                }

                if (lines != null) //Sprawdzenie czy na pewno wszystko zostalo zaimportowane
                {
                    List <string> combinedLines = new List <string>(objLines);
                    combinedLines.AddRange(lines);

                    ObjObject newObject = new ObjObject(combinedLines, materials, vertexOffset, uvOffset);
                    objects.Add(newObject);
                }
            }

            Console.WriteLine("Wykonano funckje ObjLoader");
        }
Example #57
0
 protected override void GenEmit(ShaderProgram Program, uint InstOp)
 {
     SB.AppendLine($"{Ident}gl_Position = {ShaderOutputRegName.Position};");
     SB.AppendLine($"{Ident}EmitVertex();");
 }
Example #58
0
        public Shader GetComputeShader(

            ulong gpuVa,
            int localSizeX,
            int localSizeY,
            int localSizeZ,
            int localMemorySize,
            int sharedMemorySize)
        {
            if (gpuVa == 0)
            {
                return null;
            }

            ShaderPack pack = new ShaderPack();

            ReadOnlySpan<byte> code = GetShaderCodeHeaderless(gpuVa);

            pack.Add(code);

            Shader cs = _cache.Get(pack, out int hash);

            if (cs != null)
            {
                return cs;
            }

            _dumper.Dump(code, compute: true, out string fullPath, out string codePath);

            int QueryInfo(QueryInfoName info, int index)
            {
                return info switch
                {
                    QueryInfoName.ComputeLocalSizeX => localSizeX,
                    QueryInfoName.ComputeLocalSizeY => localSizeY,
                    QueryInfoName.ComputeLocalSizeZ => localSizeZ,
                    QueryInfoName.ComputeLocalMemorySize => localMemorySize,
                    QueryInfoName.ComputeSharedMemorySize => sharedMemorySize,
                    _ => QueryInfoCommon(info)
                };
            }


            CachedShader shader = TranslateComputeShader(
                state,
                gpuVa,
                localSizeX,
                localSizeY,
                localSizeZ,
                localMemorySize,
                sharedMemorySize);

            TranslatorCallbacks callbacks = new TranslatorCallbacks(QueryInfo, PrintLog);


            ShaderProgram program = Translator.Translate(code, callbacks, DefaultFlags | TranslationFlags.Compute);

            if (fullPath != null && codePath != null)
            {
                program.Prepend("// " + codePath);
                program.Prepend("// " + fullPath);
            }

            IShader shader = _context.Renderer.CompileShader(program);

            IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader });

            cs = new Shader(hostProgram, new ShaderMeta(hostProgram, program.Info));

            int insertIndex = _cache.Add(hash, cs, pack);

            if (Configuration.Enabled)
            {
                ShaderProgramInfo[] info = new ShaderProgramInfo[] { program.Info };

                ShaderCacheFile.Save(Configuration.ShaderPath, info, pack, hostProgram.GetGpuBinary(), hash, insertIndex);
            }

            return cs;
        }
Example #59
0
        static void Main(string[] args)
        {
            Glut.glutInit();
            Glut.glutInitDisplayMode(Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH);
            Glut.glutInitWindowSize(width, height);
            Glut.glutCreateWindow("Project");

            Glut.glutIdleFunc(OnRenderFrame);
            Glut.glutDisplayFunc(OnDisplay);
            Glut.glutKeyboardFunc(OnKeyboardDown);
            Glut.glutKeyboardFunc(OnKeyboardUp);
            Glut.glutCloseFunc(OnClose);
            Glut.glutReshapeFunc(OnReshape);

            Gl.Enable(EnableCap.DepthTest);

            //program = new ShaderProgram(VertexShader, FragmentShader);
            program = new ShaderProgram(VertexShaderTexture, FragmentShaderTexture);

            program.Use();
            program["projection_matrix"].SetValue(Matrix4.CreatePerspectiveFieldOfView(0.45f, (float)width / height, 0.1f, 1000f));
            program["view_matrix"].SetValue(Matrix4.LookAt(new Vector3(0, 0, 10), Vector3.Zero, new Vector3(0, 1, 0)));

            program["light_direction"].SetValue(new Vector3(0, 1, 1));
            //program["light_direction2"].SetValue(new Vector3(0, 0, 1));
            program["enable_lighting"].SetValue(lighting);

            //load texture
            crateTexture = new Texture("texture2.jpg");

            //create cube vertices
            cube = new VBO <Vector3>(new Vector3[] {
                new Vector3(1, 1, -1), new Vector3(-1, 1, -1), new Vector3(-1, 1, 1), new Vector3(1, 1, 1),     //top
                new Vector3(1, -1, 1), new Vector3(-1, -1, 1), new Vector3(-1, -1, -1), new Vector3(1, -1, -1), //bottom
                new Vector3(1, 1, 1), new Vector3(-1, 1, 1), new Vector3(-1, -1, 1), new Vector3(1, -1, 1),     //front
                new Vector3(1, -1, -1), new Vector3(-1, -1, -1), new Vector3(-1, 1, -1), new Vector3(1, 1, -1), //back
                new Vector3(-1, 1, 1), new Vector3(-1, 1, -1), new Vector3(-1, -1, -1), new Vector3(-1, -1, 1), //left
                new Vector3(1, 1, -1), new Vector3(1, 1, 1), new Vector3(1, -1, 1), new Vector3(1, -1, -1)      //right
            });
            //cube normals
            cubeNormals = new VBO <Vector3>(new Vector3[] {
                new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0),
                new Vector3(0, -1, 0), new Vector3(0, -1, 0), new Vector3(0, -1, 0), new Vector3(0, -1, 0),
                new Vector3(0, 0, 1), new Vector3(0, 0, 1), new Vector3(0, 0, 1), new Vector3(0, 0, 1),
                new Vector3(0, 0, -1), new Vector3(0, 0, -1), new Vector3(0, 0, -1), new Vector3(0, 0, -1),
                new Vector3(-1, 0, 0), new Vector3(-1, 0, 0), new Vector3(-1, 0, 0), new Vector3(-1, 0, 0),
                new Vector3(1, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 0, 0)
            });
            //texture for cube
            cubeUV = new VBO <Vector2>(new Vector2[] {
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1)
            });

            cubeElements = new VBO <int>(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
                                                     21, 22, 23 }, BufferTarget.ElementArrayBuffer);

            Glut.glutMainLoop();
        }
Example #60
0
 public void RenderBeforeChildren(RenderEventArgs arg)
 {
     {
         int width = arg.Param.Viewport.width, height = arg.Param.Viewport.height;
         if (width != this.canvasWidth || height != this.canvasHeight)
         {
             UpdateResources(width, height);
             this.canvasWidth  = width;
             this.canvasHeight = height;
         }
     }
     {
         this.cullFaceState.On();
         this.depthTestState.On();
     }
     {
         // Clear head-pointer image
         this.headClearBuffer.Bind();
         this.headTexture.Bind();
         int  width = this.canvasWidth, height = this.canvasHeight;
         uint format = GL.GL_RED_INTEGER, type = GL.GL_UNSIGNED_BYTE;
         GL.Instance.TexSubImage2D((uint)GL.GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, IntPtr.Zero);
         this.headTexture.Unbind();
         this.headClearBuffer.Unbind();
     }
     uint imageUnit0 = 0, imageUnit1 = 1;
     {
         // Bind head-pointer image for read-write
         glBindImageTexture(imageUnit0, this.headTexture.Id, 0, false, 0, GL.GL_READ_WRITE, GL.GL_R32UI);
         // Bind linked-list buffer for write
         glBindImageTexture(imageUnit1, this.linkedListTexture.Id, 0, false, 0, GL.GL_WRITE_ONLY, GL.GL_RGBA32UI);
     }
     {
         ICamera camera     = arg.Camera;
         mat4    projection = camera.GetProjectionMatrix();
         mat4    view       = camera.GetViewMatrix();
         mat4    model      = this.GetModelMatrix();
         {
             // first pass
             RenderMethod  method  = this.RenderUnit.Methods[buildLists];
             ShaderProgram program = method.Program;
             program.SetUniform(mvpMatrix, projection * view * model);
             method.Render();
         }
         {
             // second pass
             RenderMethod  method  = this.RenderUnit.Methods[resolveLists];
             ShaderProgram program = method.Program;
             program.SetUniform(mvpMatrix, projection * view * model);
             method.Render();
         }
     }
     {
         glBindImageTexture(imageUnit1, 0, 0, false, 0, GL.GL_WRITE_ONLY, GL.GL_RGBA32UI);
         glBindImageTexture(imageUnit0, 0, 0, false, 0, GL.GL_READ_WRITE, GL.GL_R32UI);
     }
     {
         this.cullFaceState.Off();
         this.depthTestState.Off();
     }
 }