Beispiel #1
0
        public static Texture LoadTexture(string name)
        {
            var path = Path.Combine(RootPath, "textures/", name);
            var mem  = MemoryBlock.FromArray(File.ReadAllBytes(path));

            return(Texture.FromFile(mem, TextureFlags.None, 0));
        }
Beispiel #2
0
        public static Shader LoadShader(string name)
        {
            var path = Path.Combine(GetShaderPath(), name) + ".bin";
            var mem  = MemoryBlock.FromArray(File.ReadAllBytes(path));

            return(new Shader(mem));
        }
Beispiel #3
0
        internal IndexBuffer CreateIndexBuffer(ushort[] indices)
        {
            var index_buffer = new IndexBuffer(MemoryBlock.FromArray(indices));

            index_buffers[index_buffers_idx++] = index_buffer;

            return(index_buffer);
        }
Beispiel #4
0
        public unsafe static Mesh LoadMesh(string fileName)
        {
            var          path   = Path.Combine(RootPath, "meshes/", fileName);
            var          groups = new List <MeshGroup>();
            var          group  = new MeshGroup();
            VertexLayout layout = null;

            using (var reader = new MemoryReader(File.ReadAllBytes(path))) {
                while (!reader.Done)
                {
                    var tag = reader.Read <uint>();
                    if (tag == ChunkTagVB)
                    {
                        // skip bounding volume info
                        reader.Skip(BoundingVolumeSize);

                        layout = ReadVertexLayout(reader);

                        var vertexCount = reader.Read <ushort>();
                        var vertexData  = reader.ReadArray <byte>(vertexCount * layout.Stride);
                        group.VertexBuffer = new VertexBuffer(MemoryBlock.FromArray(vertexData), layout);
                    }
                    else if (tag == ChunkTagIB)
                    {
                        var indexCount = reader.Read <uint>();
                        var indexData  = reader.ReadArray <ushort>((int)indexCount);

                        group.IndexBuffer = new IndexBuffer(MemoryBlock.FromArray(indexData));
                    }
                    else if (tag == ChunkTagPri)
                    {
                        // skip material name
                        var len = reader.Read <ushort>();
                        reader.Skip(len);

                        // read primitive data
                        var count = reader.Read <ushort>();
                        for (int i = 0; i < count; i++)
                        {
                            // skip name
                            len = reader.Read <ushort>();
                            reader.Skip(len);

                            var prim = reader.Read <Primitive>();
                            group.Primitives.Add(prim);

                            // skip bounding volumes
                            reader.Skip(BoundingVolumeSize);
                        }

                        groups.Add(group);
                        group = new MeshGroup();
                    }
                }
            }
            return(new Mesh(layout, groups));
        }
Beispiel #5
0
        public Texture2D(string path, TextureFlags flags = TextureFlags.None, TextureFormat format = TextureFormat.BGRA8)
        {
#if DEBUG
            this.path = System.IO.Path.GetFileNameWithoutExtension(path);
#endif
            int    width, height, bytesPerPixel;
            byte[] data = FFmpegHelper.ImageFromFile(path, out width, out height, out bytesPerPixel);
            handle = Texture.Create2D(width, height, 0, format, flags, MemoryBlock.FromArray(data));
        }
Beispiel #6
0
        Shader LoadShader(string fileName)
        {
            var filePath = System.IO.Path.Combine(NSBundle.MainBundle.ResourcePath, "shaders", "metal", fileName);
            var file     = File.OpenRead(filePath);
            var buffer   = new byte[file.Length];

            file.Read(buffer, 0, (int)file.Length);
            return(new Shader(MemoryBlock.FromArray(buffer)));
        }
Beispiel #7
0
        private void ImplInitialize(byte[] vertex_src, byte[] frag_src, IReadOnlyList <string> samplers, IReadOnlyList <string> @params)
        {
            var vertex_shader = new Shader(MemoryBlock.FromArray(vertex_src));
            var frag_shader   = new Shader(MemoryBlock.FromArray(frag_src));

            this.Program = new Program(vertex_shader, frag_shader, true);

            BuildSamplersList(samplers);

            BuildParametersList(@params);
        }
Beispiel #8
0
        private void ImplInitialize()
        {
            index_buffer = new IndexBuffer(MemoryBlock.FromArray(indices));

            base_render_state = RenderState.WriteRGB | RenderState.WriteA;

            blending_state = RenderState.BlendFunction(RenderState.BlendSourceAlpha,
                                                       RenderState.BlendInverseSourceAlpha);

            render_state = base_render_state | blending_state;
        }
Beispiel #9
0
        public Mesh(MemoryBlock vertices, VertexLayout decl, ushort[] indices)
        {
            var group = new MeshGroup();

            group.VertexBuffer = new VertexBuffer(vertices, decl);
            group.IndexBuffer  = new IndexBuffer(MemoryBlock.FromArray(indices));

            vertexDecl = decl;
            groups     = new List <MeshGroup> {
                group
            };
        }
Beispiel #10
0
        unsafe static void RenderThread(Window window)
        {
            // initialize the renderer
            Bgfx.Init();
            Bgfx.Reset(window.Width, window.Height, ResetFlags.Vsync);
            Bgfx.SetDebugFeatures(DebugFeatures.DisplayText);
            Bgfx.SetViewClear(0, ClearTargets.Color | ClearTargets.Depth, unchecked ((int)0xffffffff));

            var fontProgram = new Program(
                new Shader(MemoryBlock.FromArray(Shaders.FontVS)),
                new Shader(MemoryBlock.FromArray(Shaders.FontFS)),
                destroyShaders: true
                );

            var u_texColor = new Uniform("u_texColor", UniformType.Int1);
            var atlas      = new TextureAtlas(4096);

            var font     = FontCollection.SystemFonts.Load("Verdana");
            var analyzer = new TextAnalyzer(atlas);
            var buffer   = new TextBuffer(12800);

            //buffer.Append(analyzer, font, "m");
            //buffer.Append(analyzer, font, "Hello, World! (¼)");


            buffer.Append(analyzer, font,
                          @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus congue vitae augue sit amet laoreet. Etiam eros ligula, vestibulum non nisi a, convallis sodales odio. Integer dapibus ipsum eros, sit amet euismod ligula fringilla quis. Pellentesque placerat, dui vitae venenatis aliquam, augue eros porttitor erat, sit amet imperdiet dolor nulla nec justo. Etiam at elit vel diam consectetur venenatis vel et eros. In leo ante, vestibulum eu volutpat a, facilisis et justo. Sed semper arcu id lectus faucibus, ac pretium nunc sagittis. Praesent faucibus eu nisl non lacinia. Suspendisse suscipit vulputate velit, non sodales augue. In ante nulla, tempus vitae nisi tincidunt, dignissim venenatis elit. Phasellus fermentum turpis sed sapien dapibus, quis varius leo mattis. Nam nisl nibh, eleifend in maximus ac, ultricies ut eros.

Phasellus auctor magna erat, iaculis interdum purus porta vulputate. Etiam vel neque at justo dictum tincidunt. Etiam enim nibh, dapibus accumsan blandit suscipit, dignissim vitae quam. Duis at metus et nulla posuere malesuada ut at urna. Quisque eget arcu venenatis, gravida tellus volutpat, vehicula tellus. Pellentesque rutrum purus vel ante sodales sollicitudin. Phasellus ut elit blandit, maximus ipsum ut, varius nisi.

Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Quisque volutpat in lectus sit amet pharetra. In mi justo, maximus sit amet viverra nec, posuere vel leo. Phasellus in justo quis ex semper suscipit. Pellentesque ut ornare purus.Donec et pretium metus. Integer dapibus est a nibh convallis pulvinar. Mauris metus diam, congue eget arcu volutpat, varius vehicula sapien. Donec posuere, massa et fringilla tincidunt, lacus ante fermentum sapien, ut dictum tellus erat id quam.Donec tempus urna velit, ac congue nibh egestas luctus. Praesent vel leo at enim imperdiet maximus non nec massa.

Pellentesque auctor ultricies accumsan. Vestibulum ipsum mi, tincidunt ut lacinia et, lobortis in lacus. Donec eu velit imperdiet, viverra mi ut, congue tortor. Vestibulum ac dui pretium, interdum tortor a, varius nulla. Nunc consequat neque sed sodales sagittis. Nullam condimentum metus sit amet sapien elementum, a pulvinar eros cursus. Sed eget elit tellus. Fusce ac pellentesque orci. Nullam sagittis malesuada elit, sed dignissim nibh sollicitudin malesuada. Mauris ac hendrerit enim. Aliquam ex urna, sagittis varius ex eu, commodo consequat tortor.

Praesent varius mauris sed lacus congue sollicitudin. Nulla lectus nunc, euismod id nibh quis, sollicitudin imperdiet neque. Maecenas suscipit quam sit amet venenatis cursus. Donec lacinia interdum rutrum. Phasellus quis odio justo. Duis sed justo quis quam rutrum consequat. Praesent et suscipit magna, eu condimentum mauris.Mauris in ligula odio. Integer tincidunt nisi et ipsum efficitur rutrum.");

            Bgfx.SetViewTransform(0, Matrix4x4.Identity, Matrix4x4.CreateOrthographicOffCenter(0, 1280, 720, 0, -1.0f, 1.0f));

            // main loop
            while (window.ProcessEvents(ResetFlags.Vsync))
            {
                Bgfx.SetViewRect(0, 0, 0, window.Width, window.Height);

                Bgfx.SetTexture(0, u_texColor, atlas.Texture);
                Bgfx.SetProgram(fontProgram);
                buffer.Submit();

                Bgfx.Frame();
            }

            // cleanup
            Bgfx.Shutdown();
        }
Beispiel #11
0
        private void ImplInitialize(Pixmap pixmap)
        {
            this.ImplUpdateTexProperties();

            this.Texture = Texture.Create2D(
                pixmap.Width,
                pixmap.Height,
                false,
                0,
                TextureFormat.BGRA8,
                TexFlags,
                MemoryBlock.FromArray(pixmap.PixelData)
                );
        }
Beispiel #12
0
        public ShaderProgram(string pathVS, string pathFS)
        {
            if (!File.Exists(pathVS))
            {
                throw new FileNotFoundException("Failed to create ShaderProgram, shader not found: " + pathVS);
            }
            else if (!File.Exists(pathFS))
            {
                throw new FileNotFoundException("Failed to create ShaderProgram, shader not found: " + pathFS);
            }

            programHandle = new SharpBgfx.Program(
                new SharpBgfx.Shader(MemoryBlock.FromArray(File.ReadAllBytes(pathVS))),
                new SharpBgfx.Shader(MemoryBlock.FromArray(File.ReadAllBytes(pathFS))), true);
        }
Beispiel #13
0
        internal ShaderProgram CreateShader(byte[] vertex_src, byte[] frag_src, string[] samplers, string[] _params)
        {
            if (vertex_src.Length == 0 || frag_src.Length == 0)
            {
                throw new Exception("Cannot load ShaderProgram with empty shader sources");
            }

            var vertex_shader = new Shader(MemoryBlock.FromArray(vertex_src));
            var frag_shader   = new Shader(MemoryBlock.FromArray(frag_src));

            var program = new Program(vertex_shader, frag_shader, true);

            var shader_program = new ShaderProgram(program, samplers, _params);

            return(shader_program);
        }
Beispiel #14
0
        public void InitRenderer(MTKView view, IMTLDevice device)
        {
#if BGFX
            var platformData = new PlatformData();
            platformData.WindowHandle = view.Handle;
            platformData.Context      = device.Handle;

            Bgfx.Bgfx.SetPlatformData(platformData);

            var settings = new InitSettings();
            settings.Backend      = RendererBackend.Metal;
            settings.Width        = (int)view.Bounds.Width;
            settings.Height       = (int)view.Bounds.Height;
            settings.ResetFlags   = ResetFlags.Vsync;
            settings.PlatformData = platformData;
            //settings.limits.maxEncoders = 128;

            Bgfx.Bgfx.ManuallyRenderFrame();
            Bgfx.Bgfx.Init(settings);

            var vertexLayout = new VertexLayout();
            vertexLayout.Begin(RendererBackend.Metal);
            vertexLayout.Add(VertexAttributeUsage.Position, 3, VertexAttributeType.Float);
            vertexLayout.Add(VertexAttributeUsage.Color0, 4, VertexAttributeType.UInt8, true);
            vertexLayout.End();

            var vertexBuffer = new VertexBuffer(MemoryBlock.FromArray(Data.cubeVertices), vertexLayout);
            var indexBuffer  = new IndexBuffer(MemoryBlock.FromArray(Data.cubeTriList));

            var vertexShader   = LoadShader("vs_cubes.bin");
            var fragmentShader = LoadShader("fs_cubes.bin");
            var program        = new Program(vertexShader, fragmentShader);


            _vertexBuffer = vertexBuffer;
            _indexBuffer  = indexBuffer;
            _program      = program;

            Bgfx.Bgfx.Touch(0);
#endif
            view.Delegate = this;
        }
Beispiel #15
0
        internal Texture2D CreateTexture(Pixmap pixmap, bool tiled, bool filtered,
                                         bool render_target = false)
        {
            var tex_flags = Texture2D.BuildTexFlags(tiled, filtered, render_target);

            var tex_object = Texture.Create2D(
                pixmap.Width,
                pixmap.Height,
                false,
                0,
                TextureFormat.BGRA8,
                tex_flags,
                MemoryBlock.FromArray(pixmap.PixelData)
                );


            var tex_2d = new Texture2D(tex_object, render_target, filtered, tiled);

            //UpdateTextureData(tex_2d, pixmap);

            return(tex_2d);
        }
Beispiel #16
0
    static unsafe void RunCompute(Sample sample, bool indirectSupported)
    {
        // build vertex layouts
        var quadLayout = new VertexLayout();

        quadLayout.Begin()
        .Add(VertexAttributeUsage.Position, 2, VertexAttributeType.Float)
        .End();

        var computeLayout = new VertexLayout();

        computeLayout.Begin()
        .Add(VertexAttributeUsage.TexCoord0, 4, VertexAttributeType.Float)
        .End();

        // static quad data
        var vb = new VertexBuffer(MemoryBlock.FromArray(QuadVertices), quadLayout);
        var ib = new IndexBuffer(MemoryBlock.FromArray(QuadIndices));

        // create compute buffers
        var currPositionBuffer0 = new DynamicVertexBuffer(1 << 15, computeLayout, BufferFlags.ComputeReadWrite);
        var currPositionBuffer1 = new DynamicVertexBuffer(1 << 15, computeLayout, BufferFlags.ComputeReadWrite);
        var prevPositionBuffer0 = new DynamicVertexBuffer(1 << 15, computeLayout, BufferFlags.ComputeReadWrite);
        var prevPositionBuffer1 = new DynamicVertexBuffer(1 << 15, computeLayout, BufferFlags.ComputeReadWrite);

        // load shaders
        var particleProgram        = ResourceLoader.LoadProgram("vs_particle", "fs_particle");
        var initInstancesProgram   = ResourceLoader.LoadProgram("cs_init_instances");
        var updateInstancesProgram = ResourceLoader.LoadProgram("cs_update_instances");

        // indirect rendering support
        var  indirectProgram = SharpBgfx.Program.Invalid;
        var  indirectBuffer  = IndirectBuffer.Invalid;
        bool useIndirect     = false;

        if (indirectSupported)
        {
            indirectProgram = ResourceLoader.LoadProgram("cs_indirect");
            indirectBuffer  = new IndirectBuffer(2);
            useIndirect     = true;
        }

        // setup params uniforms
        var paramData = new ParamsData {
            TimeStep          = 0.0157f,
            DispatchSize      = 32,
            Gravity           = 0.109f,
            Damping           = 0.25f,
            ParticleIntensity = 0.64f,
            ParticleSize      = 0.279f,
            BaseSeed          = 57,
            ParticlePower     = 3.5f,
            InitialSpeed      = 3.2f,
            InitialShape      = 1,
            MaxAccel          = 100.0f
        };

        // have the compute shader run initialization
        var u_params = new Uniform("u_params", UniformType.Vector4, 3);

        Bgfx.SetUniform(u_params, &paramData, 3);
        Bgfx.SetComputeBuffer(0, prevPositionBuffer0, ComputeBufferAccess.Write);
        Bgfx.SetComputeBuffer(1, currPositionBuffer0, ComputeBufferAccess.Write);
        Bgfx.Dispatch(0, initInstancesProgram, MaxParticleCount / ThreadGroupUpdateSize);

        // start the frame clock
        var clock = new Clock();

        clock.Start();

        // main loop
        while (sample.ProcessEvents(ResetFlags.Vsync))
        {
            // tick the clock
            var elapsed = clock.Frame();
            var time    = clock.TotalTime();

            // write some debug text
            Bgfx.DebugTextClear();
            Bgfx.DebugTextWrite(0, 1, DebugColor.White, DebugColor.Blue, "SharpBgfx/Samples/24-NBody");
            Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Cyan, "Description: N-body simulation with compute shaders using buffers.");
            Bgfx.DebugTextWrite(0, 3, DebugColor.White, DebugColor.Cyan, "Frame: {0:F3} ms", elapsed * 1000);

            // fill the indirect buffer if we're using it
            if (useIndirect)
            {
                Bgfx.SetUniform(u_params, &paramData, 3);
                Bgfx.SetComputeBuffer(0, indirectBuffer, ComputeBufferAccess.Write);
                Bgfx.Dispatch(0, indirectProgram);
            }

            // update particle positions
            Bgfx.SetComputeBuffer(0, prevPositionBuffer0, ComputeBufferAccess.Read);
            Bgfx.SetComputeBuffer(1, currPositionBuffer0, ComputeBufferAccess.Read);
            Bgfx.SetComputeBuffer(2, prevPositionBuffer1, ComputeBufferAccess.Write);
            Bgfx.SetComputeBuffer(3, currPositionBuffer1, ComputeBufferAccess.Write);
            Bgfx.SetUniform(u_params, &paramData, 3);
            if (useIndirect)
            {
                Bgfx.Dispatch(0, updateInstancesProgram, indirectBuffer, 1);
            }
            else
            {
                Bgfx.Dispatch(0, updateInstancesProgram, paramData.DispatchSize);
            }

            // ping-pong the buffers for next frame
            Swap(ref currPositionBuffer0, ref currPositionBuffer1);
            Swap(ref prevPositionBuffer0, ref prevPositionBuffer1);

            // view transforms for particle rendering
            var viewMatrix = Matrix4x4.CreateLookAt(new Vector3(0.0f, 0.0f, -45.0f), -Vector3.UnitZ, Vector3.UnitY);
            var projMatrix = Matrix4x4.CreatePerspectiveFieldOfView((float)Math.PI / 4, (float)sample.WindowWidth / sample.WindowHeight, 0.1f, 10000.0f);
            Bgfx.SetViewTransform(0, &viewMatrix.M11, &projMatrix.M11);
            Bgfx.SetViewRect(0, 0, 0, sample.WindowWidth, sample.WindowHeight);

            // draw the particles
            Bgfx.SetVertexBuffer(vb);
            Bgfx.SetIndexBuffer(ib);
            Bgfx.SetInstanceDataBuffer(currPositionBuffer0, 0, paramData.DispatchSize * ThreadGroupUpdateSize);
            Bgfx.SetRenderState(RenderState.ColorWrite | RenderState.BlendAdd | RenderState.DepthTestAlways);
            if (useIndirect)
            {
                Bgfx.Submit(0, particleProgram, indirectBuffer);
            }
            else
            {
                Bgfx.Submit(0, particleProgram);
            }

            // done with frame
            Bgfx.Frame();
        }

        // cleanup
        if (indirectSupported)
        {
            indirectProgram.Dispose();
            indirectBuffer.Dispose();
        }

        u_params.Dispose();
        currPositionBuffer0.Dispose();
        currPositionBuffer1.Dispose();
        prevPositionBuffer0.Dispose();
        prevPositionBuffer1.Dispose();
        updateInstancesProgram.Dispose();
        initInstancesProgram.Dispose();
        particleProgram.Dispose();
        ib.Dispose();
        vb.Dispose();
    }
Beispiel #17
0
    static unsafe void RenderThread(Sample sample)
    {
        // initialize the renderer
        Bgfx.Init();
        Bgfx.Reset(sample.WindowWidth, sample.WindowHeight, ResetFlags.Vsync);

        // enable debug text
        Bgfx.SetDebugFeatures(DebugFeatures.DisplayText);

        // load shaders
        var programTextureLighting = ResourceLoader.LoadProgram("vs_stencil_texture_lighting", "fs_stencil_texture_lighting");
        var programColorLighting   = ResourceLoader.LoadProgram("vs_stencil_color_lighting", "fs_stencil_color_lighting");
        var programColorTexture    = ResourceLoader.LoadProgram("vs_stencil_color_texture", "fs_stencil_color_texture");
        var programColorBlack      = ResourceLoader.LoadProgram("vs_stencil_color", "fs_stencil_color_black");
        var programTexture         = ResourceLoader.LoadProgram("vs_stencil_texture", "fs_stencil_texture");

        // load meshes
        var bunnyMesh  = ResourceLoader.LoadMesh("bunny.bin");
        var columnMesh = ResourceLoader.LoadMesh("column.bin");
        var hplaneMesh = new Mesh(MemoryBlock.FromArray(StaticMeshes.HorizontalPlane), PosNormalTexcoordVertex.Layout, StaticMeshes.PlaneIndices);
        var vplaneMesh = new Mesh(MemoryBlock.FromArray(StaticMeshes.VerticalPlane), PosNormalTexcoordVertex.Layout, StaticMeshes.PlaneIndices);

        // load textures
        var figureTex     = ResourceLoader.LoadTexture("figure-rgba.dds");
        var flareTex      = ResourceLoader.LoadTexture("flare.dds");
        var fieldstoneTex = ResourceLoader.LoadTexture("fieldstone-rgba.dds");

        // create uniforms
        var colorTextureHandle = new Uniform("u_texColor", UniformType.Sampler);
        var uniforms           = new Uniforms();

        uniforms.SubmitConstUniforms();

        // light colors
        uniforms.LightColor = new[] {
            new Vector4(1.0f, 0.7f, 0.2f, 0.0f), // yellow
            new Vector4(0.7f, 0.2f, 1.0f, 0.0f), // purple
            new Vector4(0.2f, 1.0f, 0.7f, 0.0f), // cyan
            new Vector4(1.0f, 0.4f, 0.2f, 0.0f)  // orange
        };

        // camera
        var camera = new Camera(60.0f, sample.WindowWidth, sample.WindowHeight, 0.1f, 100.0f);

        camera.Position = new Vector3(0.0f, 18.0f, -40.0f);

        // start the frame clock
        var clock = new Clock();

        clock.Start();

        // check caps and stats, for testing purposes
        Bgfx.GetCaps();
        Bgfx.GetStats();

        // main loop
        while (sample.ProcessEvents(ResetFlags.Vsync))
        {
            // tick the clock
            var elapsed = clock.Frame();
            var time    = clock.TotalTime();

            // write some debug text
            Bgfx.DebugTextClear();
            Bgfx.DebugTextWrite(0, 1, DebugColor.White, DebugColor.Blue, "SharpBgfx/Samples/13-Stencil");
            Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Cyan, "Description: Stencil reflections.");
            Bgfx.DebugTextWrite(0, 3, DebugColor.White, DebugColor.Cyan, "Frame: {0:F3} ms", elapsed * 1000);

            // clear the background
            Bgfx.SetViewClear(BaseId, ClearTargets.Color | ClearTargets.Depth | ClearTargets.Stencil, 0x30303000);
            Bgfx.SetViewRect(BaseId, 0, 0, sample.WindowWidth, sample.WindowHeight);
            Bgfx.Touch(BaseId);

            // set view params for each pass
            var viewMtx = camera.GetViewMatrix();
            var projMtx = camera.GetProjectionMatrix();
            for (byte i = PassId0; i <= PassId4; i++)
            {
                Bgfx.SetViewRect(i, 0, 0, sample.WindowWidth, sample.WindowHeight);
                Bgfx.SetViewTransform(i, (float *)&viewMtx, (float *)&projMtx);
            }

            // first pass - draw ground plane
            var floorMtx = FloorTransform;
            hplaneMesh.Submit(PassId0, programColorBlack, &floorMtx, StateGroups[PrebuiltRenderState.StencilReflectionCraftStencil], uniforms);

            // second pass - reflected objects
            Bgfx.SetViewClear(PassId1, ClearTargets.Depth, 0);
            uniforms.AmbientPass  = true;
            uniforms.LightingPass = true;
            uniforms.Color        = new Vector4(0.70f, 0.65f, 0.60f, 0.8f);
            uniforms.LightCount   = LightCount;

            // light positions
            var lightPositions  = new Vector4[LightCount];
            var reflectedLights = new Vector4[LightCount];
            for (int i = 0; i < lightPositions.Length; i++)
            {
                var v3 = new Vector3(
                    (float)Math.Sin(time * 1.1 + i * 0.03 + i * 1.07 * Math.PI / 2) * 20.0f,
                    8.0f + (1.0f - (float)Math.Cos(time * 1.5 + i * 0.29 + 1.49f * Math.PI / 2)) * 4.0f,
                    (float)Math.Cos(time * 1.3 + i * 0.13 + i * 1.79 * Math.PI / 2) * 20.0f
                    );

                lightPositions[i]  = new Vector4(v3, 15.0f);
                reflectedLights[i] = new Vector4(Vector3.Transform(v3, ReflectionTransform), 15.0f);
            }

            uniforms.LightPosRadius = reflectedLights;
            var bunnyMtx =
                Matrix4x4.CreateScale(5) *
                Matrix4x4.CreateRotationY(time - 1.56f) *
                Matrix4x4.CreateTranslation(0.0f, 2.0f, 0.0f);
            var reflectedBunnyMtx = bunnyMtx * ReflectionTransform;
            bunnyMesh.Submit(PassId1, programColorLighting, &reflectedBunnyMtx, StateGroups[PrebuiltRenderState.StencilReflectionDrawReflected], uniforms);

            for (int i = 0; i < 4; i++)
            {
                var mtx = ColumnTransforms[i] * ReflectionTransform;
                columnMesh.Submit(PassId1, programColorLighting, &mtx, StateGroups[PrebuiltRenderState.StencilReflectionDrawReflected], uniforms);
            }

            // third pass - blend the plane and reflections
            uniforms.LightPosRadius = lightPositions;
            hplaneMesh.Submit(PassId2, programTextureLighting, &floorMtx, StateGroups[PrebuiltRenderState.StencilReflectionBlendPlane], uniforms, fieldstoneTex, colorTextureHandle);

            // fourth pass - draw the solid objects
            bunnyMesh.Submit(PassId3, programColorLighting, &bunnyMtx, StateGroups[PrebuiltRenderState.StencilReflectionDrawScene], uniforms);
            for (int i = 0; i < 4; i++)
            {
                var mtx = ColumnTransforms[i];
                columnMesh.Submit(PassId3, programColorLighting, &mtx, StateGroups[PrebuiltRenderState.StencilReflectionDrawScene], uniforms);
            }

            // fifth pass - draw the lights as objects
            for (int i = 0; i < LightCount; i++)
            {
                var c = uniforms.LightColor[i];
                uniforms.Color = new Vector4(c.X, c.Y, c.Z, 0.8f);

                var p   = lightPositions[i];
                var mtx = Matrix4x4.CreateScale(1.5f) * Matrix4x4.CreateBillboard(new Vector3(p.X, p.Y, p.Z), camera.Position, Vector3.UnitY, -Vector3.UnitZ);
                vplaneMesh.Submit(PassId4, programColorTexture, &mtx, StateGroups[PrebuiltRenderState.CustomBlendLightTexture], uniforms, flareTex, colorTextureHandle);
            }

            // advance to the next frame. Rendering thread will be kicked to
            // process submitted rendering primitives.
            Bgfx.Frame();
        }

        // clean up
        bunnyMesh.Dispose();
        columnMesh.Dispose();
        hplaneMesh.Dispose();
        vplaneMesh.Dispose();

        figureTex.Dispose();
        fieldstoneTex.Dispose();
        flareTex.Dispose();

        programTextureLighting.Dispose();
        programColorLighting.Dispose();
        programColorTexture.Dispose();
        programColorBlack.Dispose();
        programTexture.Dispose();

        colorTextureHandle.Dispose();
        uniforms.Dispose();

        Bgfx.Shutdown();
    }
Beispiel #18
0
 public VertexBuffer(VertexColor[] vertices)
 {
     handle = new SharpBgfx.VertexBuffer(MemoryBlock.FromArray(vertices), VertexColor.vertexLayout);
 }
Beispiel #19
0
 public void SetData(byte[] data, int x, int y, int width, int height)
 {
     handle.Update2D(0, x, y, width, height, MemoryBlock.FromArray(data), ushort.MaxValue);
 }
Beispiel #20
0
 public void SetData(byte[] data)
 {
     handle.Update2D(0, 0, 0, handle.Width, handle.Height, MemoryBlock.FromArray(data), ushort.MaxValue);
 }
Beispiel #21
0
 public static VertexBuffer CreateVertexBuffer()
 {
     return(new VertexBuffer(MemoryBlock.FromArray(vertices), PosColorVertex.Layout));
 }
Beispiel #22
0
 public Texture2D(byte[] data, int width, int height, TextureFlags flags = TextureFlags.None, TextureFormat format = TextureFormat.BGRA8)
 {
     handle = Texture.Create2D(width, height, 0, format, flags, MemoryBlock.FromArray(data));
 }
Beispiel #23
0
 public static IndexBuffer CreateIndexBuffer()
 {
     return(new IndexBuffer(MemoryBlock.FromArray(indices)));
 }
Beispiel #24
0
 public IndexBuffer(ushort[] indices)
 {
     handle = new SharpBgfx.IndexBuffer(MemoryBlock.FromArray(indices));
 }
Beispiel #25
0
        public static Mesh LoadMesh(string fileName)
        {
            var          path   = Path.Combine(RootPath, "meshes/", fileName);
            var          groups = new List <MeshGroup>();
            var          group  = new MeshGroup();
            VertexLayout layout = null;

            using (var file = MemoryMappedFile.CreateFromFile(path)) {
                var reader = file.CreateViewAccessor();
                var bytes  = new FileInfo(path).Length;
                var index  = 0;

                while (index < bytes)
                {
                    var tag = reader.ReadUInt32(index); index += sizeof(uint);
                    if (tag == ChunkTagVB)
                    {
                        // skip bounding volume info
                        index += BoundingVolumeSize;

                        layout = reader.ReadVertexLayout(ref index);

                        var vertexCount = reader.ReadUInt16(ref index);
                        var vertexData  = reader.ReadArray <byte>(vertexCount * layout.Stride, ref index);
                        group.VertexBuffer = new VertexBuffer(MemoryBlock.FromArray(vertexData), layout);
                    }
                    else if (tag == ChunkTagIB)
                    {
                        var indexCount = reader.ReadUInt32(ref index);
                        var indexData  = reader.ReadArray <ushort>((int)indexCount, ref index);

                        group.IndexBuffer = new IndexBuffer(MemoryBlock.FromArray(indexData));
                    }
                    else if (tag == ChunkTagPri)
                    {
                        // skip material name
                        var len = reader.ReadUInt16(ref index);
                        index += len;

                        // read primitive data
                        var count = reader.ReadUInt16(ref index);
                        for (int i = 0; i < count; i++)
                        {
                            // skip name
                            len    = reader.ReadUInt16(ref index);
                            index += len;

                            var prim = reader.Read <Primitive>(ref index);
                            group.Primitives.Add(prim);

                            // skip bounding volumes
                            index += BoundingVolumeSize;
                        }

                        groups.Add(group);
                        group = new MeshGroup();
                    }
                }
            }

            return(new Mesh(layout, groups));
        }