コード例 #1
0
ファイル: Program.cs プロジェクト: raizam/SharpBgfx
    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);

        // set view 0 clear state
        Bgfx.SetViewClear(0, ClearTargets.Color | ClearTargets.Depth, 0x303030ff);

        // check capabilities
        var caps              = Bgfx.GetCaps();
        var computeSupported  = caps.SupportedFeatures.HasFlag(DeviceFeatures.Compute);
        var indirectSupported = caps.SupportedFeatures.HasFlag(DeviceFeatures.DrawIndirect);

        if (computeSupported)
        {
            RunCompute(sample, indirectSupported);
        }
        else
        {
            RunUnsupported(sample);
        }

        // clean up
        Bgfx.Shutdown();
    }
コード例 #2
0
    // Start is called before the first frame update
    void Start()
    {
        width  = (int)image.rectTransform.rect.width;
        height = (int)image.rectTransform.rect.height;

        bool isInit = Bgfx.Init();

        Debug.Log("bgfx initial result: " + isInit);
        // enable debug text
        //Bgfx.SetDebugFeatures(DebugFeatures.DisplayText);
        //// set view 0 clear state
        //Bgfx.SetViewClear(0, ClearTargets.Color | ClearTargets.Depth, 0x303030ff);

        // Bgfx.SetWindowHandle(image.mainTexture.GetNativeTexturePtr());
        //PlatformData platformData = new PlatformData();
        //platformData.DisplayType = System.IntPtr.Zero;
        //platformData.WindowHandle = image.mainTexture.GetNativeTexturePtr();
        //string str = "aassssssssss";

        //IntPtr initstr = Marshal.StringToHGlobalAnsi(str);
        //platformData.Context = imageTem.mainTexture.g;
        //platformData.Backbuffer = System.IntPtr.Zero;
        //platformData.BackbufferDepthStencil = System.IntPtr.Zero;
        //Bgfx.SetPlatformData(platformData);
    }
コード例 #3
0
ファイル: Program.cs プロジェクト: jangocheng/GLFWDotNet
        public static int Main(string[] args)
        {
            if (GLFW.Init() == 0)
            {
                return(-1);
            }

            GLFW.WindowHint(GLFW.CLIENT_API, GLFW.NO_API);

            string title = $"GLFW & SharpBgfx";

            IntPtr window = GLFW.CreateWindow(640, 480, title, IntPtr.Zero, IntPtr.Zero);

            if (window == IntPtr.Zero)
            {
                GLFW.Terminate();
                return(-1);
            }

            Bgfx.SetPlatformData(new PlatformData()
            {
                WindowHandle = GetWin32Window(window)
            });

            Bgfx.Init();

            Bgfx.Reset(640, 480, ResetFlags.Vsync);

            Bgfx.SetDebugFeatures(DebugFeatures.DisplayText);

            Bgfx.SetViewClear(0, ClearTargets.Color | ClearTargets.Depth, 0x303030ff);

            while (GLFW.WindowShouldClose(window) == 0)
            {
                GLFW.PollEvents();

                Bgfx.Touch(0);

                // write some debug text
                Bgfx.DebugTextClear();
                Bgfx.DebugTextWrite(0, 1, DebugColor.White, DebugColor.Blue, "GLFWDotNet & SharpBgfx");
                Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Cyan, "Description: Initialization and debug text.");

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

                GLFW.SwapBuffers(window);
            }

            Bgfx.Shutdown();

            GLFW.Terminate();

            return(0);
        }
コード例 #4
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();
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: zachlungu/SharpBgfx
    static void RenderThread(Sample sample)
    {
        // initialize the renderer
        Bgfx.Init();
        Bgfx.Reset(sample.WindowWidth, sample.WindowHeight, ResetFlags.Vsync);

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

        // set view 0 clear state
        Bgfx.SetViewClear(0, ClearTargets.Color | ClearTargets.Depth, 0x303030ff);

        // main loop
        while (sample.ProcessEvents(ResetFlags.Vsync))
        {
            // set view 0 viewport
            Bgfx.SetViewRect(0, 0, 0, sample.WindowWidth, sample.WindowHeight);

            //  make sure view 0 is cleared if no other draw calls are submitted
            Bgfx.Touch(0);

            // write some debug text
            Bgfx.DebugTextClear();
            Bgfx.DebugTextImage(
                Math.Max(sample.WindowWidth / 2 / 8, 20) - 20,
                Math.Max(sample.WindowHeight / 2 / 16, 6) - 6,
                40, 12,
                Logo.Bytes,
                160
                );

            Bgfx.DebugTextWrite(0, 1, DebugColor.White, DebugColor.Blue, "SharpBgfx/Samples/00-HelloWorld");
            Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Cyan, "Description: Initialization and debug text.");

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

        // clean up
        Bgfx.Shutdown();
    }
コード例 #6
0
        private void ImplInitialize(IntPtr graphics_surface_ptr, int width, int height)
        {
            Bgfx.SetPlatformData(new PlatformData
            {
                WindowHandle = graphics_surface_ptr
            });

            var bgfx_callback_handler = new BgfxCallbackHandler();

            var settings = new InitSettings
            {
                Backend         = RendererBackend.Default,
                ResetFlags      = ResetFlags.Vsync,
                Width           = width,
                Height          = height,
                CallbackHandler = bgfx_callback_handler
            };

            Bgfx.Init(settings);


            var caps = Bgfx.GetCaps();

            GraphicsBackend gfx_backend = GraphicsBackend.OpenGL;

            switch (caps.Backend)
            {
            case RendererBackend.OpenGL: gfx_backend = GraphicsBackend.OpenGL; break;

            case RendererBackend.Direct3D11:
            case RendererBackend.Direct3D12:
            case RendererBackend.Direct3D9:
                gfx_backend = GraphicsBackend.OpenGL; break;
            }

            Info = new GraphicsInfo(gfx_backend, caps.MaxTextureSize);
        }
コード例 #7
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();
    }
コード例 #8
0
        public Renderer(GameWindow sdlWindow, int width, int height, RendererFlags flags = RendererFlags.None, RendererType type = RendererType.Default)
        {
            window = sdlWindow;

            // retrieve platform specific data and pass them to bgfx
            SDL.SDL_SysWMinfo wmi          = window.GetPlatformWindowInfo();
            PlatformData      platformData = new PlatformData();

            switch (wmi.subsystem)
            {
            case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_WINDOWS:
                platformData.WindowHandle = wmi.info.win.window;
                break;

            case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_X11:
                platformData.DisplayType  = wmi.info.x11.display;
                platformData.WindowHandle = wmi.info.x11.window;
                break;

            case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_COCOA:
                platformData.WindowHandle = wmi.info.cocoa.window;
                break;

            default:
                throw new ApplicationException("Failed to initialize renderer, unsupported platform detected");
            }

            if (platformData.WindowHandle == IntPtr.Zero)
            {
                throw new ApplicationException("Failed to initialize renderer, invalid platform window handle");
            }

            Bgfx.SetPlatformData(platformData);
            Bgfx.Init((RendererBackend)type);

            if (width * height <= 0)
            {
                Int2 windowSize = window.ClientSize;
                width  = windowSize.x;
                height = windowSize.y;
            }

            Reset(width, height, flags);

            shaderPath = Path.Combine(Program.basePath, "Shaders");
            switch (rendererType)
            {
            case RendererType.Direct3D11:
                shaderPath = Path.Combine(shaderPath, "dx11");
                break;

            case RendererType.Direct3D9:
                shaderPath = Path.Combine(shaderPath, "dx9");
                break;

            case RendererType.OpenGL:
                shaderPath = Path.Combine(shaderPath, "opengl");
                break;

            default:
                throw new ApplicationException("No shader path defined for renderer " + rendererType.ToString());
            }

            spriteRenderer = new SpriteRenderer(this, width, height);

            defaultProgram = new ShaderProgram(
                Path.Combine(shaderPath, "default_vs.bin"),
                Path.Combine(shaderPath, "default_fs.bin"));

            textureColor = new Uniform("s_texColor", UniformType.Int1);
        }
コード例 #9
0
    static unsafe void RenderThread(Sample sample)
    {
        // initialize the renderer
        Bgfx.Init();
        Bgfx.Reset(sample.WindowWidth, sample.WindowHeight, ResetFlags.None);

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

        // set view 0 clear state
        Bgfx.SetViewClear(0, ClearTargets.Color | ClearTargets.Depth, 0x303030ff);

        // create vertex and index buffers
        var vbh = Cube.CreateVertexBuffer();
        var ibh = Cube.CreateIndexBuffer();

        // load shaders
        var program = ResourceLoader.LoadProgram("vs_cubes", "fs_cubes");

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

        clock.Start();

        int   cubeDim    = 15;
        float lastUpdate = 0.0f;
        int   frameCount = 0;

        // main loop
        while (sample.ProcessEvents(ResetFlags.None))
        {
            // set view 0 viewport
            Bgfx.SetViewRect(0, 0, 0, sample.WindowWidth, sample.WindowHeight);

            // view transforms
            var viewMatrix = Matrix4x4.CreateLookAt(new Vector3(0.0f, 0.0f, -35.0f), Vector3.Zero, Vector3.UnitY);
            var projMatrix = Matrix4x4.CreatePerspectiveFieldOfView((float)Math.PI / 3, (float)sample.WindowWidth / sample.WindowHeight, 0.1f, 100.0f);
            Bgfx.SetViewTransform(0, &viewMatrix.M11, &projMatrix.M11);

            // make sure view 0 is cleared if no other draw calls are submitted
            Bgfx.Touch(0);

            // tick the clock
            var elapsed = clock.Frame();
            var time    = clock.TotalTime();
            if (elapsed > 10)
            {
                elapsed = 0;
            }

            frameCount++;
            lastUpdate += elapsed;
            if (lastUpdate > 1.0f)
            {
                var avgFrameTime = frameCount / lastUpdate;
                if (avgFrameTime > HighThreshold)
                {
                    cubeDim = Math.Min(cubeDim + 2, 40);
                }
                else if (avgFrameTime < LowThreshold)
                {
                    cubeDim = Math.Max(cubeDim - 1, 2);
                }

                frameCount = 0;
                lastUpdate = 0;
            }

            var initial = new Vector3(
                -Step * cubeDim / 2.0f,
                -Step * cubeDim / 2.0f,
                -15.0f
                );

            // write some debug text
            Bgfx.DebugTextClear();
            Bgfx.DebugTextWrite(0, 1, DebugColor.White, DebugColor.Blue, "Description: CPU/driver stress test, maximizing draw calls.");
            Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Cyan, "Draw Calls: {0}", cubeDim * cubeDim * cubeDim);
            Bgfx.DebugTextWrite(0, 3, DebugColor.White, DebugColor.Cyan, "Frame:      {0:F3} ms", elapsed * 1000);

            for (int z = 0; z < cubeDim; z++)
            {
                for (int y = 0; y < cubeDim; y++)
                {
                    for (int x = 0; x < cubeDim; x++)
                    {
                        // model matrix
                        var transform = Matrix4x4.CreateFromYawPitchRoll(time + x * 0.21f, time + y * 0.37f, time + y * 0.13f);
                        transform     = Matrix4x4.CreateScale(Scale) * transform;
                        transform.M41 = initial.X + x * Step;
                        transform.M42 = initial.Y + y * Step;
                        transform.M43 = initial.Z + z * Step;
                        Bgfx.SetTransform(&transform.M11);

                        // set pipeline states
                        Bgfx.SetVertexBuffer(0, vbh);
                        Bgfx.SetIndexBuffer(ibh);
                        Bgfx.SetRenderState(RenderState.Default);

                        // submit primitives
                        Bgfx.Submit(0, program);
                    }
                }
            }

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

        // clean up
        ibh.Dispose();
        vbh.Dispose();
        program.Dispose();
        Bgfx.Shutdown();
    }
コード例 #10
0
ファイル: Core.cs プロジェクト: OpenLSR/OpenLSR
        unsafe static void Main(string[] args)
        {
            int width  = 640;
            int height = 480;

            var renderer = new Renderer();

            renderer.CreateSDL(width, height, string.Format("OpenLSR v{0}", Assembly.GetEntryAssembly().GetName().Version.ToString()));

            var wmi = new SDL_SysWMinfo();

            SDL_VERSION(out wmi.version);
            SDL_GetWindowWMInfo(renderer.window, ref wmi);

            var pd = new PlatformData();

            pd.WindowHandle = wmi.info.win.window;

            var init = new InitSettings();

            init.PlatformData = pd;

            Bgfx.Init(init);
            Bgfx.Reset(width, height, ResetFlags.Vsync);

            SDL_ShowWindow(renderer.window);

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

            // set view 0 clear state
            Bgfx.SetViewClear(0, ClearTargets.Color | ClearTargets.Depth, 0x303030ff);

            bool      quit = false;
            SDL_Event Event;

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

            clock.Start();

            // main loop
            while (!quit)
            {
                while (SDL_PollEvent(out Event) != 0)
                {
                    switch (Event.type)
                    {
                    case SDL_EventType.SDL_QUIT:
                        quit = true;
                        break;

                    default:
                        break;
                    }
                }

                // set view 0 viewport
                Bgfx.SetViewRect(0, 0, 0, width, height);

                //  make sure view 0 is cleared if no other draw calls are submitted
                Bgfx.Touch(0);

                // tick the clock
                var elapsed = clock.Frame();
                var time    = clock.TotalTime();

                // write some debug text
                Bgfx.DebugTextClear();

                Bgfx.DebugTextWrite(0, 1, DebugColor.White, DebugColor.Magenta, "OpenLSR Test");
                Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Magenta, "Frame: {0:F3} ms", elapsed * 1000);


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

            // clean up
            Bgfx.Shutdown();

            SDL_DestroyRenderer(renderer.renderer);
            SDL_DestroyWindow(renderer.window);

            SDL_Quit();
        }
コード例 #11
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);

        // set view 0 clear state
        Bgfx.SetViewClear(0, ClearTargets.Color | ClearTargets.Depth, 0x303030ff);

        // create vertex and index buffers
        var vbh = Cube.CreateVertexBuffer();
        var ibh = Cube.CreateIndexBuffer();

        // load shaders
        var program = ResourceLoader.LoadProgram("vs_cubes", "fs_cubes");

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

        clock.Start();

        var imguiController = new ImGuiController(1);

        var image = imguiController.AddTexture(ResourceLoader.LoadTexture("fieldstone-rgba.dds"));

        // main loop
        while (sample.ProcessEvents(ResetFlags.Vsync))
        {
            // set view 0 viewport
            Bgfx.SetViewRect(0, 0, 0, sample.WindowWidth, sample.WindowHeight);

            // view transforms
            var viewMatrix = Matrix4x4.CreateLookAt(new Vector3(0.0f, 0.0f, -35.0f), Vector3.Zero, Vector3.UnitY);
            var projMatrix = Matrix4x4.CreatePerspectiveFieldOfView((float)Math.PI / 3, (float)sample.WindowWidth / sample.WindowHeight, 0.1f, 100.0f);
            Bgfx.SetViewTransform(0, &viewMatrix.M11, &projMatrix.M11);

            // make sure view 0 is cleared if no other draw calls are submitted
            Bgfx.Touch(0);

            // 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/ImGui");
            Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Cyan, "Description: Rendering simple static mesh.");
            Bgfx.DebugTextWrite(0, 3, DebugColor.White, DebugColor.Cyan, "Frame: {0:F3} ms", elapsed * 1000);

            // submit 11x11 cubes
            for (int y = 0; y < 11; y++)
            {
                for (int x = 0; x < 11; x++)
                {
                    // model matrix
                    var transform = Matrix4x4.CreateFromYawPitchRoll(time + x * 0.21f, time + y * 0.37f, 0.0f);
                    transform.M41 = -15.0f + x * 3.0f;
                    transform.M42 = -15.0f + y * 3.0f;
                    transform.M43 = 0.0f;
                    Bgfx.SetTransform(&transform.M11);

                    // set pipeline states
                    Bgfx.SetVertexBuffer(0, vbh);
                    Bgfx.SetIndexBuffer(ibh);
                    Bgfx.SetRenderState(RenderState.Default);

                    // submit primitives
                    Bgfx.Submit(0, program);
                }
            }

            imguiController.StartFrame();

            ImGui.ShowDemoWindow();

            ImGui.SetNextWindowPos(new Vector2(100, 100));
            ImGui.SetNextWindowSize(new Vector2(400, 400));
            ImGui.Begin("Drawing an image");
            ImGui.Image(image, new Vector2(((float)Math.Sin(clock.TotalTime()) + 1) * 200, ((float)Math.Sin(clock.TotalTime()) + 1) * 200));
            ImGui.End();

            imguiController.EndFrame(elapsed, new Vector2(sample.WindowWidth, sample.WindowHeight));


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

        // clean up
        ibh.Dispose();
        vbh.Dispose();
        program.Dispose();
        Bgfx.Shutdown();
    }
コード例 #12
0
        unsafe static bool InitInternal(bool startedAtFullScreen, bool multiMonitorMode, string fontManagerDefaultLanguage) //, bool isEditor )//, Vec2I mainRenderTargetSize )
        {
            OgreNativeWrapper.CheckNativeBridge((int)ParameterType.TextureCube);                                            // GpuProgramParameters.GetAutoConstantTypeCount() );

            //!!!!new UWP
            var path = VirtualFileSystem.Directories.PlatformSpecific;

            if (SystemSettings.CurrentPlatform == SystemSettings.Platform.UWP)
            {
                path = VirtualFileSystem.MakePathRelative(path);
            }

            Vector2I initialWindowSize = new Vector2I(10, 10);

            if (SystemSettings.CurrentPlatform == SystemSettings.Platform.UWP)
            {
                initialWindowSize = EngineApp.platform.CreatedWindow_GetClientRectangle().Size;
            }

            //set backend for Android
            if (SystemSettings.CurrentPlatform == SystemSettings.Platform.Android)
            {
                EngineSettings.Init.RendererBackend = RendererBackend.OpenGLES;
                //EngineSettings.Init.RendererBackend = RendererBackend.Vulkan;
                //EngineSettings.Init.RendererBackend = RendererBackend.Noop;
            }

            //set platform data
            if (SystemSettings.CurrentPlatform == SystemSettings.Platform.Android && EngineSettings.Init.RendererBackend == RendererBackend.OpenGLES)
            {
                //Android, OpenGLES
                Bgfx.SetPlatformData(new PlatformData {
                    Context = (IntPtr)1
                });
            }
            else
            {
                Bgfx.SetPlatformData(new PlatformData {
                    WindowHandle = EngineApp.ApplicationWindowHandle
                });
            }

            if (EngineApp.ApplicationType == EngineApp.ApplicationTypeEnum.Simulation && EngineSettings.Init.SimulationTripleBuffering)
            {
                Bgfx.SetTripleBuffering();
            }

            //Log.InvisibleInfo( "Renderer backend: " + EngineSettings.Init.RendererBackend.ToString() );

            var initSettings = new InitSettings
            {
                Backend         = EngineSettings.Init.RendererBackend,
                CallbackHandler = new CallbackHandler(),

                ////!!!!в релизе можно включить. в NeoAxis.DefaultSettings.config
                //Debug = true
                //!!!!
                //ResetFlags = ResetFlags.MSAA8x,
            };

            Bgfx.Init(initSettings);

            Bgfx.Reset(initialWindowSize.X, initialWindowSize.Y, GetApplicationWindowResetFlags());

            realRoot = (OgreRoot *)OgreRoot.New(path);

            //profilingToolBeginOperationDelegate = profilingToolBeginOperation;
            //profilingToolEndOperationDelegate = profilingToolEndOperation;
            //OgreRoot.setCallbackDelegates( realRoot,
            //   profilingToolBeginOperationDelegate,
            //   profilingToolEndOperationDelegate );

            logListener_messageLoggedDelegate = logListener_messageLogged;
            logListener = (MyOgreLogListener *)MyOgreLogListener.New(
                logListener_messageLoggedDelegate);
            OgreLogManager.getDefaultLog_addListener(realRoot, logListener);

            MyOgreVirtualFileSystem.Init();

            //TextBlock configBlock = null;
            //if( VirtualFile.Exists( "Base/Constants/RenderingSystem.config" ) )
            //	configBlock = TextBlockUtility.LoadFromVirtualFile( "Base/Constants/RenderingSystem.config" );

            ////irradianceVolumeLightPowerSpeed
            //{
            //   irradianceVolumeLightPowerSpeed = 1;

            //   if( configBlock != null )
            //   {
            //      TextBlock staticLightingBlock = configBlock.FindChild( "staticLighting" );
            //      if( staticLightingBlock != null )
            //      {
            //         if( staticLightingBlock.IsAttributeExist( "irradianceVolumeLightPowerSpeed" ) )
            //         {
            //            irradianceVolumeLightPowerSpeed = float.Parse(
            //               staticLightingBlock.GetAttribute( "irradianceVolumeLightPowerSpeed" ) );
            //         }
            //      }
            //   }
            //}

            //if( !string.IsNullOrEmpty( EngineApp.InitSettings.RenderingDeviceName ) )
            //{
            //	OgreRoot.setRenderingDevice( realRoot, EngineApp.InitSettings.RenderingDeviceName,
            //		EngineApp.InitSettings.RenderingDeviceIndex );
            //}

            ////!!!!!!всё таки выключать можно для NULL рендеринга?
            ////renderSystem.MaxPixelShadersVersion = MaxPixelShadersVersions.PS30;
            ////renderSystem.MaxVertexShadersVersion = MaxVertexShadersVersions.VS30;
            //RenderingSystem.Direct3DFPUPreserve = EngineApp.InitSettings.RenderingDirect3DFPUPreserve;

            unsafe
            {
                OgreRoot.initialise(realRoot);
            }

            GpuProgramManager.Init();

            InitGPUSettingsAndCapabilities();

            applicationRenderWindow = new RenderWindow(FrameBuffer.Invalid, initialWindowSize, EngineApp.ApplicationWindowHandle, true);
            //applicationRenderWindow.WindowMovedOrResized( xxx );
            //!!!!!?, mainRenderTargetSize );

            //Scene manager
            MyOgreSceneManager *realSceneManager = (MyOgreSceneManager *)OgreRoot.createSceneManager(realRoot, "NeoAxisSceneManager");

            sceneManager = new OgreSceneManager(realSceneManager);

            EngineFontManager.Init(fontManagerDefaultLanguage);

            //Create viewport
            Viewport viewport = applicationRenderWindow.AddViewport(true, true);

            // RenderCamera.Purposes.UsualScene );// mainRenderTargetCamera );
            //viewport.Camera.AllowFrustumCullingTestMode = true;
            //mainRenderTargetViewport = mainRenderTarget.AddViewport( RenderCamera.Purposes.UsualScene );// mainRenderTargetCamera );
            //mainRenderTargetCamera = mainRenderTargetViewport.ViewportCamera;
            //mainRenderTargetCamera.AllowFrustumCullingTestMode = true;

            {
                IntPtr errorPointer;
                OgreResourceGroupManager.initialiseAllResourceGroups(realRoot, out errorPointer);
                string error = OgreNativeWrapper.GetOutString(errorPointer);
                if (error != null)
                {
                    Log.Error(string.Format("Renderer: {0}", error));
                    return(false);
                }
            }

            //Ogre initialization errors
            if (resourceInitializationErrors.Count != 0)
            {
                string text = "Renderer initialization errors:\n\n";
                foreach (string message in resourceInitializationErrors)
                {
                    text += message + "\n";
                }
                resourceInitializationErrors.Clear();
                Log.Error(text);
                return(false);
            }
            resourcesInitialized = true;

            GpuBufferManager.Init();

            //!!!!!
            //ResourceLoadingManagerInBackground.Init();

            return(true);
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: raizam/SharpBgfx
    static unsafe void RenderThread(Sample sample)
    {
        // initialize the renderer
        Bgfx.Init(RendererBackend.OpenGL, callbackHandler: new CallbackHandler());
        Bgfx.Reset(sample.WindowWidth, sample.WindowHeight, ResetFlags.MSAA16x | ResetFlags.Capture);

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

        // set view 0 clear state
        Bgfx.SetViewClear(0, ClearTargets.Color | ClearTargets.Depth, 0x303030ff);
        Bgfx.SetViewRect(0, 0, 0, sample.WindowWidth, sample.WindowHeight);

        // create vertex and index buffers
        var vbh = Cube.CreateVertexBuffer();
        var ibh = Cube.CreateIndexBuffer();

        // load shaders
        var program = ResourceLoader.LoadProgram("vs_callback", "fs_callback");

        // 5 seconds of 60 Hz video
        var time = 0.0f;

        for (int frame = 0; frame < 300; frame++)
        {
            // write some debug text
            Bgfx.DebugTextClear();
            Bgfx.DebugTextWrite(0, 1, DebugColor.White, DebugColor.Blue, "SharpBgfx/Samples/07-Callback");
            Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Cyan, "Description: Implementing application specific callbacks for taking screen shots,");
            Bgfx.DebugTextWrite(13, 3, DebugColor.White, DebugColor.Cyan, "caching OpenGL binary shaders, and video capture.");
            Bgfx.DebugTextWrite(0, 4, DebugColor.White, DebugColor.Cyan, "Frame: {0}", frame);

            // view transforms
            var viewMatrix = Matrix4x4.CreateLookAt(new Vector3(0.0f, 0.0f, 35.0f), Vector3.Zero, Vector3.UnitY);
            var projMatrix = Matrix4x4.CreatePerspectiveFieldOfView((float)Math.PI / 3, (float)sample.WindowWidth / sample.WindowHeight, 0.1f, 100.0f);
            Bgfx.SetViewTransform(0, &viewMatrix.M11, &projMatrix.M11);

            // fixed frame rate
            time += 1.0f / 60.0f;

            // submit 11x11 cubes
            for (int y = 0; y < 11; y++)
            {
                for (int x = 0; x < 11 - y; x++)
                {
                    // model matrix
                    var transform = Matrix4x4.CreateFromYawPitchRoll(time + x * 0.21f, time + y * 0.37f, 0.0f);
                    transform.M41 = -15.0f + x * 3.0f;
                    transform.M42 = -15.0f + y * 3.0f;
                    transform.M43 = 0.0f;
                    Bgfx.SetTransform(&transform.M11);

                    // set pipeline states
                    Bgfx.SetVertexBuffer(0, vbh);
                    Bgfx.SetIndexBuffer(ibh);
                    Bgfx.SetRenderState(RenderState.Default);

                    // submit primitives
                    Bgfx.Submit(0, program);
                }
            }

            // take a screenshot at frame 150
            if (frame == 150)
            {
                Bgfx.RequestScreenShot("frame150");
            }

            // advance to next frame
            Bgfx.Frame();
        }

        // clean up
        ibh.Dispose();
        vbh.Dispose();
        program.Dispose();
        Bgfx.Shutdown();
    }
コード例 #14
0
ファイル: Program.cs プロジェクト: sweep3r/SharpBgfx
    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);

        // set view 0 clear state
        Bgfx.SetViewClear(0, ClearTargets.Color | ClearTargets.Depth, 0x303030ff);

        // create vertex and index buffers
        var vbh = Cube.CreateVertexBuffer();
        var ibh = Cube.CreateIndexBuffer();

        // load shaders
        var program = ResourceLoader.LoadProgram("vs_instancing", "fs_instancing");

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

        clock.Start();

        // getting caps
        var caps = Bgfx.GetCaps();

        // main loop
        while (sample.ProcessEvents(ResetFlags.Vsync))
        {
            // set view 0 viewport
            Bgfx.SetViewRect(0, 0, 0, sample.WindowWidth, sample.WindowHeight);

            // view transforms
            var viewMatrix = Matrix4x4.CreateLookAt(new Vector3(0.0f, 0.0f, -35.0f), Vector3.Zero, Vector3.UnitY);
            var projMatrix = Matrix4x4.CreatePerspectiveFieldOfView((float)Math.PI / 3, (float)sample.WindowWidth / sample.WindowHeight, 0.1f, 100.0f);
            Bgfx.SetViewTransform(0, &viewMatrix.M11, &projMatrix.M11);

            // make sure view 0 is cleared if no other draw calls are submitted
            Bgfx.Touch(0);

            // 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/05-Instancing");
            Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Cyan, "Description: Geometry instancing.");
            Bgfx.DebugTextWrite(0, 3, DebugColor.White, DebugColor.Cyan, "Frame: {0:F3} ms", elapsed * 1000);

            // check caps
            if ((caps.SupportedFeatures & DeviceFeatures.Instancing) != DeviceFeatures.Instancing)
            {
                // instancing not supported
                Bgfx.DebugTextWrite(0, 3, DebugColor.White, DebugColor.Red, "Instancing not supported!");
            }
            else
            {
                const int instanceStride = 80;
                const int instanceCount  = 121;

                var idb = new InstanceDataBuffer(instanceCount, instanceStride);

                // fill in InstanceDataBuffer
                byte *dataPtr = (byte *)idb.Data.ToPointer();
                // TODO: extract idb->data->num
                for (int y = 0; y < 11; y++)
                {
                    for (int x = 0; x < 11; x++)
                    {
                        float *matrix     = (float *)dataPtr;
                        var    realMatrix = Matrix4x4.CreateFromYawPitchRoll(time + x * 0.21f, time + y * 0.37f, 0f);
                        realMatrix.M41 = -15.0f + x * 3.0f;
                        realMatrix.M42 = -15.0f + y * 3.0f;
                        realMatrix.M43 = 0.0f;
                        // TODO: use proper copy function, not a bycicle
                        float *realMatrixPtr = &realMatrix.M11;
                        for (int i = 0; i < 16; i++)
                        {
                            matrix[i] = realMatrixPtr[i];
                        }

                        float *color = (float *)(dataPtr + 64);
                        color[0] = (float)Math.Sin(time + x / 11.0f) * 0.5f + 0.5f;
                        color[1] = (float)Math.Cos(time + y / 11.0f) * 0.5f + 0.5f;
                        color[2] = (float)Math.Sin(time * 3.0f) * 0.5f + 0.5f;
                        color[3] = 1.0f;

                        dataPtr += instanceStride;
                    }
                }

                // set pipeline states
                Bgfx.SetVertexBuffer(0, vbh);
                Bgfx.SetIndexBuffer(ibh);
                Bgfx.SetInstanceDataBuffer(ref idb);
                Bgfx.SetRenderState(RenderState.Default);

                // submit primitives
                Bgfx.Submit(0, program);
            }

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

        // clean up
        ibh.Dispose();
        vbh.Dispose();
        program.Dispose();
        Bgfx.Shutdown();
    }