internal GraphicsContext(IntPtr graphics_surface_ptr, int width, int height) { var timer = Stopwatch.StartNew(); 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); Console.WriteLine($" > GFX INIT : {timer.Elapsed.TotalSeconds.ToString()}"); var caps = Bgfx.GetCaps(); Info = new GraphicsInfo(caps.Backend, caps.MaxTextureSize); Console.WriteLine($"GRAPHICS BACKEND : {Info.RendererBackend.ToString()}"); index_buffers = new IndexBuffer[16]; }
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); }
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); }
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); }
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); }
private static void Main(string[] args) { var platform = "x64"; if (IntPtr.Size == 4) { platform = "x86"; } NativeMethods.LoadLibrary($"{platform}/SDL2.dll"); Bgfx.InitializeLibrary(); ushort resolutionWidth = 800; ushort resolutionHeight = 600; var windowhandle = SDL.SDL_CreateWindow("hello", 10, 10, resolutionWidth, resolutionHeight, SDL.SDL_WindowFlags.SDL_WINDOW_ALLOW_HIGHDPI); var wm = new SDL.SDL_SysWMinfo(); SDL.SDL_GetWindowWMInfo(windowhandle, ref wm); Bgfx.SetPlatformData(wm.info.win.window); var init = Bgfx.Initialize(resolutionWidth, resolutionHeight, Bgfx.RendererType.DIRECT_3D11); ImGui.SetCurrentContext(ImGui.CreateContext()); var IO = ImGui.GetIO(); IO.ImeWindowHandle = wm.info.win.window; //IO.BackendFlags |= ImGuiBackendFlags.HasMouseCursors; // We can honor GetMouseCursor() values (optional) //IO.BackendFlags |= ImGuiBackendFlags.HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) //IO.BackendPlatformName = new NullTerminatedString("imgui_impl_win32".ToCharArray()); IO.KeyMap[(int)ImGuiKey.Tab] = (int)SDL.SDL_Scancode.SDL_SCANCODE_TAB; IO.KeyMap[(int)ImGuiKey.LeftArrow] = (int)SDL.SDL_Scancode.SDL_SCANCODE_LEFT; IO.KeyMap[(int)ImGuiKey.RightArrow] = (int)SDL.SDL_Scancode.SDL_SCANCODE_RIGHT; IO.KeyMap[(int)ImGuiKey.UpArrow] = (int)SDL.SDL_Scancode.SDL_SCANCODE_UP; IO.KeyMap[(int)ImGuiKey.DownArrow] = (int)SDL.SDL_Scancode.SDL_SCANCODE_DOWN; IO.KeyMap[(int)ImGuiKey.PageUp] = (int)SDL.SDL_Scancode.SDL_SCANCODE_PAGEUP; IO.KeyMap[(int)ImGuiKey.PageDown] = (int)SDL.SDL_Scancode.SDL_SCANCODE_PAGEDOWN; IO.KeyMap[(int)ImGuiKey.Home] = (int)SDL.SDL_Scancode.SDL_SCANCODE_HOME; IO.KeyMap[(int)ImGuiKey.End] = (int)SDL.SDL_Scancode.SDL_SCANCODE_END; IO.KeyMap[(int)ImGuiKey.Insert] = (int)SDL.SDL_Scancode.SDL_SCANCODE_INSERT; IO.KeyMap[(int)ImGuiKey.Delete] = (int)SDL.SDL_Scancode.SDL_SCANCODE_DELETE; IO.KeyMap[(int)ImGuiKey.Backspace] = (int)SDL.SDL_Scancode.SDL_SCANCODE_BACKSPACE; IO.KeyMap[(int)ImGuiKey.Space] = (int)SDL.SDL_Scancode.SDL_SCANCODE_SPACE; IO.KeyMap[(int)ImGuiKey.Enter] = (int)SDL.SDL_Scancode.SDL_SCANCODE_KP_ENTER; IO.KeyMap[(int)ImGuiKey.Escape] = (int)SDL.SDL_Scancode.SDL_SCANCODE_ESCAPE; IO.KeyMap[(int)ImGuiKey.KeyPadEnter] = (int)SDL.SDL_Scancode.SDL_SCANCODE_RETURN; IO.KeyMap[(int)ImGuiKey.A] = (int)SDL.SDL_Scancode.SDL_SCANCODE_A; IO.KeyMap[(int)ImGuiKey.C] = (int)SDL.SDL_Scancode.SDL_SCANCODE_C; IO.KeyMap[(int)ImGuiKey.V] = (int)SDL.SDL_Scancode.SDL_SCANCODE_V; IO.KeyMap[(int)ImGuiKey.X] = (int)SDL.SDL_Scancode.SDL_SCANCODE_X; IO.KeyMap[(int)ImGuiKey.Y] = (int)SDL.SDL_Scancode.SDL_SCANCODE_Y; IO.KeyMap[(int)ImGuiKey.Z] = (int)SDL.SDL_Scancode.SDL_SCANCODE_Z; IO.Fonts.AddFontDefault(); IO.Fonts.GetTexDataAsRGBA32(out IntPtr pixels, out var fwidth, out var fheight); IO.Fonts.SetTexID(new IntPtr(Bgfx.CreateTexture2D((ushort)fwidth, (ushort)fheight, false, 1, (Bgfx.TextureFormat)Bgfx.TextureFormat.RGBA8, (Bgfx.SamplerFlags.U_CLAMP | Bgfx.SamplerFlags.V_CLAMP | Bgfx.SamplerFlags.MIN_POINT | Bgfx.SamplerFlags.MAG_POINT | Bgfx.SamplerFlags.MIP_POINT), Bgfx.MakeRef(pixels, (uint)(4 * fwidth * fheight))).Idx)); Bgfx.SetViewClear(0, (ushort)(Bgfx.ClearFlags.COLOR | Bgfx.ClearFlags.DEPTH), 0x6495edff, 0, 0); Bgfx.SetViewMode(0, Bgfx.ViewMode.SEQUENTIAL); Bgfx.SetViewMode(255, Bgfx.ViewMode.SEQUENTIAL); Bgfx.SetDebug(Bgfx.DebugFlags.NONE); Bgfx.Reset(resolutionWidth, resolutionHeight, Bgfx.ResetFlags.VSYNC | Bgfx.ResetFlags.MSAA_X4, init.format); var running = true; var bgfxcaps = Bgfx.GetCaps(); mtxOrtho(out var ortho, 0, resolutionWidth, resolutionHeight, 0, 0, 1000.0f, 0, bgfxcaps.Homogenousdepth); var ImguiVertexLayout = new Bgfx.VertexLayout(); ImguiVertexLayout.Begin(Bgfx.RendererType.NOOP); ImguiVertexLayout.Add(Bgfx.Attrib.POSITION, Bgfx.AttribType.FLOAT, 2, false, false); ImguiVertexLayout.Add(Bgfx.Attrib.TEX_COORD0, Bgfx.AttribType.FLOAT, 2, false, false); ImguiVertexLayout.Add(Bgfx.Attrib.COLOR0, Bgfx.AttribType.UINT8, 4, true, false); ImguiVertexLayout.End(); var WhitePixelTexture = Bgfx.CreateTexture2D(1, 1, false, 1, Bgfx.TextureFormat.RGBA8, Bgfx.SamplerFlags.V_CLAMP | Bgfx.SamplerFlags.U_CLAMP | Bgfx.SamplerFlags.MIN_POINT | Bgfx.SamplerFlags.MAG_POINT | Bgfx.SamplerFlags.MIP_POINT, new uint[] { 0x0000ffff }); var TextureUniform = Bgfx.CreateUniform("s_texture", Bgfx.UniformType.SAMPLER, 1); var ImGuiShader = LoadEffect("vs_imgui.bin", "fs_imgui.bin"); while (running) { SDL.SDL_PollEvent(out var Event); if (Event.window.type == SDL.SDL_EventType.SDL_QUIT) { running = false; } var mouseState = SDL.SDL_GetMouseState(out var mouseX, out var mouseY); IO.MouseDown[0] = (mouseState & SDL.SDL_BUTTON(SDL.SDL_BUTTON_LEFT)) != 0; IO.MouseDown[1] = (mouseState & SDL.SDL_BUTTON(SDL.SDL_BUTTON_RIGHT)) != 0; IO.MouseDown[2] = (mouseState & SDL.SDL_BUTTON(SDL.SDL_BUTTON_MIDDLE)) != 0; SDL.SDL_GetWindowPosition(windowhandle, out var wx, out var wy); SDL.SDL_GetGlobalMouseState(out mouseX, out mouseY); mouseX -= wx; mouseY -= wy; IO.MousePosPrev = IO.MousePos; IO.MousePos = new Vector2(mouseX, mouseY); ImGui.NewFrame(); //ImGui.SetNextWindowSize(new Vector2(200); if (ImGui.Begin("test")) { if (ImGui.Button("click OS popup")) { SDL.SDL_ShowSimpleMessageBox(SDL.SDL_MessageBoxFlags.SDL_MESSAGEBOX_INFORMATION, "Cliked Button", "Click Message", windowhandle); } if (ImGui.Button("modal popup")) { ImGui.OpenPopup("modal popup"); } ImGui.Text("Hello"); if (ImGui.BeginPopupModal("modal popup")) { if (ImGui.Button("clicked")) { ImGui.CloseCurrentPopup(); } ImGui.EndPopup(); } } ImGui.End(); ImGui.EndFrame(); ImGui.Render(); Bgfx.SetViewRect(0, 0, 0, resolutionWidth, resolutionHeight); Bgfx.SetViewRect(255, 0, 0, resolutionWidth, resolutionHeight); IO.DisplaySize = new Vector2(resolutionWidth, resolutionHeight); IO.DisplayFramebufferScale = new Vector2(1); Bgfx.Touch(0); { var drawdata = ImGui.GetDrawData(); ushort viewID = 0; Bgfx.SetViewTransform(viewID, null, ortho); { // Render command lists for (int ii = 0, num = drawdata.CmdListsCount; ii < num; ++ii) { var drawList = drawdata.CmdListsRange[ii]; var numVertices = drawList.VtxBuffer.Size; var numIndices = drawList.IdxBuffer.Size; var tib = Bgfx.AllocateTransientIndexBuffer((uint)numIndices); var tvb = Bgfx.AllocateTransientVertexBuffer((uint)numVertices, ImguiVertexLayout); tvb.CopyIntoBuffer(drawList.VtxBuffer.Data, (uint)numVertices * (uint)Unsafe.SizeOf <ImDrawVert>()); tib.CopyIntoBuffer(drawList.IdxBuffer.Data, (uint)numIndices * (uint)Unsafe.SizeOf <ushort>()); uint offset = 0; for (int i = 0; i < drawList.CmdBuffer.Size; i++) { var cmd = drawList.CmdBuffer[i]; if (cmd.UserCallback != IntPtr.Zero) { // cmd->UserCallback(drawList, cmd); } else if (cmd.ElemCount > 0) { var state = Bgfx.StateFlags.WRITE_RGB | Bgfx.StateFlags.WRITE_A | Bgfx.StateFlags.MSAA ; var texHandle = new Bgfx.TextureHandle(); if (cmd.TextureId.ToInt32() != 0) { texHandle.Idx = (ushort)cmd.TextureId.ToInt32(); } else { texHandle.Idx = WhitePixelTexture.Idx; } state |= Bgfx.STATE_BLEND_FUNC(Bgfx.StateFlags.BLEND_SRC_ALPHA, Bgfx.StateFlags.BLEND_INV_SRC_ALPHA); ushort xx = (ushort)((cmd.ClipRect.X > 0.0f ? cmd.ClipRect.X : 0.0f)); ushort yy = (ushort)((cmd.ClipRect.Y > 0.0f ? cmd.ClipRect.Y : 0.0f)); ushort zz = (ushort)((cmd.ClipRect.Z > 65535.0f ? 65535.0f : cmd.ClipRect.Z) - xx); ushort ww = (ushort)((cmd.ClipRect.W > 65535.0f ? 65535.0f : cmd.ClipRect.W) - yy); Bgfx.SetScissor(xx, yy, zz, ww); Bgfx.SetState(state, 0); Bgfx.SetTexture(0, TextureUniform, texHandle); Bgfx.SetTransientVertexBuffer(0, tvb, 0, (uint)numVertices); Bgfx.SetTransientIndexBuffer(tib, offset, cmd.ElemCount); Bgfx.Submit(viewID, ImGuiShader.program, 0, false); } offset += cmd.ElemCount; } } } } Bgfx.Frame(false); } }