// Draw the imgui triangle data void DrawTriangles(uint count, ImVector <ushort> idxBuffer, ImPtrVector <ImDrawVertPtr> idxVert, int idxOffset, int vtxOffset, IntPtr textureId) { uint texId = (uint)textureId; ushort index; ImDrawVertPtr vertex; if (Rlgl.rlCheckBufferLimit((int)count * 3)) { Rlgl.rlglDraw(); } Rlgl.rlPushMatrix(); Rlgl.rlBegin(Rlgl.RL_TRIANGLES); Rlgl.rlEnableTexture(texId); for (int i = 0; i <= (count - 3); i += 3) { index = idxBuffer[idxOffset + i]; vertex = idxVert[vtxOffset + index]; DrawTriangleVertex(vertex); index = idxBuffer[idxOffset + i + 2]; vertex = idxVert[vtxOffset + index]; DrawTriangleVertex(vertex); index = idxBuffer[idxOffset + i + 1]; vertex = idxVert[vtxOffset + index]; DrawTriangleVertex(vertex); } Rlgl.rlDisableTexture(); Rlgl.rlEnd(); Rlgl.rlPopMatrix(); }
public int TotalIdxCount; // For convenience, sum of all cmd_lists idx_buffer.Size // Functions public ImDrawData() { //CmdLists = new ImDrawList(); Valid = false; CmdLists = null; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; }
internal ImVector <int> IndexLookup; // Sparse. Index glyphs by Unicode code-point. // Methods public ImFont() { Glyphs = new ImVector <Glyph>(); IndexXAdvance = new ImVector <float>(); IndexLookup = new ImVector <int>(); Scale = 1.0f; FallbackChar = '?'; Clear(); }
unsafe void RenderCommandLists(ImDrawDataPtr drawData) { // Scale coordinates for retina displays (screen coordinates != framebuffer coordinates) int fbWidth = (int)(drawData.DisplaySize.X * drawData.FramebufferScale.X); int fbHeight = (int)(drawData.DisplaySize.Y * drawData.FramebufferScale.Y); // Avoid rendering if display is minimized or if the command list is empty if (fbWidth <= 0 || fbHeight <= 0 || drawData.CmdListsCount == 0) { return; } drawData.ScaleClipRects(ImGui.GetIO().DisplayFramebufferScale); Rlgl.rlDisableBackfaceCulling(); for (int n = 0; n < drawData.CmdListsCount; n++) { ImDrawListPtr cmdList = drawData.CmdListsRange[n]; // Vertex buffer and index buffer generated by Dear ImGui ImPtrVector <ImDrawVertPtr> vtxBuffer = cmdList.VtxBuffer; ImVector <ushort> idxBuffer = cmdList.IdxBuffer; for (int cmdi = 0; cmdi < cmdList.CmdBuffer.Size; cmdi++) { ImDrawCmdPtr pcmd = cmdList.CmdBuffer[cmdi]; if (pcmd.UserCallback != IntPtr.Zero) { // pcmd.UserCallback(cmdList, pcmd); } else { Vector2 pos = drawData.DisplayPos; int rectX = (int)((pcmd.ClipRect.X - pos.X) * drawData.FramebufferScale.X); int rectY = (int)((pcmd.ClipRect.Y - pos.Y) * drawData.FramebufferScale.Y); int rectW = (int)((pcmd.ClipRect.Z - rectX) * drawData.FramebufferScale.X); int rectH = (int)((pcmd.ClipRect.W - rectY) * drawData.FramebufferScale.Y); if (rectX < fbWidth && rectY < fbHeight && rectW >= 0.0f && rectH >= 0.0f) { Raylib.BeginScissorMode(rectX, rectY, rectW, rectH); DrawTriangles(pcmd.ElemCount, idxBuffer, vtxBuffer, (int)pcmd.IdxOffset, (int)pcmd.VtxOffset, pcmd.TextureId); } } } } Raylib.EndScissorMode(); Rlgl.rlEnableBackfaceCulling(); }
private static void SetUpMonitorData() { ImGuiPlatformIOPtr platformIO = ImGui.GetPlatformIO(); var platformMonitors = new List <ImGuiPlatformMonitor>(); { Monitor *[] monitors = GLFW.GetMonitors(); for (int i = 0; i < monitors.Length; i++) { Monitor * monitor = monitors[i]; ImGuiPlatformMonitor m = new ImGuiPlatformMonitor(); var vidMode = GLFW.GetVideoMode(monitor); GLFW.GetMonitorPos(monitor, out int x, out int y); m.MainPos = m.WorkPos = new Vector2(x, y); m.MainSize = m.WorkSize = new Vector2(vidMode->Width, vidMode->Height); GLFW.GetMonitorContentScale(monitor, out float xScale, out float yScale); m.DpiScale = xScale; platformMonitors.Add(m); } } _monitorData = platformMonitors.ToArray(); _monitorDataPin = GCHandle.Alloc(_monitorData, GCHandleType.Pinned); var platformMonitorsPtrs = new ImGuiPlatformMonitorPtr[_monitorData.Length]; for (int i = 0; i < _monitorData.Length; i++) { fixed(ImGuiPlatformMonitor *ptr = &_monitorData[i]) { platformMonitorsPtrs[i] = new ImGuiPlatformMonitorPtr(ptr); } } _monitorPtrData = platformMonitorsPtrs; _monitorPtrDataPin = GCHandle.Alloc(_monitorPtrData, GCHandleType.Pinned); _monitorsPtrVector = new ImVector <ImGuiPlatformMonitor>(_monitorPtrData.Length, _monitorPtrData.Length, _monitorDataPin.AddrOfPinnedObject()); { ImGuiPlatformIO *ptr = platformIO; ImVector v = Unsafe.As <ImVector <ImGuiPlatformMonitor>, ImVector>(ref _monitorsPtrVector); ptr->Monitors = v; } }
internal int FocusIdxTabRequestNext; // " internal ImGuiWindow(string name) { DC = new ImGuiDrawContext(); IDStack = new ImVector <uint>(); StateStorage = new ImGuiStorage(); MenuColumns = new ImGuiSimpleColumns(); DrawList = new ImDrawList(); Name = name; ID = ImGui.Hash(0, name); IDStack.push_back(ID); MoveID = GetID("#MOVE"); Flags = 0; PosFloat = Pos = new ImVec2(0.0f, 0.0f); Size = SizeFull = new ImVec2(0.0f, 0.0f); SizeContents = SizeContentsExplicit = new ImVec2(0.0f, 0.0f); WindowPadding = new ImVec2(0.0f, 0.0f); Scroll = new ImVec2(0.0f, 0.0f); ScrollTarget = new ImVec2(float.MaxValue, float.MaxValue); ScrollTargetCenterRatio = new ImVec2(0.5f, 0.5f); ScrollbarX = ScrollbarY = false; ScrollbarSizes = new ImVec2(0.0f, 0.0f); BorderSize = 0.0f; Active = WasActive = false; Accessed = false; Collapsed = false; SkipItems = false; BeginCount = 0; PopupID = 0; AutoFitFramesX = AutoFitFramesY = -1; AutoFitOnlyGrows = false; AutoPosLastDirection = -1; HiddenFrames = 0; SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = (int)(ImGuiSetCond.ImGuiSetCond_Always | ImGuiSetCond.ImGuiSetCond_Once | ImGuiSetCond.ImGuiSetCond_FirstUseEver | ImGuiSetCond.ImGuiSetCond_Appearing); SetWindowPosCenterWanted = false; LastFrameActive = -1; ItemWidthDefault = 0.0f; FontWindowScale = 1.0f; RootWindow = null; RootNonPopupWindow = null; FocusIdxAllCounter = FocusIdxTabCounter = -1; FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = int.MaxValue; FocusIdxAllRequestNext = FocusIdxTabRequestNext = int.MaxValue; }
internal ImGuiDrawContext() { ItemWidthStack = new ImVector <float>(); TextWrapPosStack = new ImVector <float>(); AllowKeyboardFocusStack = new ImVector <bool>(); ButtonRepeatStack = new ImVector <bool>(); GroupStack = new ImVector <ImGuiGroupData>(); ChildWindows = new ImVector <ImGuiWindow>(); ColumnsData = new ImVector <ImGuiColumnData>(); CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = new ImVec2(0.0f, 0.0f); CurrentLineHeight = PrevLineHeight = 0.0f; CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; LogLinePosY = -1.0f; TreeDepth = 0; LastItemID = 0; LastItemRect = new ImRect(0.0f, 0.0f, 0.0f, 0.0f); LastItemHoveredAndUsable = LastItemHoveredRect = false; MenuBarAppending = false; MenuBarOffsetX = 0.0f; StateStorage = null; LayoutType = ImGuiLayoutType.ImGuiLayoutType_Vertical; ItemWidth = 0.0f; ButtonRepeat = false; AllowKeyboardFocus = true; TextWrapPos = -1.0f; ColorEditMode = ImGuiColorEditMode.ImGuiColorEditMode_RGB; //memset(StackSizesBackup, 0, sizeof(StackSizesBackup)); IndentX = 0.0f; ColumnsOffsetX = 0.0f; ColumnsCurrent = 0; ColumnsCount = 1; ColumnsMinX = ColumnsMaxX = 0.0f; ColumnsStartPosY = 0.0f; ColumnsCellMinY = ColumnsCellMaxY = 0.0f; ColumnsShowBorders = true; ColumnsSetID = 0; }
private void UpdateImGuiInput(InputSnapshot snapshot) { ImGuiIOPtr io = ImGui.GetIO(); Vector2 mousePosition = snapshot.MousePosition; // Determine if any of the mouse buttons were pressed during this snapshot period, even if they are no longer held. bool leftPressed = false; bool middlePressed = false; bool rightPressed = false; foreach (MouseEvent me in snapshot.MouseEvents) { if (me.Down) { switch (me.MouseButton) { case MouseButton.Left: leftPressed = true; break; case MouseButton.Middle: middlePressed = true; break; case MouseButton.Right: rightPressed = true; break; } } } io.MouseDown[0] = leftPressed || snapshot.IsMouseDown(MouseButton.Left); io.MouseDown[1] = middlePressed || snapshot.IsMouseDown(MouseButton.Right); io.MouseDown[2] = rightPressed || snapshot.IsMouseDown(MouseButton.Middle); if (p_sdl_GetGlobalMouseState == null) { p_sdl_GetGlobalMouseState = Sdl2Native.LoadFunction <SDL_GetGlobalMouseState_t>("SDL_GetGlobalMouseState"); } int x, y; unsafe { uint buttons = p_sdl_GetGlobalMouseState(&x, &y); io.MouseDown[0] = (buttons & 0b0001) != 0; io.MouseDown[1] = (buttons & 0b0010) != 0; io.MouseDown[2] = (buttons & 0b0100) != 0; } io.MousePos = new Vector2(x, y); io.MouseWheel = snapshot.WheelDelta; IReadOnlyList <char> keyCharPresses = snapshot.KeyCharPresses; for (int i = 0; i < keyCharPresses.Count; i++) { char c = keyCharPresses[i]; io.AddInputCharacter(c); } IReadOnlyList <KeyEvent> keyEvents = snapshot.KeyEvents; for (int i = 0; i < keyEvents.Count; i++) { KeyEvent keyEvent = keyEvents[i]; io.KeysDown[(int)keyEvent.Key] = keyEvent.Down; if (keyEvent.Key == Key.ControlLeft) { _controlDown = keyEvent.Down; } if (keyEvent.Key == Key.ShiftLeft) { _shiftDown = keyEvent.Down; } if (keyEvent.Key == Key.AltLeft) { _altDown = keyEvent.Down; } if (keyEvent.Key == Key.WinLeft) { _winKeyDown = keyEvent.Down; } } io.KeyCtrl = _controlDown; io.KeyAlt = _altDown; io.KeyShift = _shiftDown; io.KeySuper = _winKeyDown; ImVector <ImGuiViewportPtr> viewports = ImGui.GetPlatformIO().Viewports; for (int i = 1; i < viewports.Size; i++) { ImGuiViewportPtr v = viewports[i]; VeldridImGuiWindow window = ((VeldridImGuiWindow)GCHandle.FromIntPtr(v.PlatformUserData).Target); window.Update(); } }
public void SubmitImGuiToRenderer() { ImDrawDataPtr test; test = ImGui.GetDrawData(); ImDrawListPtr test3; if (test.CmdListsCount > 0) { test3 = test.CmdListsRange[0]; ImVector <ushort> ptr = test3.IdxBuffer; ImPtrVector <ImDrawVertPtr> t1 = test3.VtxBuffer; ImDrawVertPtr pp; ImDrawVert[] vertbuf = new ImDrawVert[t1.Size]; unsafe { for (int i = 0; i < t1.Size; i++) { pp = t1[i]; ImDrawVert ff = new ImDrawVert(); // Console.WriteLine("vertex x:{0} y:{1}, u:{2} v:{3} color:{4}", ff.pos.X, ff.pos.Y, ff.uv.X, ff.uv.Y, ff.col); ff.pos = pp.pos; ff.uv = pp.uv; ff.col = pp.col; vertbuf[i] = ff; } } ushort[] indexbuf = new ushort[ptr.Size]; for (int i = 0; i < ptr.Size; i++) { indexbuf[i] = (ushort)ptr[i]; } // indexbuf хранит индекс координаты в vertbuf, рисует полигоны, поэтому уходит по три индекса. индекс составлен так, что координаты // перечисляются против часовой стрелки. int y; Color c; Dictionary <int, Vertex[]> imgvelist = new Dictionary <int, Vertex[]>(); int idxoffsettemp = 0; int nv = 0; for (int i = 0; i < test3.CmdBuffer.Size; i++) { ImDrawCmdPtr dc = test3.CmdBuffer[i]; if (dc.TextureId != IntPtr.Zero && dc.TextureId.ToInt32() != 1) { List <SpriteRenderable> sr = BufferSpriteRenderable[dc.TextureId.ToInt32()]; idxoffsettemp = (int)dc.IdxOffset; // для этих спрайтов в sr, UV координаты даны относительно текстуры 2048 на 2048 пикселей. y = indexbuf[idxoffsettemp]; Vertex[] tempve = new Vertex[6 * sr.Count]; nv = 0; foreach (SpriteRenderable sre in sr) { PaletteReference pr = sre.Palette; // берем XY в мире, и превращаем в координаты . Потом отнимаем смещение окна Imgui // float3 worldtoIGposl = sre.ScreenPosition(Game.worldRenderer); // потом в шейдере отнимется смещение от ViewPort // worldtoIGposl = worldtoIGposl - new float3(Game.worldRenderer.Viewport.TopLeft.X, Game.worldRenderer.Viewport.TopLeft.Y, 0); // worldtoIGposl = worldtoIGposl - new float3(worldtoIGposl.X, worldtoIGposl.Y,0); // worldtoIGposl = worldtoIGposl + new float3(this.Bounds.X+100, this.Bounds.Y+100, 0) ; // var xy = wr.ScreenPxPosition(pos) + wr.ScreenPxOffset(offset) - (0.5f * scale * sprite.Size.XY).ToInt2(); // Console.WriteLine("x: " + xy.X + " y: " + xy.Y + " | offX:" + sre.sprite.Offset.X + " offY:" + sre.sprite.Offset.Y +" |SpriteRenderable " + this.Actor.Info.Name + " owner:" + this.Actor.Owner); SamplerPointer spritelocation = Game.Renderer.ImguiSpriteRenderer.SetRenderStateForSprite(sre.sprite); // OpenRA.Graphics.Util.FastCreateQuadImGui(tempve, new float3(this.Bounds.X+ 16 * sre.Offset.X / 1024 + sre.sprite.Offset.X, this.Bounds.Y + 16 * sre.Offset.Y / 1024 + sre.sprite.Offset.Y, 0) + sre.sprite.FractionalOffset * sre.sprite.Size, sre.sprite, new int2(4, 0), pr.TextureIndex, nv, sre.sprite.Size); OpenRA.Graphics.Util.FastCreateQuadImGui(tempve, new float3(16 + vertbuf[y].pos.X + 16 * sre.Offset.X / 1024 + sre.sprite.Offset.X, 16 + vertbuf[y].pos.Y + 16 * sre.Offset.Y / 1024 + sre.sprite.Offset.Y, 0), sre.sprite, spritelocation, pr.TextureIndex, nv, sre.sprite.Size); nv += 6; } nv -= 6; imgvelist[y] = tempve; // new Vertex(vertbuf[idxoffsettemp].pos.X, vertbuf[idxoffsettemp].pos.Y, 0, vertbuf[idxoffsettemp].uv.X, vertbuf[idxoffsettemp].uv.Y, 0f, 0f, 0f, 5f, 255f / 255f, 255f / 255f, 255f / 255f, 255f / 255f) // sr.Render(null); } } ve = new Vertex[indexbuf.Length + nv]; for (int i = 0; i < indexbuf.Length; i++) { y = indexbuf[i]; // индекс для vertbuf хранится в ячейке indexbuf. c = Color.FromArgb(vertbuf[y].col); // если совпал y с imgvelist ключом, то запускаем for на 6 циклов и потом увеличиваем i на 6 позиций. if (imgvelist.ContainsKey(y)) { for (int f = 0; f < imgvelist[y].Length; f++) { ve[i] = imgvelist[y][f]; i++; } i--; } else { imguifonttextureLocation = Game.Renderer.ImguiSpriteRenderer.SetRenderStateForSprite(sp); ve[i] = new Vertex(vertbuf[y].pos.X, vertbuf[y].pos.Y, 0, vertbuf[y].uv.X, vertbuf[y].uv.Y, 0f, 0f, imguifonttextureLocation.num1, 0f, 4f, 0, c.R / 255f, c.G / 255f, c.B / 255f, c.A / 255f, 0, 0); } } // теперь нужно создать спрайт, чтобы вызывать Renderer.DrawSprite для занесения данных в VAO // типа строчка в VBO появляется как желание нарисовать спрайт. В данном случае спрайт это должна быть буква. // Но нет. Тут просто линия цветные Game.Renderer.ImguiSpriteRenderer.DrawRGBAVertices(ve); //Game.Renderer.ImguiSpriteRenderer.ns = 1; } }
public static void RenderDrawData(ImDrawData drawData, int displayW, int displayH) { // We are using the OpenGL fixed pipeline to make the example code simpler to read! // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers. int lastTexture; GL.GetIntegerv(GL.Enum.GL_TEXTURE_BINDING_2D, out lastTexture); Int4 lastViewport; GL.GetIntegerv4(GL.Enum.GL_VIEWPORT, out lastViewport); Int4 lastScissorBox; GL.GetIntegerv4(GL.Enum.GL_SCISSOR_BOX, out lastScissorBox); GL.PushAttrib(GL.Enum.GL_ENABLE_BIT | GL.Enum.GL_COLOR_BUFFER_BIT | GL.Enum.GL_TRANSFORM_BIT); GL.Enable(GL.Enum.GL_BLEND); GL.BlendFunc(GL.Enum.GL_SRC_ALPHA, GL.Enum.GL_ONE_MINUS_SRC_ALPHA); GL.Disable(GL.Enum.GL_CULL_FACE); GL.Disable(GL.Enum.GL_DEPTH_TEST); GL.Enable(GL.Enum.GL_SCISSOR_TEST); GL.EnableClientState(GL.Enum.GL_VERTEX_ARRAY); GL.EnableClientState(GL.Enum.GL_TEXTURE_COORD_ARRAY); GL.EnableClientState(GL.Enum.GL_COLOR_ARRAY); GL.Enable(GL.Enum.GL_TEXTURE_2D); GL.UseProgram(0); // Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays) ImGuiIO io = ImGui.GetIO(); ImGui.ScaleClipRects(drawData, io.DisplayFramebufferScale); // Setup orthographic projection matrix GL.Viewport(0, 0, displayW, displayH); GL.MatrixMode(GL.Enum.GL_PROJECTION); GL.PushMatrix(); GL.LoadIdentity(); GL.Ortho( 0.0f, io.DisplaySize.X / io.DisplayFramebufferScale.X, io.DisplaySize.Y / io.DisplayFramebufferScale.Y, 0.0f, -1.0f, 1.0f ); GL.MatrixMode(GL.Enum.GL_MODELVIEW); GL.PushMatrix(); GL.LoadIdentity(); // Render command lists for (int n = 0; n < drawData.CmdListsCount; n++) { ImDrawList cmdList = drawData[n]; ImVector <ImDrawVert> vtxBuffer = cmdList.VtxBuffer; ImVector <ushort> idxBuffer = cmdList.IdxBuffer; GL.VertexPointer(2, GL.Enum.GL_FLOAT, ImDrawVert.Size, new IntPtr((long)vtxBuffer.Data + ImDrawVert.PosOffset)); GL.TexCoordPointer(2, GL.Enum.GL_FLOAT, ImDrawVert.Size, new IntPtr((long)vtxBuffer.Data + ImDrawVert.UVOffset)); GL.ColorPointer(4, GL.Enum.GL_UNSIGNED_BYTE, ImDrawVert.Size, new IntPtr((long)vtxBuffer.Data + ImDrawVert.ColOffset)); long idxBufferOffset = 0; for (int cmdi = 0; cmdi < cmdList.CmdBuffer.Size; cmdi++) { ImDrawCmd pcmd = cmdList.CmdBuffer[cmdi]; if (pcmd.UserCallback != IntPtr.Zero) { pcmd.InvokeUserCallback(ref cmdList, ref pcmd); } else { GL.BindTexture(GL.Enum.GL_TEXTURE_2D, (int)pcmd.TextureId); GL.Scissor( (int)pcmd.ClipRect.X, (int)(io.DisplaySize.Y - pcmd.ClipRect.W), (int)(pcmd.ClipRect.Z - pcmd.ClipRect.X), (int)(pcmd.ClipRect.W - pcmd.ClipRect.Y) ); GL.DrawElements(GL.Enum.GL_TRIANGLES, (int)pcmd.ElemCount, GL.Enum.GL_UNSIGNED_SHORT, new IntPtr((long)idxBuffer.Data + idxBufferOffset)); } idxBufferOffset += pcmd.ElemCount * 2 /*sizeof(ushort)*/; } } // Restore modified state GL.DisableClientState(GL.Enum.GL_COLOR_ARRAY); GL.DisableClientState(GL.Enum.GL_TEXTURE_COORD_ARRAY); GL.DisableClientState(GL.Enum.GL_VERTEX_ARRAY); GL.BindTexture(GL.Enum.GL_TEXTURE_2D, lastTexture); GL.MatrixMode(GL.Enum.GL_MODELVIEW); GL.PopMatrix(); GL.MatrixMode(GL.Enum.GL_PROJECTION); GL.PopMatrix(); GL.PopAttrib(); GL.Viewport(lastViewport.X, lastViewport.Y, lastViewport.Z, lastViewport.W); GL.Scissor(lastScissorBox.X, lastScissorBox.Y, lastScissorBox.Z, lastScissorBox.W); }
public unsafe static void RenderDrawData(DrawData *drawData, int displayW, int displayH) { // We are using the OpenGL fixed pipeline to make the example code simpler to read! // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers. int lastTexture; GL.GetInteger(GetPName.TextureBinding2D, out lastTexture); Int4 lastViewport = new Int4(); TypedReference tr = __makeref(lastViewport); IntPtr ptr = **(IntPtr **)(&tr); GL.GetInteger(GetPName.Viewport, (int *)ptr); Int4 lastScissorBox = new Int4(); tr = __makeref(lastScissorBox); ptr = **(IntPtr **)(&tr); GL.GetInteger(GetPName.ScissorBox, (int *)ptr); GL.PushAttrib(AttribMask.EnableBit | AttribMask.ColorBufferBit | AttribMask.TransformBit); GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha); GL.Disable(EnableCap.CullFace); GL.Disable(EnableCap.DepthTest); GL.Enable(EnableCap.ScissorTest); GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.TextureCoordArray); GL.EnableClientState(ArrayCap.ColorArray); GL.Enable(EnableCap.Texture2D); GL.UseProgram(0); // Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays) IO io = ImGui.GetIO(); ImGui.ScaleClipRects(drawData, io.DisplayFramebufferScale); // Setup orthographic projection matrix GL.Viewport(0, 0, displayW, displayH); GL.MatrixMode(MatrixMode.Projection); GL.PushMatrix(); GL.LoadIdentity(); GL.Ortho( 0.0f, io.DisplaySize.X / io.DisplayFramebufferScale.X, io.DisplaySize.Y / io.DisplayFramebufferScale.Y, 0.0f, -1.0f, 1.0f ); GL.MatrixMode(MatrixMode.Modelview); GL.PushMatrix(); GL.LoadIdentity(); // Render command lists for (int n = 0; n < drawData->CmdListsCount; n++) { DrawList cmddList = new DrawList(drawData->CmdLists[n]); NativeDrawList *cmdList = drawData->CmdLists[n]; ImVector vtxBuffer = cmdList->VtxBuffer; ImVector idxBuffer = cmdList->IdxBuffer; GL.VertexPointer(2, VertexPointerType.Float, sizeof(DrawVert), new IntPtr((long)vtxBuffer.Data + DrawVert.PosOffset)); GL.TexCoordPointer(2, TexCoordPointerType.Float, sizeof(DrawVert), new IntPtr((long)vtxBuffer.Data + DrawVert.UVOffset)); GL.ColorPointer(4, ColorPointerType.UnsignedByte, sizeof(DrawVert), new IntPtr((long)vtxBuffer.Data + DrawVert.ColOffset)); long idxBufferOffset = 0; for (int cmdi = 0; cmdi < cmdList->CmdBuffer.Size; cmdi++) { DrawCmd *pcmd = &(((DrawCmd *)cmdList->CmdBuffer.Data)[cmdi]); /* if (pcmd->UserCallback!= IntPtr.Zero) { * pcmd->(ref cmdList, ref pcmd); * } else {*/ GL.BindTexture(TextureTarget.Texture2D, (int)pcmd->TextureId); GL.Scissor( (int)pcmd->ClipRect.X, (int)(io.DisplaySize.Y - pcmd->ClipRect.W), (int)(pcmd->ClipRect.Z - pcmd->ClipRect.X), (int)(pcmd->ClipRect.W - pcmd->ClipRect.Y) ); GL.DrawElements(PrimitiveType.Triangles, (int)pcmd->ElemCount, DrawElementsType.UnsignedByte, new IntPtr((long)idxBuffer.Data + idxBufferOffset)); idxBufferOffset += pcmd->ElemCount * 2 /*sizeof(ushort)*/; } } // Restore modified state GL.DisableClientState(ArrayCap.ColorArray); GL.DisableClientState(ArrayCap.TextureCoordArray); GL.DisableClientState(ArrayCap.VertexArray); GL.BindTexture(TextureTarget.Texture2D, lastTexture); GL.MatrixMode(MatrixMode.Modelview); GL.PopMatrix(); GL.MatrixMode(MatrixMode.Projection); GL.PopMatrix(); GL.PopAttrib(); GL.Viewport(lastViewport.X, lastViewport.Y, lastViewport.Z, lastViewport.W); GL.Scissor(lastScissorBox.X, lastScissorBox.Y, lastScissorBox.Z, lastScissorBox.W); }
private void UpdateImGuiInput() { ImGuiIOPtr io = ImGui.GetIO(); io.MouseWheel = 0; ImVector <ImGuiViewportPtr> viewports = ImGui.GetPlatformIO().Viewports; for (int i = 0; i < viewports.Size; i++) { ImGuiViewportPtr v = viewports[i]; var target = GCHandle.FromIntPtr(v.PlatformUserData).Target; if (target is VeldridImGuiWindow veldridWindow) { var snapshot = veldridWindow.PumpEvents(); io.MouseWheel += snapshot.WheelDelta; IReadOnlyList <char> keyCharPresses = snapshot.KeyCharPresses; for (int k = 0; k < keyCharPresses.Count; k++) { char c = keyCharPresses[k]; io.AddInputCharacter(c); } IReadOnlyList <KeyEvent> keyEvents = snapshot.KeyEvents; for (int k = 0; k < keyEvents.Count; k++) { KeyEvent keyEvent = keyEvents[k]; io.KeysDown[(int)keyEvent.Key] = keyEvent.Down; if (keyEvent.Key == Key.ControlLeft) { _controlDown = keyEvent.Down; } if (keyEvent.Key == Key.ShiftLeft) { _shiftDown = keyEvent.Down; } if (keyEvent.Key == Key.AltLeft) { _altDown = keyEvent.Down; } if (keyEvent.Key == Key.WinLeft) { _winKeyDown = keyEvent.Down; } } } } if (p_sdl_GetGlobalMouseState == null) { p_sdl_GetGlobalMouseState = Sdl2Native.LoadFunction <SDL_GetGlobalMouseState_t>("SDL_GetGlobalMouseState"); } int x, y; unsafe { uint buttons = p_sdl_GetGlobalMouseState(&x, &y); io.MouseDown[0] = (buttons & 0b0001) != 0; io.MouseDown[1] = (buttons & 0b0010) != 0; io.MouseDown[2] = (buttons & 0b0100) != 0; } io.MousePos = new Vector2(x, y); io.KeyCtrl = _controlDown; io.KeyAlt = _altDown; io.KeyShift = _shiftDown; io.KeySuper = _winKeyDown; }
private void UpdateImGuiInput() { #if DEBUG using Profiler fullProfiler = new Profiler(GetType()); #endif ImGuiIOPtr io = ImGui.GetIO(); if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0) { //Pump events for all windows, but only update inputs regarding the focused one ImVector <ImGuiViewportPtr> viewports = ImGui.GetPlatformIO().Viewports; for (int i = 0; i < viewports.Size; i++) { WindowBase window = (WindowBase)GCHandle.FromIntPtr(viewports[i].PlatformUserData).Target; bool atualizarSnapshot = window.SdlWindow.Focused; window.OnUpdate(atualizarSnapshot); } } else { mainWindow.OnUpdate(); } InputSnapshot snapshot = InputManager.Snapshot; // Determine if any of the mouse buttons were pressed during this snapshot period, even if they are no longer held. bool leftPressed = false; bool middlePressed = false; bool rightPressed = false; for (int me = 0; me < snapshot.MouseEvents.Count; me++) { if (snapshot.MouseEvents[me].Down) { switch (snapshot.MouseEvents[me].MouseButton) { case MouseButton.Left: leftPressed = true; break; case MouseButton.Middle: middlePressed = true; break; case MouseButton.Right: rightPressed = true; break; } } } io.MouseDown[0] = leftPressed || snapshot.IsMouseDown(MouseButton.Left); io.MouseDown[1] = rightPressed || snapshot.IsMouseDown(MouseButton.Right); io.MouseDown[2] = middlePressed || snapshot.IsMouseDown(MouseButton.Middle); if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0) { int x, y; unsafe { uint buttons = Sdl_GetGlobalMouseState(&x, &y); io.MouseDown[0] = (buttons & 0b00001) != 0; io.MouseDown[1] = (buttons & 0b00100) != 0; io.MouseDown[2] = (buttons & 0b00010) != 0; io.MouseDown[3] = (buttons & 0b01000) != 0; io.MouseDown[4] = (buttons & 0b10000) != 0; } io.MousePos = new Vector2(x, y); } else { io.MousePos = snapshot.MousePosition; } io.MouseWheel = snapshot.WheelDelta; #region Keyboard #region TypedKeys IReadOnlyList <char> keyCharPresses = snapshot.KeyCharPresses; for (int i = 0; i < keyCharPresses.Count; i++) { char c = keyCharPresses[i]; io.AddInputCharacter(c); } #endregion IReadOnlyList <KeyEvent> keyEvents = snapshot.KeyEvents; for (int i = 0; i < keyEvents.Count; i++) { io.KeysDown[(int)keyEvents[i].Key] = keyEvents[i].Down; } io.KeyCtrl = io.KeysDown[(int)KeyCodes.ControlLeft] || io.KeysDown[(int)KeyCodes.ControlRight]; io.KeyAlt = io.KeysDown[(int)KeyCodes.AltLeft] || io.KeysDown[(int)KeyCodes.AltRight]; io.KeyShift = io.KeysDown[(int)KeyCodes.ShiftLeft] || io.KeysDown[(int)KeyCodes.ShiftRight]; io.KeySuper = io.KeysDown[(int)KeyCodes.SuperLeft] || io.KeysDown[(int)KeyCodes.SuperRight]; #endregion }
public void RenderDrawData(ImDrawData drawData) { GraphicsDevice device = Game.GraphicsDevice; // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers. Viewport lastViewport = device.Viewport; Rectangle lastScissorBox = device.ScissorRectangle; device.BlendFactor = Color.White; device.BlendState = BlendState.NonPremultiplied; device.RasterizerState = RasterizerState; device.DepthStencilState = DepthStencilState.DepthRead; // Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays) ImGuiIO io = ImGui.GetIO(); ImGui.ScaleClipRects(drawData, io.DisplayFramebufferScale); // Setup projection device.Viewport = new Viewport(0, 0, device.PresentationParameters.BackBufferWidth, device.PresentationParameters.BackBufferHeight); if (Effect == null) { Effect = new BasicEffect(device); } Effect effect = Effect; SetupEffect(this, effect); // Render command lists for (int n = 0; n < drawData.CmdListsCount; n++) { ImDrawList cmdList = drawData[n]; ImVector <ImDrawVertXNA> vtxBuffer; unsafe { vtxBuffer = new ImVector <ImDrawVertXNA>(cmdList.VtxBuffer.Native); } ImDrawVertXNA[] vtxArray = new ImDrawVertXNA[vtxBuffer.Size]; for (int i = 0; i < vtxBuffer.Size; i++) { vtxArray[i] = vtxBuffer[i]; } ImVector <short> idxBuffer; unsafe { idxBuffer = new ImVector <short>(cmdList.IdxBuffer.Native); } /* * short[] idxArray = new short[idxBuffer.Size]; * for (int i = 0; i < idxBuffer.Size; i++) * idxArray[i] = idxBuffer[i]; */ uint offset = 0; for (int cmdi = 0; cmdi < cmdList.CmdBuffer.Size; cmdi++) { ImDrawCmd pcmd = cmdList.CmdBuffer[cmdi]; if (pcmd.UserCallback != IntPtr.Zero) { pcmd.InvokeUserCallback(ref cmdList, ref pcmd); } else { // Instead of uploading the complete idxBuffer again and again, just upload what's required. short[] idxArray = new short[pcmd.ElemCount]; for (int i = 0; i < pcmd.ElemCount; i++) { idxArray[i] = idxBuffer[(int)offset + i]; } SetEffectTexture(this, effect, GetTexture((int)pcmd.TextureId)); device.ScissorRectangle = new Rectangle( (int)pcmd.ClipRect.X, (int)pcmd.ClipRect.Y, (int)(pcmd.ClipRect.Z - pcmd.ClipRect.X), (int)(pcmd.ClipRect.W - pcmd.ClipRect.Y) ); foreach (EffectPass pass in effect.CurrentTechnique.Passes) { pass.Apply(); device.DrawUserIndexedPrimitives( PrimitiveType.TriangleList, vtxArray, 0, vtxBuffer.Size, idxArray, 0, (int)pcmd.ElemCount / 3, ImDrawVertXNA._VertexDeclaration ); } } offset += pcmd.ElemCount; } } // Restore modified state device.Viewport = lastViewport; device.ScissorRectangle = lastScissorBox; }