-- GENERATED by tools/love.sh from the Luau source - do not edit local function __iter(t, ...) if type(t) ~= 'table' or (getmetatable(t) and getmetatable(t).__call) then return t, ... end local n, i, k = #t, 0, nil return function() if i < n then i = i + 1 return i, t[i] end repeat k = next(t, k) until k == nil or type(k) ~= 'number' or k < 1 or k > n or k % 1 ~= 0 if k ~= nil then return k, t[k] end end end table.create = table.create or function(n, v) local t = {} if v ~= nil then for i = 1, n do t[i] = v end end return t end table.clone = table.clone or function(t) local c = {} for k, v in pairs(t) do c[k] = v end return setmetatable(c, getmetatable(t)) end math.clamp = math.clamp or function(x, a, b) return math.max(a, math.min(b, x)) end math.sign = math.sign or function(x) return x > 0 and 1 or (x < 0 and -1 or 0) end math.round = math.round or function(x) return x >= 0 and math.floor(x + 0.5) or math.ceil(x - 0.5) end -- ImNodes for imgui-luau. Port of https://github.com/Nelarius/imnodes (eb36902c892548ef94f88f51ad7e7c9c7058a71c). -- Usage: local ImNodes = require(path.to.ImNodes)(require(path.to.ImGui)) return function(G) local ImGui, ImVec2, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4 local ImRect, ImVector, IM_COL32, IM_ASSERT = G.ImRect, G.ImVector, G.IM_COL32, G.IM_ASSERT local ImNodes = {} local internal = {} -- [Port] imnodes_internal.h contents (kept off the public table, out of the 200-locals budget) ImNodes.internal = internal local INT_MAX = 2147483647 --------------------------------------------------------------------------- -- imnodes.h enums --------------------------------------------------------------------------- do ImNodes.ImNodesCol = { NodeBackground = 0, NodeBackgroundHovered = 1, NodeBackgroundSelected = 2, NodeOutline = 3, TitleBar = 4, TitleBarHovered = 5, TitleBarSelected = 6, Link = 7, LinkHovered = 8, LinkSelected = 9, Pin = 10, PinHovered = 11, BoxSelector = 12, BoxSelectorOutline = 13, GridBackground = 14, GridLine = 15, GridLinePrimary = 16, MiniMapBackground = 17, MiniMapBackgroundHovered = 18, MiniMapOutline = 19, MiniMapOutlineHovered = 20, MiniMapNodeBackground = 21, MiniMapNodeBackgroundHovered = 22, MiniMapNodeBackgroundSelected = 23, MiniMapNodeOutline = 24, MiniMapLink = 25, MiniMapLinkSelected = 26, MiniMapCanvas = 27, MiniMapCanvasOutline = 28, COUNT = 29, } ImNodes.ImNodesStyleVar = { GridSpacing = 0, NodeCornerRounding = 1, NodePadding = 2, NodeBorderThickness = 3, LinkThickness = 4, LinkLineSegmentsPerLength = 5, LinkHoverDistance = 6, PinCircleRadius = 7, PinQuadSideLength = 8, PinTriangleSideLength = 9, PinLineThickness = 10, PinHoverRadius = 11, PinOffset = 12, MiniMapPadding = 13, MiniMapOffset = 14, COUNT = 15, } ImNodes.ImNodesStyleFlags = { None = 0, NodeOutline = bit32.lshift(1, 0), GridLines = bit32.lshift(1, 2), GridLinesPrimary = bit32.lshift(1, 3), GridSnapping = bit32.lshift(1, 4), } ImNodes.ImNodesPinShape = { Circle = 0, CircleFilled = 1, Triangle = 2, TriangleFilled = 3, Quad = 4, QuadFilled = 5, } -- This enum controls the way the attribute pins behave. ImNodes.ImNodesAttributeFlags = { None = 0, -- Allow detaching a link by left-clicking and dragging the link at a pin it is connected to. -- NOTE: the user has to actually delete the link for this to work. A deleted link can be -- detected by calling IsLinkDestroyed() after EndNodeEditor(). EnableLinkDetachWithDragClick = bit32.lshift(1, 0), -- Visual snapping of an in progress link will trigger IsLink Created/Destroyed events. Allows -- for previewing the creation of a link while dragging it across attributes. See here for demo: -- https://github.com/Nelarius/imnodes/issues/41#issuecomment-647132113 NOTE: the user has to -- actually delete the link for this to work. A deleted link can be detected by calling -- IsLinkDestroyed() after EndNodeEditor(). EnableLinkCreationOnSnap = bit32.lshift(1, 1), } ImNodes.ImNodesMiniMapLocation = { BottomLeft = 0, BottomRight = 1, TopLeft = 2, TopRight = 3, } end --------------------------------------------------------------------------- -- imnodes_internal.h: [SECTION] internal enums --------------------------------------------------------------------------- do internal.ImNodesScope = { None = 1, Editor = bit32.lshift(1, 1), Node = bit32.lshift(1, 2), Attribute = bit32.lshift(1, 3), } internal.ImNodesAttributeType = { None = 0, Input = 1, Output = 2, } internal.ImNodesUIState = { None = 0, LinkStarted = bit32.lshift(1, 0), LinkDropped = bit32.lshift(1, 1), LinkCreated = bit32.lshift(1, 2), } internal.ImNodesClickInteractionType = { Node = 0, Link = 1, LinkCreation = 2, Panning = 3, BoxSelection = 4, ImGuiItem = 5, None = 6, } internal.ImNodesLinkCreationType = { Standard = 0, FromDetach = 1, } end --------------------------------------------------------------------------- -- ImNodesIO / ImNodesStyle --------------------------------------------------------------------------- do -- [Port] `const bool* Modifier` has no Luau equivalent: Modifier is nil (NULL) or a function returning bool, -- e.g. ImNodes.GetIO().EmulateThreeButtonMouse.Modifier = function() return ImGui.GetIO().KeyAlt end function ImNodes.ImNodesIO() return { EmulateThreeButtonMouse = { Modifier = nil }, LinkDetachWithModifierClick = { Modifier = nil }, MultipleSelectModifier = { Modifier = nil }, -- Holding alt mouse button pans the node area, by default middle mouse button will be used -- Set based on ImGuiMouseButton values AltMouseButton = G.ImGuiMouseButton.Middle, -- Panning speed when dragging an element and mouse is outside the main editor view. AutoPanningSpeed = 1000.0, } end function ImNodes.ImNodesStyle() local colors = {} -- [Port] 0-based like ImGuiStyle.Colors in the core port for i = 0, ImNodes.ImNodesCol.COUNT - 1 do colors[i] = 0 end return { GridSpacing = 24.0, NodeCornerRounding = 4.0, NodePadding = ImVec2(8.0, 8.0), NodeBorderThickness = 1.0, LinkThickness = 3.0, LinkLineSegmentsPerLength = 0.1, LinkHoverDistance = 10.0, PinCircleRadius = 4.0, PinQuadSideLength = 7.0, PinTriangleSideLength = 9.5, PinLineThickness = 1.0, PinHoverRadius = 10.0, PinOffset = 0.0, MiniMapPadding = ImVec2(8.0, 8.0), MiniMapOffset = ImVec2(4.0, 4.0), -- By default, ImNodesStyleFlags_NodeOutline and ImNodesStyleFlags_Gridlines are enabled. Flags = bit32.bor(ImNodes.ImNodesStyleFlags.NodeOutline, ImNodes.ImNodesStyleFlags.GridLines), Colors = colors, } end end --------------------------------------------------------------------------- -- imnodes_internal.h: [SECTION] internal data structures --------------------------------------------------------------------------- do -- [Port] ImObjectPool: IdMap is a plain table (id -> index) instead of ImGuiStorage; pool indices are 1-based. -- [Port] T is the element constructor (template parameter), e.g. internal.ImNodeData function internal.ImObjectPool(T) return { Pool = ImVector(), InUse = ImVector(), FreeList = ImVector(), IdMap = {}, T = T } end -- [Port] ImOptionalIndex is represented by a plain int, with INVALID_INDEX as the "no value" sentinel. internal.INVALID_INDEX = -1 function internal.ImNodeData(node_id) return { Id = node_id, Origin = ImVec2(0.0, 0.0), -- The node origin is in editor space TitleBarContentRect = ImRect(), Rect = ImRect(ImVec2(0.0, 0.0), ImVec2(0.0, 0.0)), ColorStyle = { Background = 0, BackgroundHovered = 0, BackgroundSelected = 0, Outline = 0, Titlebar = 0, TitlebarHovered = 0, TitlebarSelected = 0, }, LayoutStyle = { CornerRounding = 0.0, Padding = ImVec2(0.0, 0.0), BorderThickness = 0.0 }, PinIndices = ImVector(), Draggable = true, } end function internal.ImPinData(pin_id) return { Id = pin_id, ParentNodeIdx = 0, AttributeRect = ImRect(), Type = internal.ImNodesAttributeType.None, Shape = ImNodes.ImNodesPinShape.CircleFilled, Pos = ImVec2(0.0, 0.0), -- screen-space coordinates Flags = ImNodes.ImNodesAttributeFlags.None, ColorStyle = { Background = 0, Hovered = 0 }, } end function internal.ImLinkData(link_id) return { Id = link_id, StartPinIdx = 0, EndPinIdx = 0, ColorStyle = { Base = 0, Hovered = 0, Selected = 0 }, } end function internal.ImClickInteractionState() return { Type = internal.ImNodesClickInteractionType.None, LinkCreation = { StartPinIdx = 0, EndPinIdx = internal.INVALID_INDEX, Type = internal.ImNodesLinkCreationType.Standard, }, BoxSelector = { Rect = ImRect(), -- Coordinates in grid space }, } end function internal.ImNodesColElement(c, s) return { Color = c, Item = s } end -- [Port] FloatValue is 1-based: [1] = upstream [0], [2] = upstream [1] function internal.ImNodesStyleVarElement(variable, value) if type(value) == "number" then return { Item = variable, FloatValue = { value, 0.0 } } end return { Item = variable, FloatValue = { value.x, value.y } } end end --------------------------------------------------------------------------- -- imnodes_internal.h: [SECTION] global and editor context structs --------------------------------------------------------------------------- do function internal.ImNodesEditorContext() return { Nodes = internal.ImObjectPool(internal.ImNodeData), Pins = internal.ImObjectPool(internal.ImPinData), Links = internal.ImObjectPool(internal.ImLinkData), NodeDepthOrder = ImVector(), -- ui related fields Panning = ImVec2(0.0, 0.0), AutoPanningDelta = ImVec2(0.0, 0.0), -- Minimum and maximum extents of all content in grid space. Valid after final -- ImNodes::EndNode() call. GridContentBounds = ImRect(), SelectedNodeIndices = ImVector(), SelectedLinkIndices = ImVector(), -- Relative origins of selected nodes for snapping of dragged nodes SelectedNodeOffsets = ImVector(), -- Offset of the primary node origin relative to the mouse cursor. PrimaryNodeOffset = ImVec2(0.0, 0.0), ClickInteraction = internal.ImClickInteractionState(), -- Mini-map state set by MiniMap() MiniMapEnabled = false, MiniMapLocation = ImNodes.ImNodesMiniMapLocation.BottomLeft, MiniMapSizeFraction = 0.0, MiniMapNodeHoveringCallback = nil, MiniMapNodeHoveringCallbackUserData = nil, -- Mini-map state set during EndNodeEditor() call MiniMapRectScreenSpace = ImRect(), MiniMapContentScreenSpace = ImRect(), MiniMapScaling = 0.0, } end function internal.ImNodesContext() return { DefaultEditorCtx = nil, EditorCtx = nil, -- Canvas draw list and helper state CanvasDrawList = nil, NodeIdxToSubmissionIdx = {}, -- [Port] ImGuiStorage -> plain table NodeIdxSubmissionOrder = ImVector(), NodeIndicesOverlappingWithMouse = ImVector(), OccludedPinIndices = ImVector(), -- Canvas extents CanvasOriginScreenSpace = ImVec2(0.0, 0.0), CanvasRectScreenSpace = ImRect(), -- Debug helpers CurrentScope = internal.ImNodesScope.None, -- Configuration state Io = ImNodes.ImNodesIO(), Style = ImNodes.ImNodesStyle(), ColorModifierStack = ImVector(), StyleModifierStack = ImVector(), TextBuffer = "", -- [Port] ImGuiTextBuffer -> string CurrentAttributeFlags = 0, AttributeFlagStack = ImVector(), -- UI element state CurrentNodeIdx = 0, CurrentPinIdx = 0, CurrentAttributeId = 0, HoveredNodeIdx = internal.INVALID_INDEX, HoveredLinkIdx = internal.INVALID_INDEX, HoveredPinIdx = internal.INVALID_INDEX, DeletedLinkIdx = internal.INVALID_INDEX, SnapLinkIdx = internal.INVALID_INDEX, -- Event helper state -- TODO: this should be a part of a state machine, and not a member of the global struct. -- Unclear what parts of the code this relates to. ImNodesUIState = internal.ImNodesUIState.None, ActiveAttributeId = 0, ActiveAttribute = false, -- ImGui::IO cache MousePos = ImVec2(0.0, 0.0), LeftMouseClicked = false, LeftMouseReleased = false, AltMouseClicked = false, LeftMouseDragging = false, AltMouseDragging = false, AltMouseScrollDelta = 0.0, MultipleSelectModifier = false, } end internal.GImNodes = nil function internal.EditorContextGet() -- No editor context was set! Did you forget to call ImNodes::CreateContext()? IM_ASSERT(internal.GImNodes.EditorCtx ~= nil) return internal.GImNodes.EditorCtx end end --------------------------------------------------------------------------- -- [SECTION] API implementation: context --------------------------------------------------------------------------- do function internal.Initialize(context) context.CanvasOriginScreenSpace = ImVec2(0.0, 0.0) context.CanvasRectScreenSpace = ImRect(ImVec2(0.0, 0.0), ImVec2(0.0, 0.0)) context.CurrentScope = internal.ImNodesScope.None context.CurrentPinIdx = INT_MAX context.CurrentNodeIdx = INT_MAX context.DefaultEditorCtx = ImNodes.EditorContextCreate() context.EditorCtx = context.DefaultEditorCtx context.CurrentAttributeFlags = ImNodes.ImNodesAttributeFlags.None context.AttributeFlagStack:push_back(internal.GImNodes.CurrentAttributeFlags) ImNodes.StyleColorsDark(context.Style) end function internal.Shutdown(ctx) ImNodes.EditorContextFree(ctx.DefaultEditorCtx) end function ImNodes.CreateContext() local ctx = internal.ImNodesContext() if internal.GImNodes == nil then ImNodes.SetCurrentContext(ctx) end internal.Initialize(ctx) return ctx end function ImNodes.DestroyContext(ctx) -- nil = destroy current context if ctx == nil then ctx = internal.GImNodes end internal.Shutdown(ctx) if internal.GImNodes == ctx then ImNodes.SetCurrentContext(nil) end end function ImNodes.GetCurrentContext() return internal.GImNodes end function ImNodes.SetCurrentContext(ctx) internal.GImNodes = ctx end function ImNodes.EditorContextCreate() return internal.ImNodesEditorContext() end function ImNodes.EditorContextFree(ctx) -- [Port] no-op: memory is garbage collected end function ImNodes.EditorContextSet(ctx) internal.GImNodes.EditorCtx = ctx end function ImNodes.EditorContextGetPanning() local editor = internal.EditorContextGet() return ImVec2(editor.Panning.x, editor.Panning.y) -- [Port] returned by value end function ImNodes.EditorContextResetPanning(pos) local editor = internal.EditorContextGet() editor.Panning = ImVec2(pos.x, pos.y) end function ImNodes.GetIO() return internal.GImNodes.Io end -- Returns the global style struct. See the struct declaration for default values. function ImNodes.GetStyle() return internal.GImNodes.Style end end --------------------------------------------------------------------------- -- Style presets --------------------------------------------------------------------------- do local Col = ImNodes.ImNodesCol function ImNodes.StyleColorsDark(dest) if dest == nil then dest = internal.GImNodes.Style end local c = dest.Colors c[Col.NodeBackground] = IM_COL32(50, 50, 50, 255) c[Col.NodeBackgroundHovered] = IM_COL32(75, 75, 75, 255) c[Col.NodeBackgroundSelected] = IM_COL32(75, 75, 75, 255) c[Col.NodeOutline] = IM_COL32(100, 100, 100, 255) -- title bar colors match ImGui's titlebg colors c[Col.TitleBar] = IM_COL32(41, 74, 122, 255) c[Col.TitleBarHovered] = IM_COL32(66, 150, 250, 255) c[Col.TitleBarSelected] = IM_COL32(66, 150, 250, 255) -- link colors match ImGui's slider grab colors c[Col.Link] = IM_COL32(61, 133, 224, 200) c[Col.LinkHovered] = IM_COL32(66, 150, 250, 255) c[Col.LinkSelected] = IM_COL32(66, 150, 250, 255) -- pin colors match ImGui's button colors c[Col.Pin] = IM_COL32(53, 150, 250, 180) c[Col.PinHovered] = IM_COL32(53, 150, 250, 255) c[Col.BoxSelector] = IM_COL32(61, 133, 224, 30) c[Col.BoxSelectorOutline] = IM_COL32(61, 133, 224, 150) c[Col.GridBackground] = IM_COL32(40, 40, 50, 200) c[Col.GridLine] = IM_COL32(200, 200, 200, 40) c[Col.GridLinePrimary] = IM_COL32(240, 240, 240, 60) -- minimap colors c[Col.MiniMapBackground] = IM_COL32(25, 25, 25, 150) c[Col.MiniMapBackgroundHovered] = IM_COL32(25, 25, 25, 200) c[Col.MiniMapOutline] = IM_COL32(150, 150, 150, 100) c[Col.MiniMapOutlineHovered] = IM_COL32(150, 150, 150, 200) c[Col.MiniMapNodeBackground] = IM_COL32(200, 200, 200, 100) c[Col.MiniMapNodeBackgroundHovered] = IM_COL32(200, 200, 200, 255) c[Col.MiniMapNodeBackgroundSelected] = c[Col.MiniMapNodeBackgroundHovered] c[Col.MiniMapNodeOutline] = IM_COL32(200, 200, 200, 100) c[Col.MiniMapLink] = c[Col.Link] c[Col.MiniMapLinkSelected] = c[Col.LinkSelected] c[Col.MiniMapCanvas] = IM_COL32(200, 200, 200, 25) c[Col.MiniMapCanvasOutline] = IM_COL32(200, 200, 200, 200) end function ImNodes.StyleColorsClassic(dest) if dest == nil then dest = internal.GImNodes.Style end local c = dest.Colors c[Col.NodeBackground] = IM_COL32(50, 50, 50, 255) c[Col.NodeBackgroundHovered] = IM_COL32(75, 75, 75, 255) c[Col.NodeBackgroundSelected] = IM_COL32(75, 75, 75, 255) c[Col.NodeOutline] = IM_COL32(100, 100, 100, 255) c[Col.TitleBar] = IM_COL32(69, 69, 138, 255) c[Col.TitleBarHovered] = IM_COL32(82, 82, 161, 255) c[Col.TitleBarSelected] = IM_COL32(82, 82, 161, 255) c[Col.Link] = IM_COL32(255, 255, 255, 100) c[Col.LinkHovered] = IM_COL32(105, 99, 204, 153) c[Col.LinkSelected] = IM_COL32(105, 99, 204, 153) c[Col.Pin] = IM_COL32(89, 102, 156, 170) c[Col.PinHovered] = IM_COL32(102, 122, 179, 200) c[Col.BoxSelector] = IM_COL32(82, 82, 161, 100) c[Col.BoxSelectorOutline] = IM_COL32(82, 82, 161, 255) c[Col.GridBackground] = IM_COL32(40, 40, 50, 200) c[Col.GridLine] = IM_COL32(200, 200, 200, 40) c[Col.GridLinePrimary] = IM_COL32(240, 240, 240, 60) -- minimap colors c[Col.MiniMapBackground] = IM_COL32(25, 25, 25, 100) c[Col.MiniMapBackgroundHovered] = IM_COL32(25, 25, 25, 200) c[Col.MiniMapOutline] = IM_COL32(150, 150, 150, 100) c[Col.MiniMapOutlineHovered] = IM_COL32(150, 150, 150, 200) c[Col.MiniMapNodeBackground] = IM_COL32(200, 200, 200, 100) c[Col.MiniMapNodeBackgroundSelected] = c[Col.MiniMapNodeBackgroundHovered] c[Col.MiniMapNodeBackgroundSelected] = IM_COL32(200, 200, 240, 255) c[Col.MiniMapNodeOutline] = IM_COL32(200, 200, 200, 100) c[Col.MiniMapLink] = c[Col.Link] c[Col.MiniMapLinkSelected] = c[Col.LinkSelected] c[Col.MiniMapCanvas] = IM_COL32(200, 200, 200, 25) c[Col.MiniMapCanvasOutline] = IM_COL32(200, 200, 200, 200) end function ImNodes.StyleColorsLight(dest) if dest == nil then dest = internal.GImNodes.Style end local c = dest.Colors c[Col.NodeBackground] = IM_COL32(240, 240, 240, 255) c[Col.NodeBackgroundHovered] = IM_COL32(240, 240, 240, 255) c[Col.NodeBackgroundSelected] = IM_COL32(240, 240, 240, 255) c[Col.NodeOutline] = IM_COL32(100, 100, 100, 255) c[Col.TitleBar] = IM_COL32(248, 248, 248, 255) c[Col.TitleBarHovered] = IM_COL32(209, 209, 209, 255) c[Col.TitleBarSelected] = IM_COL32(209, 209, 209, 255) -- original imgui values: 66, 150, 250 c[Col.Link] = IM_COL32(66, 150, 250, 100) -- original imgui values: 117, 138, 204 c[Col.LinkHovered] = IM_COL32(66, 150, 250, 242) c[Col.LinkSelected] = IM_COL32(66, 150, 250, 242) -- original imgui values: 66, 150, 250 c[Col.Pin] = IM_COL32(66, 150, 250, 160) c[Col.PinHovered] = IM_COL32(66, 150, 250, 255) c[Col.BoxSelector] = IM_COL32(90, 170, 250, 30) c[Col.BoxSelectorOutline] = IM_COL32(90, 170, 250, 150) c[Col.GridBackground] = IM_COL32(225, 225, 225, 255) c[Col.GridLine] = IM_COL32(180, 180, 180, 100) c[Col.GridLinePrimary] = IM_COL32(120, 120, 120, 100) -- minimap colors c[Col.MiniMapBackground] = IM_COL32(25, 25, 25, 100) c[Col.MiniMapBackgroundHovered] = IM_COL32(25, 25, 25, 200) c[Col.MiniMapOutline] = IM_COL32(150, 150, 150, 100) c[Col.MiniMapOutlineHovered] = IM_COL32(150, 150, 150, 200) c[Col.MiniMapNodeBackground] = IM_COL32(200, 200, 200, 100) c[Col.MiniMapNodeBackgroundSelected] = c[Col.MiniMapNodeBackgroundHovered] c[Col.MiniMapNodeBackgroundSelected] = IM_COL32(200, 200, 240, 255) c[Col.MiniMapNodeOutline] = IM_COL32(200, 200, 200, 100) c[Col.MiniMapLink] = c[Col.Link] c[Col.MiniMapLinkSelected] = c[Col.LinkSelected] c[Col.MiniMapCanvas] = IM_COL32(200, 200, 200, 25) c[Col.MiniMapCanvasOutline] = IM_COL32(200, 200, 200, 200) end end --------------------------------------------------------------------------- -- Push/Pop style --------------------------------------------------------------------------- do function ImNodes.PushColorStyle(item, color) local g = internal.GImNodes g.ColorModifierStack:push_back(internal.ImNodesColElement(g.Style.Colors[item], item)) g.Style.Colors[item] = color end function ImNodes.PopColorStyle() local g = internal.GImNodes IM_ASSERT(g.ColorModifierStack.Size > 0) local elem = g.ColorModifierStack:back() g.Style.Colors[elem.Item] = elem.Color g.ColorModifierStack:pop_back() end -- [Port] ImNodesStyleVarInfo: Offset -> field Name; Type is always ImGuiDataType_Float. Indexed by ImNodesStyleVar (0-based). local GStyleVarInfo = { [0] = { Count = 1, Name = "GridSpacing" }, { Count = 1, Name = "NodeCornerRounding" }, { Count = 2, Name = "NodePadding" }, { Count = 1, Name = "NodeBorderThickness" }, { Count = 1, Name = "LinkThickness" }, { Count = 1, Name = "LinkLineSegmentsPerLength" }, { Count = 1, Name = "LinkHoverDistance" }, { Count = 1, Name = "PinCircleRadius" }, { Count = 1, Name = "PinQuadSideLength" }, { Count = 1, Name = "PinTriangleSideLength" }, { Count = 1, Name = "PinLineThickness" }, { Count = 1, Name = "PinHoverRadius" }, { Count = 1, Name = "PinOffset" }, { Count = 2, Name = "MiniMapPadding" }, { Count = 2, Name = "MiniMapOffset" }, } local function GetStyleVarInfo(idx) IM_ASSERT(idx >= 0 and idx < ImNodes.ImNodesStyleVar.COUNT) return GStyleVarInfo[idx] end -- [Port] float and ImVec2 overloads merged; dispatch on type(value). function ImNodes.PushStyleVar(item, value) local g = internal.GImNodes local var_info = GetStyleVarInfo(item) if type(value) == "number" then IM_ASSERT(var_info.Count == 1, "Called PushStyleVar() float variant but variable is not a float!") g.StyleModifierStack:push_back(internal.ImNodesStyleVarElement(item, g.Style[var_info.Name])) g.Style[var_info.Name] = value else IM_ASSERT(var_info.Count == 2, "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!") g.StyleModifierStack:push_back(internal.ImNodesStyleVarElement(item, g.Style[var_info.Name])) g.Style[var_info.Name] = ImVec2(value.x, value.y) end end function ImNodes.PopStyleVar(count) if count == nil then count = 1 end local g = internal.GImNodes while count > 0 do IM_ASSERT(g.StyleModifierStack.Size > 0) local style_backup = g.StyleModifierStack:back() g.StyleModifierStack:pop_back() local var_info = GetStyleVarInfo(style_backup.Item) if var_info.Count == 1 then g.Style[var_info.Name] = style_backup.FloatValue[1] elseif var_info.Count == 2 then g.Style[var_info.Name] = ImVec2(style_backup.FloatValue[1], style_backup.FloatValue[2]) end count = count - 1 end end end --------------------------------------------------------------------------- -- imnodes_internal.h: [SECTION] ObjectPool implementation --------------------------------------------------------------------------- do function internal.ObjectPoolFind(objects, id) local index = objects.IdMap[id] if index == nil then return -1 end return index end -- [Port] ObjectPoolUpdate and the ImNodeData specialization merged; dispatch on objects.T. function internal.ObjectPoolUpdate(objects) local is_nodes = objects.T == internal.ImNodeData for i = 1, objects.InUse.Size do if objects.InUse[i] then if is_nodes then objects.Pool[i].PinIndices:clear() end else local id = objects.Pool[i].Id if objects.IdMap[id] == i then if is_nodes then -- Remove node idx form depth stack the first time we detect that this idx slot is -- unused local depth_stack = internal.EditorContextGet().NodeDepthOrder local elem = depth_stack:find_index(i) IM_ASSERT(elem ~= nil) depth_stack:erase(elem) end objects.IdMap[id] = nil objects.FreeList:push_back(i) end end end end function internal.ObjectPoolReset(objects) for i = 1, objects.InUse.Size do objects.InUse[i] = false end end -- [Port] ObjectPoolFindOrCreateIndex and the ImNodeData specialization merged. function internal.ObjectPoolFindOrCreateIndex(objects, id) local index = objects.IdMap[id] -- Construct new object if index == nil then if objects.FreeList:empty() then IM_ASSERT(objects.Pool.Size == objects.InUse.Size) local new_size = objects.Pool.Size + 1 objects.Pool:resize(new_size) objects.InUse:resize(new_size) index = new_size else index = objects.FreeList:back() objects.FreeList:pop_back() end objects.Pool[index] = objects.T(id) objects.IdMap[id] = index if objects.T == internal.ImNodeData then internal.EditorContextGet().NodeDepthOrder:push_back(index) end end -- Flag it as used objects.InUse[index] = true return index end function internal.ObjectPoolFindOrCreateObject(objects, id) local index = internal.ObjectPoolFindOrCreateIndex(objects, id) return objects.Pool[index] end end --------------------------------------------------------------------------- -- [SECTION] bezier curve helpers / coordinate space conversion helpers --------------------------------------------------------------------------- do function internal.EvalCubicBezier(t, P0, P1, P2, P3) -- B(t) = (1-t)**3 p0 + 3(1 - t)**2 t P1 + 3(1-t)t**2 P2 + t**3 P3 local u = 1.0 - t local b0 = u * u * u local b1 = 3 * u * u * t local b2 = 3 * u * t * t local b3 = t * t * t return ImVec2( b0 * P0.x + b1 * P1.x + b2 * P2.x + b3 * P3.x, b0 * P0.y + b1 * P1.y + b2 * P2.y + b3 * P3.y) end -- Calculates the closest point along each bezier curve segment. function internal.GetClosestPointOnCubicBezier(num_segments, p, cb) IM_ASSERT(num_segments > 0) local p_last = cb.P0 local p_closest = ImVec2() local p_closest_dist = G.FLT_MAX local t_step = 1.0 / num_segments for i = 1, num_segments do local p_current = internal.EvalCubicBezier(t_step * i, cb.P0, cb.P1, cb.P2, cb.P3) local p_line = G.ImStd.ImLineClosestPoint(p_last, p_current, p) local dist = G.ImLengthSqr(p - p_line) if dist < p_closest_dist then p_closest = p_line p_closest_dist = dist end p_last = p_current end return p_closest end function internal.GetDistanceToCubicBezier(pos, cubic_bezier, num_segments) local point_on_curve = internal.GetClosestPointOnCubicBezier(num_segments, pos, cubic_bezier) local to_curve = point_on_curve - pos return math.sqrt(G.ImLengthSqr(to_curve)) end function internal.GetContainingRectForCubicBezier(cb) local min = ImVec2(math.min(cb.P0.x, cb.P3.x), math.min(cb.P0.y, cb.P3.y)) local max = ImVec2(math.max(cb.P0.x, cb.P3.x), math.max(cb.P0.y, cb.P3.y)) local hover_distance = internal.GImNodes.Style.LinkHoverDistance local rect = ImRect(min, max) rect:Add(cb.P1) rect:Add(cb.P2) rect:Expand(ImVec2(hover_distance, hover_distance)) return rect end function internal.GetCubicBezier(start, end_, start_type, line_segments_per_length) IM_ASSERT(start_type == internal.ImNodesAttributeType.Input or start_type == internal.ImNodesAttributeType.Output) if start_type == internal.ImNodesAttributeType.Input then start, end_ = end_, start end local link_length = math.sqrt(G.ImLengthSqr(end_ - start)) local offset = ImVec2(0.25 * link_length, 0.0) return { P0 = start, P1 = start + offset, P2 = end_ - offset, P3 = end_, NumSegments = math.max(math.floor(link_length * line_segments_per_length), 1), } end function internal.EvalImplicitLineEq(p1, p2, p) return (p2.y - p1.y) * p.x + (p1.x - p2.x) * p.y + (p2.x * p1.y - p1.x * p2.y) end local function Sign(val) return (val > 0.0 and 1 or 0) - (val < 0.0 and 1 or 0) end function internal.RectangleOverlapsLineSegment(rect, p1, p2) -- Trivial case: rectangle contains an endpoint if rect:Contains(p1) or rect:Contains(p2) then return true end -- Flip rectangle if necessary local flip_rect = ImRect( math.min(rect.Min.x, rect.Max.x), math.min(rect.Min.y, rect.Max.y), math.max(rect.Min.x, rect.Max.x), math.max(rect.Min.y, rect.Max.y)) -- Trivial case: line segment lies to one particular side of rectangle if (p1.x < flip_rect.Min.x and p2.x < flip_rect.Min.x) or (p1.x > flip_rect.Max.x and p2.x > flip_rect.Max.x) or (p1.y < flip_rect.Min.y and p2.y < flip_rect.Min.y) or (p1.y > flip_rect.Max.y and p2.y > flip_rect.Max.y) then return false end local corner_signs = { Sign(internal.EvalImplicitLineEq(p1, p2, flip_rect.Min)), Sign(internal.EvalImplicitLineEq(p1, p2, ImVec2(flip_rect.Max.x, flip_rect.Min.y))), Sign(internal.EvalImplicitLineEq(p1, p2, ImVec2(flip_rect.Min.x, flip_rect.Max.y))), Sign(internal.EvalImplicitLineEq(p1, p2, flip_rect.Max)), } local sum = 0 local sum_abs = 0 for i = 1, 4 do sum = sum + corner_signs[i] sum_abs = sum_abs + math.abs(corner_signs[i]) end -- At least one corner of rectangle lies on a different side of line segment return math.abs(sum) ~= sum_abs end function internal.RectangleOverlapsBezier(rectangle, cb) local current = internal.EvalCubicBezier(0.0, cb.P0, cb.P1, cb.P2, cb.P3) local dt = 1.0 / cb.NumSegments for s = 0, cb.NumSegments - 1 do local next_ = internal.EvalCubicBezier((s + 1) * dt, cb.P0, cb.P1, cb.P2, cb.P3) if internal.RectangleOverlapsLineSegment(rectangle, current, next_) then return true end current = next_ end return false end function internal.RectangleOverlapsLink(rectangle, start, end_, start_type) -- First level: simple rejection test via rectangle overlap: local lrect = ImRect( math.min(start.x, end_.x), math.min(start.y, end_.y), math.max(start.x, end_.x), math.max(start.y, end_.y)) if rectangle:Overlaps(lrect) then -- First, check if either one or both endpoinds are trivially contained -- in the rectangle if rectangle:Contains(start) or rectangle:Contains(end_) then return true end -- Second level of refinement: do a more expensive test against the -- link local cubic_bezier = internal.GetCubicBezier(start, end_, start_type, internal.GImNodes.Style.LinkLineSegmentsPerLength) return internal.RectangleOverlapsBezier(rectangle, cubic_bezier) end return false end function internal.ScreenSpaceToGridSpace(editor, v) return v - internal.GImNodes.CanvasOriginScreenSpace - editor.Panning end function internal.ScreenSpaceToGridSpaceRect(editor, r) return ImRect(internal.ScreenSpaceToGridSpace(editor, r.Min), internal.ScreenSpaceToGridSpace(editor, r.Max)) end function internal.GridSpaceToScreenSpace(editor, v) return v + internal.GImNodes.CanvasOriginScreenSpace + editor.Panning end function internal.GridSpaceToEditorSpace(editor, v) return v + editor.Panning end function internal.EditorSpaceToGridSpace(editor, v) return v - editor.Panning end function internal.EditorSpaceToScreenSpace(v) return internal.GImNodes.CanvasOriginScreenSpace + v end function internal.MiniMapSpaceToGridSpace(editor, v) return (v - editor.MiniMapContentScreenSpace.Min) / editor.MiniMapScaling + editor.GridContentBounds.Min end function internal.ScreenSpaceToMiniMapSpace(editor, v) return (internal.ScreenSpaceToGridSpace(editor, v) - editor.GridContentBounds.Min) * editor.MiniMapScaling + editor.MiniMapContentScreenSpace.Min end function internal.ScreenSpaceToMiniMapSpaceRect(editor, r) return ImRect(internal.ScreenSpaceToMiniMapSpace(editor, r.Min), internal.ScreenSpaceToMiniMapSpace(editor, r.Max)) end end --------------------------------------------------------------------------- -- [SECTION] draw list helper --------------------------------------------------------------------------- do -- [Port] channel indices are 0-based like ImDrawListSplitter in the core port; _Channels.Data is 1-based. function internal.ImDrawListGrowChannels(draw_list, num_channels) local splitter = draw_list._Splitter if splitter._Count == 1 then splitter:Split(draw_list, num_channels + 1) return end -- NOTE: this logic has been lifted from ImDrawListSplitter::Split with slight modifications -- to allow nested splits. The main modification is that we only create new ImDrawChannel -- instances after splitter._Count, instead of over the whole splitter._Channels array like -- the regular ImDrawListSplitter::Split method does. local old_channel_capacity = splitter._Channels.Size -- NOTE: _Channels is not resized down, and therefore _Count <= _Channels.size()! local old_channel_count = splitter._Count local requested_channel_count = old_channel_count + num_channels if old_channel_capacity < old_channel_count + num_channels then splitter._Channels:resize(requested_channel_count) end splitter._Count = requested_channel_count local channels = splitter._Channels.Data for i = old_channel_count, requested_channel_count - 1 do local channel = channels[i + 1] -- If we're inside the old capacity region of the array, we need to reuse the existing -- memory of the command and index buffers. if i < old_channel_capacity and channel ~= nil and channel._CmdBuffer ~= nil then channel._CmdBuffer:resize(0) channel._IdxBuffer:resize(0) else -- Else, we need to construct new draw channels. channel = G.ImDrawChannel() channels[i + 1] = channel end do local draw_cmd = G.ImDrawCmd() G.ImVec4_Copy(draw_cmd.ClipRect, draw_list._ClipRectStack:back()) draw_cmd.TexRef = draw_list._TextureStack:back() channel._CmdBuffer:push_back(draw_cmd) end end end function internal.ImDrawListSplitterSwapChannels(splitter, lhs_idx, rhs_idx) if lhs_idx == rhs_idx then return end IM_ASSERT(lhs_idx >= 0 and lhs_idx < splitter._Count) IM_ASSERT(rhs_idx >= 0 and rhs_idx < splitter._Count) local lhs_channel = splitter._Channels.Data[lhs_idx + 1] local rhs_channel = splitter._Channels.Data[rhs_idx + 1] lhs_channel._CmdBuffer, rhs_channel._CmdBuffer = rhs_channel._CmdBuffer, lhs_channel._CmdBuffer lhs_channel._IdxBuffer, rhs_channel._IdxBuffer = rhs_channel._IdxBuffer, lhs_channel._IdxBuffer local current_channel = splitter._Current if current_channel == lhs_idx then splitter._Current = rhs_idx elseif current_channel == rhs_idx then splitter._Current = lhs_idx end end function internal.DrawListSet(window_draw_list) local g = internal.GImNodes g.CanvasDrawList = window_draw_list g.NodeIdxToSubmissionIdx = {} g.NodeIdxSubmissionOrder:clear() end -- The draw list channels are structured as follows. First we have our base channel, the canvas grid -- on which we render the grid lines in BeginNodeEditor(). The base channel is the reason -- draw_list_submission_idx_to_background_channel_idx offsets the index by one. Each BeginNode() -- call appends two new draw channels, for the node background and foreground. The node foreground -- is the channel into which the node's ImGui content is rendered. Finally, in EndNodeEditor() we -- append one last draw channel for rendering the selection box and the incomplete link on top of -- everything else. -- -- [Port] submission indices are 0-based (as upstream); NodeIdxSubmissionOrder[s + 1] holds submission s. function internal.DrawListAddNode(node_idx) local g = internal.GImNodes g.NodeIdxToSubmissionIdx[node_idx] = g.NodeIdxSubmissionOrder.Size g.NodeIdxSubmissionOrder:push_back(node_idx) internal.ImDrawListGrowChannels(g.CanvasDrawList, 2) end function internal.DrawListAppendClickInteractionChannel() -- NOTE: don't use this function outside of EndNodeEditor. Using this before all nodes have been -- added will screw up the node draw order. internal.ImDrawListGrowChannels(internal.GImNodes.CanvasDrawList, 1) end function internal.DrawListSubmissionIdxToBackgroundChannelIdx(submission_idx) -- NOTE: the first channel is the canvas background, i.e. the grid return 1 + 2 * submission_idx end function internal.DrawListSubmissionIdxToForegroundChannelIdx(submission_idx) return internal.DrawListSubmissionIdxToBackgroundChannelIdx(submission_idx) + 1 end function internal.DrawListActivateClickInteractionChannel() local dl = internal.GImNodes.CanvasDrawList dl._Splitter:SetCurrentChannel(dl, dl._Splitter._Count - 1) end function internal.DrawListActivateCurrentNodeForeground() local g = internal.GImNodes local foreground_channel_idx = internal.DrawListSubmissionIdxToForegroundChannelIdx(g.NodeIdxSubmissionOrder.Size - 1) g.CanvasDrawList._Splitter:SetCurrentChannel(g.CanvasDrawList, foreground_channel_idx) end function internal.DrawListActivateNodeBackground(node_idx) local g = internal.GImNodes local submission_idx = g.NodeIdxToSubmissionIdx[node_idx] -- There is a discrepancy in the submitted node count and the rendered node count! Did you call -- one of the following functions -- * EditorContextMoveToNode -- * SetNodeScreenSpacePos -- * SetNodeGridSpacePos -- * SetNodeDraggable -- after the BeginNode/EndNode function calls? IM_ASSERT(submission_idx ~= nil) local background_channel_idx = internal.DrawListSubmissionIdxToBackgroundChannelIdx(submission_idx) g.CanvasDrawList._Splitter:SetCurrentChannel(g.CanvasDrawList, background_channel_idx) end function internal.DrawListSwapSubmissionIndices(lhs_idx, rhs_idx) IM_ASSERT(lhs_idx ~= rhs_idx) local splitter = internal.GImNodes.CanvasDrawList._Splitter internal.ImDrawListSplitterSwapChannels(splitter, internal.DrawListSubmissionIdxToBackgroundChannelIdx(lhs_idx), internal.DrawListSubmissionIdxToBackgroundChannelIdx(rhs_idx)) internal.ImDrawListSplitterSwapChannels(splitter, internal.DrawListSubmissionIdxToForegroundChannelIdx(lhs_idx), internal.DrawListSubmissionIdxToForegroundChannelIdx(rhs_idx)) end -- [Port] loop variables are 0-based like upstream; ImVector reads use [k + 1]. function internal.DrawListSortChannelsByDepth(node_idx_depth_order) local order = internal.GImNodes.NodeIdxSubmissionOrder if order.Size < 2 then return end IM_ASSERT(node_idx_depth_order.Size == order.Size) local start_idx = node_idx_depth_order.Size - 1 while node_idx_depth_order[start_idx + 1] == order[start_idx + 1] do start_idx = start_idx - 1 if start_idx == 0 then -- early out if submission order and depth order are the same return end end -- TODO: this is an O(N^2) algorithm. It might be worthwhile revisiting this to see if the time -- complexity can be reduced. for depth_idx = start_idx, 1, -1 do local node_idx = node_idx_depth_order[depth_idx + 1] -- Find the current index of the node_idx in the submission order array local submission_idx = -1 for i = 0, order.Size - 1 do if order[i + 1] == node_idx then submission_idx = i break end end IM_ASSERT(submission_idx >= 0) if submission_idx ~= depth_idx then for j = submission_idx, depth_idx - 1 do internal.DrawListSwapSubmissionIndices(j, j + 1) order[j + 1], order[j + 2] = order[j + 2], order[j + 1] end end end end end --------------------------------------------------------------------------- -- [SECTION] ui state logic --------------------------------------------------------------------------- do local ClickType = internal.ImNodesClickInteractionType local INVALID_INDEX = internal.INVALID_INDEX function internal.GetScreenSpacePinCoordinates(node_rect, attribute_rect, type_) IM_ASSERT(type_ == internal.ImNodesAttributeType.Input or type_ == internal.ImNodesAttributeType.Output) local x if type_ == internal.ImNodesAttributeType.Input then x = node_rect.Min.x - internal.GImNodes.Style.PinOffset else x = node_rect.Max.x + internal.GImNodes.Style.PinOffset end return ImVec2(x, 0.5 * (attribute_rect.Min.y + attribute_rect.Max.y)) end function internal.MouseInCanvas() -- This flag should be true either when hovering or clicking something in the canvas. local is_window_hovered_or_focused = ImGui.IsWindowHovered() or ImGui.IsWindowFocused() return is_window_hovered_or_focused and internal.GImNodes.CanvasRectScreenSpace:Contains(ImGui.GetMousePos()) end function internal.BeginNodeSelection(editor, node_idx) local g = internal.GImNodes -- Don't start selecting a node if we are e.g. already creating and dragging -- a new link! New link creation can happen when the mouse is clicked over -- a node, but within the hover radius of a pin. if editor.ClickInteraction.Type ~= ClickType.None then return end editor.ClickInteraction.Type = ClickType.Node -- If the node is not already contained in the selection, then we want only -- the interaction node to be selected, effective immediately. -- -- If the multiple selection modifier is active, we want to add this node -- to the current list of selected nodes. -- -- Otherwise, we want to allow for the possibility of multiple nodes to be -- moved at once. if not editor.SelectedNodeIndices:contains(node_idx) then editor.SelectedLinkIndices:clear() if not g.MultipleSelectModifier then editor.SelectedNodeIndices:clear() end editor.SelectedNodeIndices:push_back(node_idx) -- Ensure that individually selected nodes get rendered on top local depth_stack = editor.NodeDepthOrder local elem = depth_stack:find_index(node_idx) IM_ASSERT(elem ~= nil) depth_stack:erase(elem) depth_stack:push_back(node_idx) elseif g.MultipleSelectModifier then -- Deselect a previously-selected node editor.SelectedNodeIndices:find_erase(node_idx) -- Don't allow dragging after deselecting editor.ClickInteraction.Type = ClickType.None end -- To support snapping of multiple nodes, we need to store the offset of -- each node in the selection to the origin of the dragged node. local ref_origin = editor.Nodes.Pool[node_idx].Origin editor.PrimaryNodeOffset = ref_origin + g.CanvasOriginScreenSpace + editor.Panning - g.MousePos editor.SelectedNodeOffsets:clear() for idx = 1, editor.SelectedNodeIndices.Size do local node = editor.SelectedNodeIndices[idx] editor.SelectedNodeOffsets:push_back(editor.Nodes.Pool[node].Origin - ref_origin) end end function internal.BeginLinkSelection(editor, link_idx) editor.ClickInteraction.Type = ClickType.Link -- When a link is selected, clear all other selections, and insert the link -- as the sole selection. editor.SelectedNodeIndices:clear() editor.SelectedLinkIndices:clear() editor.SelectedLinkIndices:push_back(link_idx) end function internal.BeginLinkDetach(editor, link_idx, detach_pin_idx) local link = editor.Links.Pool[link_idx] local state = editor.ClickInteraction state.Type = ClickType.LinkCreation state.LinkCreation.EndPinIdx = INVALID_INDEX state.LinkCreation.StartPinIdx = (detach_pin_idx == link.StartPinIdx and{link.EndPinIdx }or{link.StartPinIdx })[1] internal.GImNodes.DeletedLinkIdx = link_idx end function internal.BeginLinkCreation(editor, hovered_pin_idx) editor.ClickInteraction.Type = ClickType.LinkCreation editor.ClickInteraction.LinkCreation.StartPinIdx = hovered_pin_idx editor.ClickInteraction.LinkCreation.EndPinIdx = INVALID_INDEX editor.ClickInteraction.LinkCreation.Type = internal.ImNodesLinkCreationType.Standard local g = internal.GImNodes g.ImNodesUIState = bit32.bor(g.ImNodesUIState, internal.ImNodesUIState.LinkStarted) end -- [Port] pin_idx is optional (nil or INVALID_INDEX = no value) function internal.BeginLinkInteraction(editor, link_idx, pin_idx) local g = internal.GImNodes -- Check if we are clicking the link with the modifier pressed. -- This will in a link detach via clicking. local modifier = g.Io.LinkDetachWithModifierClick.Modifier local modifier_pressed = modifier ~= nil and modifier() if modifier_pressed then local link = editor.Links.Pool[link_idx] local start_pin = editor.Pins.Pool[link.StartPinIdx] local end_pin = editor.Pins.Pool[link.EndPinIdx] local mouse_pos = g.MousePos local dist_to_start = G.ImLengthSqr(start_pin.Pos - mouse_pos) local dist_to_end = G.ImLengthSqr(end_pin.Pos - mouse_pos) local closest_pin_idx = (dist_to_start < dist_to_end and{link.StartPinIdx }or{link.EndPinIdx })[1] editor.ClickInteraction.Type = ClickType.LinkCreation internal.BeginLinkDetach(editor, link_idx, closest_pin_idx) editor.ClickInteraction.LinkCreation.Type = internal.ImNodesLinkCreationType.FromDetach elseif pin_idx ~= nil and pin_idx ~= INVALID_INDEX then local hovered_pin_flags = editor.Pins.Pool[pin_idx].Flags -- Check the 'click and drag to detach' case. if bit32.band(hovered_pin_flags, ImNodes.ImNodesAttributeFlags.EnableLinkDetachWithDragClick) ~= 0 then internal.BeginLinkDetach(editor, link_idx, pin_idx) editor.ClickInteraction.LinkCreation.Type = internal.ImNodesLinkCreationType.FromDetach else internal.BeginLinkCreation(editor, pin_idx) end else internal.BeginLinkSelection(editor, link_idx) end end function internal.BeginCanvasInteraction(editor) local g = internal.GImNodes local any_ui_element_hovered = g.HoveredNodeIdx ~= INVALID_INDEX or g.HoveredLinkIdx ~= INVALID_INDEX or g.HoveredPinIdx ~= INVALID_INDEX or ImGui.IsAnyItemHovered() local mouse_not_in_canvas = not internal.MouseInCanvas() if editor.ClickInteraction.Type ~= ClickType.None or any_ui_element_hovered or mouse_not_in_canvas or not ImGui.IsWindowHovered() then return end local started_panning = g.AltMouseClicked if started_panning then editor.ClickInteraction.Type = ClickType.Panning elseif g.LeftMouseClicked then editor.ClickInteraction.Type = ClickType.BoxSelection editor.ClickInteraction.BoxSelector.Rect.Min = internal.ScreenSpaceToGridSpace(editor, g.MousePos) end end function internal.BoxSelectorUpdateSelection(editor, box_rect) -- Invert box selector coordinates as needed box_rect = ImRect( math.min(box_rect.Min.x, box_rect.Max.x), math.min(box_rect.Min.y, box_rect.Max.y), math.max(box_rect.Min.x, box_rect.Max.x), math.max(box_rect.Min.y, box_rect.Max.y)) -- Update node selection editor.SelectedNodeIndices:clear() -- Test for overlap against node rectangles for node_idx = 1, editor.Nodes.Pool.Size do if editor.Nodes.InUse[node_idx] then local node = editor.Nodes.Pool[node_idx] if box_rect:Overlaps(node.Rect) then editor.SelectedNodeIndices:push_back(node_idx) end end end -- Update link selection editor.SelectedLinkIndices:clear() -- Test for overlap against links for link_idx = 1, editor.Links.Pool.Size do if editor.Links.InUse[link_idx] then local link = editor.Links.Pool[link_idx] local pin_start = editor.Pins.Pool[link.StartPinIdx] local pin_end = editor.Pins.Pool[link.EndPinIdx] local node_start_rect = editor.Nodes.Pool[pin_start.ParentNodeIdx].Rect local node_end_rect = editor.Nodes.Pool[pin_end.ParentNodeIdx].Rect local start = internal.GetScreenSpacePinCoordinates(node_start_rect, pin_start.AttributeRect, pin_start.Type) local end_ = internal.GetScreenSpacePinCoordinates(node_end_rect, pin_end.AttributeRect, pin_end.Type) -- Test if internal.RectangleOverlapsLink(box_rect, start, end_, pin_start.Type) then editor.SelectedLinkIndices:push_back(link_idx) end end end end function internal.SnapOriginToGrid(origin) local g = internal.GImNodes if bit32.band(g.Style.Flags, ImNodes.ImNodesStyleFlags.GridSnapping) ~= 0 then local spacing = g.Style.GridSpacing local spacing2 = spacing * 0.5 -- Snap the origin to the nearest grid point in any direction local modx = math.fmod(math.abs(origin.x) + spacing2, spacing) - spacing2 local mody = math.fmod(math.abs(origin.y) + spacing2, spacing) - spacing2 local x, y = origin.x - modx, origin.y - mody if origin.x < 0.0 then x = origin.x + modx end if origin.y < 0.0 then y = origin.y + mody end return ImVec2(x, y) end return origin end function internal.TranslateSelectedNodes(editor) local g = internal.GImNodes if g.LeftMouseDragging then -- If we have grid snap enabled, don't start moving nodes until we've moved the mouse -- slightly local shouldTranslate = true if bit32.band(g.Style.Flags, ImNodes.ImNodesStyleFlags.GridSnapping) ~= 0 then shouldTranslate = ImGui.GetIO().MouseDragMaxDistanceSqr[0] > 5.0 end local origin = internal.SnapOriginToGrid(g.MousePos - g.CanvasOriginScreenSpace - editor.Panning + editor.PrimaryNodeOffset) for i = 1, editor.SelectedNodeIndices.Size do local node_rel = editor.SelectedNodeOffsets[i] local node = editor.Nodes.Pool[editor.SelectedNodeIndices[i] ] if node.Draggable and shouldTranslate then node.Origin = origin + node_rel + editor.AutoPanningDelta end end end end -- [Port] LinkPredicate folded in: links are equal if they join the same pins, in either order. function internal.FindDuplicateLink(editor, start_pin_idx, end_pin_idx) local lo, hi = math.min(start_pin_idx, end_pin_idx), math.max(start_pin_idx, end_pin_idx) for link_idx = 1, editor.Links.Pool.Size do local link = editor.Links.Pool[link_idx] if editor.Links.InUse[link_idx] and math.min(link.StartPinIdx, link.EndPinIdx) == lo and math.max(link.StartPinIdx, link.EndPinIdx) == hi then return link_idx end end return INVALID_INDEX end function internal.ShouldLinkSnapToPin(editor, start_pin, hovered_pin_idx, duplicate_link) local end_pin = editor.Pins.Pool[hovered_pin_idx] -- The end pin must be in a different node if start_pin.ParentNodeIdx == end_pin.ParentNodeIdx then return false end -- The end pin must be of a different type if start_pin.Type == end_pin.Type then return false end -- The link to be created must not be a duplicate, unless it is the link which was created on -- snap. In that case we want to snap, since we want it to appear visually as if the created -- link remains snapped to the pin. if duplicate_link ~= INVALID_INDEX and duplicate_link ~= internal.GImNodes.SnapLinkIdx then return false end return true end function internal.GetScreenSpacePinCoordinatesForPin(editor, pin) local parent_node_rect = editor.Nodes.Pool[pin.ParentNodeIdx].Rect return internal.GetScreenSpacePinCoordinates(parent_node_rect, pin.AttributeRect, pin.Type) end local function UpdateLinkCreation(editor) local g = internal.GImNodes local lc = editor.ClickInteraction.LinkCreation local start_pin = editor.Pins.Pool[lc.StartPinIdx] local hovered = g.HoveredPinIdx ~= INVALID_INDEX local maybe_duplicate_link_idx = (hovered and{(internal.FindDuplicateLink(editor, lc.StartPinIdx, g.HoveredPinIdx) )}or{INVALID_INDEX })[1] local should_snap = hovered and internal.ShouldLinkSnapToPin(editor, start_pin, g.HoveredPinIdx, maybe_duplicate_link_idx) -- If we created on snap and the hovered pin is empty or changed, then we need signal that -- the link's state has changed. local snapping_pin_changed = lc.EndPinIdx ~= INVALID_INDEX and g.HoveredPinIdx ~= lc.EndPinIdx -- Detach the link that was created by this link event if it's no longer in snap range if snapping_pin_changed and g.SnapLinkIdx ~= INVALID_INDEX then internal.BeginLinkDetach(editor, g.SnapLinkIdx, lc.EndPinIdx) end local start_pos = internal.GetScreenSpacePinCoordinatesForPin(editor, start_pin) -- If we are within the hover radius of a receiving pin, snap the link -- endpoint to it local end_pos = (should_snap and{(internal.GetScreenSpacePinCoordinatesForPin(editor, editor.Pins.Pool[g.HoveredPinIdx]) )}or{g.MousePos })[1] local cubic_bezier = internal.GetCubicBezier(start_pos, end_pos, start_pin.Type, g.Style.LinkLineSegmentsPerLength) g.CanvasDrawList:AddBezierCubic(cubic_bezier.P0, cubic_bezier.P1, cubic_bezier.P2, cubic_bezier.P3, g.Style.Colors[ImNodes.ImNodesCol.Link], g.Style.LinkThickness, cubic_bezier.NumSegments) local link_creation_on_snap = hovered and bit32.band(editor.Pins.Pool[g.HoveredPinIdx].Flags, ImNodes.ImNodesAttributeFlags.EnableLinkCreationOnSnap) ~= 0 if not should_snap then lc.EndPinIdx = INVALID_INDEX end local create_link = should_snap and (g.LeftMouseReleased or link_creation_on_snap) if create_link and maybe_duplicate_link_idx == INVALID_INDEX then -- Avoid send OnLinkCreated() events every frame if the snap link is not saved -- (only applies for EnableLinkCreationOnSnap) if not g.LeftMouseReleased and lc.EndPinIdx == g.HoveredPinIdx then return end g.ImNodesUIState = bit32.bor(g.ImNodesUIState, internal.ImNodesUIState.LinkCreated) lc.EndPinIdx = g.HoveredPinIdx end if g.LeftMouseReleased then editor.ClickInteraction.Type = ClickType.None if not create_link then g.ImNodesUIState = bit32.bor(g.ImNodesUIState, internal.ImNodesUIState.LinkDropped) end end end function internal.ClickInteractionUpdate(editor) local g = internal.GImNodes local t = editor.ClickInteraction.Type if t == ClickType.BoxSelection then local selector = editor.ClickInteraction.BoxSelector selector.Rect.Max = internal.ScreenSpaceToGridSpace(editor, g.MousePos) local box_rect = ImRect(internal.GridSpaceToScreenSpace(editor, selector.Rect.Min), internal.GridSpaceToScreenSpace(editor, selector.Rect.Max)) internal.BoxSelectorUpdateSelection(editor, box_rect) local box_selector_color = g.Style.Colors[ImNodes.ImNodesCol.BoxSelector] local box_selector_outline = g.Style.Colors[ImNodes.ImNodesCol.BoxSelectorOutline] g.CanvasDrawList:AddRectFilled(box_rect.Min, box_rect.Max, box_selector_color) g.CanvasDrawList:AddRect(box_rect.Min, box_rect.Max, box_selector_outline) if g.LeftMouseReleased then local depth_stack = editor.NodeDepthOrder local selected_idxs = editor.SelectedNodeIndices -- Bump the selected node indices, in order, to the top of the depth stack. -- NOTE: this algorithm has worst case time complexity of O(N^2), if the node selection -- is ~ N (due to selected_idxs.contains()). if selected_idxs.Size > 0 and selected_idxs.Size < depth_stack.Size then local num_moved = 0 -- The number of indices moved. Stop after selected_idxs.Size for i = 1, depth_stack.Size - selected_idxs.Size do local node_idx = depth_stack[i] while selected_idxs:contains(node_idx) do depth_stack:erase(i) depth_stack:push_back(node_idx) num_moved = num_moved + 1 node_idx = depth_stack[i] end if num_moved == selected_idxs.Size then break end end end editor.ClickInteraction.Type = ClickType.None end elseif t == ClickType.Node then internal.TranslateSelectedNodes(editor) if g.LeftMouseReleased then editor.ClickInteraction.Type = ClickType.None end elseif t == ClickType.Link then if g.LeftMouseReleased then editor.ClickInteraction.Type = ClickType.None end elseif t == ClickType.LinkCreation then UpdateLinkCreation(editor) elseif t == ClickType.Panning then local dragging = g.AltMouseDragging if dragging then editor.Panning = editor.Panning + ImGui.GetIO().MouseDelta else editor.ClickInteraction.Type = ClickType.None end elseif t == ClickType.ImGuiItem then if g.LeftMouseReleased then editor.ClickInteraction.Type = ClickType.None end elseif t == ClickType.None then -- nothing else IM_ASSERT(false, "Unreachable code!") end end function internal.ResolveOccludedPins(editor, occluded_pin_indices) local depth_stack = editor.NodeDepthOrder occluded_pin_indices:resize(0) if depth_stack.Size < 2 then return end -- For each node in the depth stack for depth_idx = 1, depth_stack.Size - 1 do local node_below = editor.Nodes.Pool[depth_stack[depth_idx] ] -- Iterate over the rest of the depth stack to find nodes overlapping the pins for next_depth_idx = depth_idx + 1, depth_stack.Size do local rect_above = editor.Nodes.Pool[depth_stack[next_depth_idx] ].Rect -- Iterate over each pin for idx = 1, node_below.PinIndices.Size do local pin_idx = node_below.PinIndices[idx] if rect_above:Contains(editor.Pins.Pool[pin_idx].Pos) then occluded_pin_indices:push_back(pin_idx) end end end end end function internal.ResolveHoveredPin(pins, occluded_pin_indices) local g = internal.GImNodes local smallest_distance = G.FLT_MAX local pin_idx_with_smallest_distance = INVALID_INDEX local hover_radius_sqr = g.Style.PinHoverRadius * g.Style.PinHoverRadius for idx = 1, pins.Pool.Size do if pins.InUse[idx] and not occluded_pin_indices:contains(idx) then local distance_sqr = G.ImLengthSqr(pins.Pool[idx].Pos - g.MousePos) -- TODO: GImNodes->Style.PinHoverRadius needs to be copied into pin data and the pin-local -- value used here. This is no longer called in BeginAttribute/EndAttribute scope and the -- detected pin might have a different hover radius than what the user had when calling -- BeginAttribute/EndAttribute. if distance_sqr < hover_radius_sqr and distance_sqr < smallest_distance then smallest_distance = distance_sqr pin_idx_with_smallest_distance = idx end end end return pin_idx_with_smallest_distance end function internal.ResolveHoveredNode(depth_stack) local overlapping = internal.GImNodes.NodeIndicesOverlappingWithMouse if overlapping.Size == 0 then return INVALID_INDEX end if overlapping.Size == 1 then return overlapping[1] end local largest_depth_idx = -1 local node_idx_on_top = -1 for i = 1, overlapping.Size do local node_idx = overlapping[i] for depth_idx = 1, depth_stack.Size do if depth_stack[depth_idx] == node_idx and depth_idx > largest_depth_idx then largest_depth_idx = depth_idx node_idx_on_top = node_idx end end end IM_ASSERT(node_idx_on_top ~= -1) return node_idx_on_top end function internal.ResolveHoveredLink(links, pins) local g = internal.GImNodes local smallest_distance = G.FLT_MAX local link_idx_with_smallest_distance = INVALID_INDEX -- There are two ways a link can be detected as "hovered". -- 1. The link is within hover distance to the mouse. The closest such link is selected as being -- hovered over. -- 2. If the link is connected to the currently hovered pin. -- -- The latter is a requirement for link detaching with drag click to work, as both a link and -- pin are required to be hovered over for the feature to work. for idx = 1, links.Pool.Size do if links.InUse[idx] then local link = links.Pool[idx] local start_pin = pins.Pool[link.StartPinIdx] local end_pin = pins.Pool[link.EndPinIdx] -- If there is a hovered pin links can only be considered hovered if they use that pin if g.HoveredPinIdx ~= INVALID_INDEX then if g.HoveredPinIdx == link.StartPinIdx or g.HoveredPinIdx == link.EndPinIdx then return idx end else -- TODO: the calculated CubicBeziers could be cached since we generate them again when -- rendering the links local cubic_bezier = internal.GetCubicBezier(start_pin.Pos, end_pin.Pos, start_pin.Type, g.Style.LinkLineSegmentsPerLength) -- The distance test local link_rect = internal.GetContainingRectForCubicBezier(cubic_bezier) -- First, do a simple bounding box test against the box containing the link -- to see whether calculating the distance to the link is worth doing. if link_rect:Contains(g.MousePos) then local distance = internal.GetDistanceToCubicBezier(g.MousePos, cubic_bezier, cubic_bezier.NumSegments) if distance < g.Style.LinkHoverDistance and distance < smallest_distance then smallest_distance = distance link_idx_with_smallest_distance = idx end end end end end return link_idx_with_smallest_distance end end --------------------------------------------------------------------------- -- [SECTION] render helpers --------------------------------------------------------------------------- do local Col = ImNodes.ImNodesCol local PinShape = ImNodes.ImNodesPinShape function internal.GetItemRect() return ImRect(ImGui.GetItemRectMin(), ImGui.GetItemRectMax()) end function internal.GetNodeTitleBarOrigin(node) return node.Origin + node.LayoutStyle.Padding end function internal.GetNodeContentOrigin(node) local title_bar_height = ImVec2(0.0, node.TitleBarContentRect:GetHeight() + 2.0 * node.LayoutStyle.Padding.y) return node.Origin + title_bar_height + node.LayoutStyle.Padding end function internal.GetNodeTitleRect(node) local expanded_title_rect = ImRect(node.TitleBarContentRect.Min, node.TitleBarContentRect.Max) expanded_title_rect:Expand(node.LayoutStyle.Padding) return ImRect( expanded_title_rect.Min, expanded_title_rect.Min + ImVec2(node.Rect:GetWidth(), 0.0) + ImVec2(0.0, expanded_title_rect:GetHeight())) end function internal.DrawGrid(editor, canvas_size) local g = internal.GImNodes local offset = editor.Panning local line_color = g.Style.Colors[Col.GridLine] local line_color_prim = g.Style.Colors[Col.GridLinePrimary] local draw_primary = bit32.band(g.Style.Flags, ImNodes.ImNodesStyleFlags.GridLinesPrimary) ~= 0 local spacing = g.Style.GridSpacing -- [Port] C fmodf keeps the sign of the dividend, like math.fmod local x = math.fmod(offset.x, spacing) while x < canvas_size.x do local col = line_color if offset.x - x == 0.0 and draw_primary then col = line_color_prim end g.CanvasDrawList:AddLine(internal.EditorSpaceToScreenSpace(ImVec2(x, 0.0)), internal.EditorSpaceToScreenSpace(ImVec2(x, canvas_size.y)), col) x = x + spacing end local y = math.fmod(offset.y, spacing) while y < canvas_size.y do local col = line_color if offset.y - y == 0.0 and draw_primary then col = line_color_prim end g.CanvasDrawList:AddLine(internal.EditorSpaceToScreenSpace(ImVec2(0.0, y)), internal.EditorSpaceToScreenSpace(ImVec2(canvas_size.x, y)), col) y = y + spacing end end local function CalculateQuadOffsets(side_length) local half_side = 0.5 * side_length return { TopLeft = ImVec2(-half_side, half_side), BottomLeft = ImVec2(-half_side, -half_side), BottomRight = ImVec2(half_side, -half_side), TopRight = ImVec2(half_side, half_side), } end local function CalculateTriangleOffsets(side_length) -- Calculates the Vec2 offsets from an equilateral triangle's midpoint to -- its vertices. Here is how the left_offset and right_offset are -- calculated. -- -- For an equilateral triangle of side length s, the -- triangle's height, h, is h = s * sqrt(3) / 2. -- -- The length from the base to the midpoint is (1 / 3) * h. The length from -- the midpoint to the triangle vertex is (2 / 3) * h. local sqrt_3 = math.sqrt(3.0) local left_offset = -0.1666666666667 * sqrt_3 * side_length local right_offset = 0.333333333333 * sqrt_3 * side_length local vertical_offset = 0.5 * side_length return { TopLeft = ImVec2(left_offset, vertical_offset), BottomLeft = ImVec2(left_offset, -vertical_offset), Right = ImVec2(right_offset, 0.0), } end local CIRCLE_NUM_SEGMENTS = 8 function internal.DrawPinShape(pin_pos, pin, pin_color) local g = internal.GImNodes local dl = g.CanvasDrawList local shape = pin.Shape if shape == PinShape.Circle then dl:AddCircle(pin_pos, g.Style.PinCircleRadius, pin_color, CIRCLE_NUM_SEGMENTS, g.Style.PinLineThickness) elseif shape == PinShape.CircleFilled then dl:AddCircleFilled(pin_pos, g.Style.PinCircleRadius, pin_color, CIRCLE_NUM_SEGMENTS) elseif shape == PinShape.Quad then local offset = CalculateQuadOffsets(g.Style.PinQuadSideLength) dl:AddQuad(pin_pos + offset.TopLeft, pin_pos + offset.BottomLeft, pin_pos + offset.BottomRight, pin_pos + offset.TopRight, pin_color, g.Style.PinLineThickness) elseif shape == PinShape.QuadFilled then local offset = CalculateQuadOffsets(g.Style.PinQuadSideLength) dl:AddQuadFilled(pin_pos + offset.TopLeft, pin_pos + offset.BottomLeft, pin_pos + offset.BottomRight, pin_pos + offset.TopRight, pin_color) elseif shape == PinShape.Triangle then local offset = CalculateTriangleOffsets(g.Style.PinTriangleSideLength) dl:AddTriangle(pin_pos + offset.TopLeft, pin_pos + offset.BottomLeft, pin_pos + offset.Right, pin_color, -- NOTE: for some weird reason, the line drawn by AddTriangle is -- much thinner than the lines drawn by AddCircle or AddQuad. -- Multiplying the line thickness by two seemed to solve the -- problem at a few different thickness values. 2.0 * g.Style.PinLineThickness) elseif shape == PinShape.TriangleFilled then local offset = CalculateTriangleOffsets(g.Style.PinTriangleSideLength) dl:AddTriangleFilled(pin_pos + offset.TopLeft, pin_pos + offset.BottomLeft, pin_pos + offset.Right, pin_color) else IM_ASSERT(false, "Invalid PinShape value!") end end function internal.DrawPin(editor, pin_idx) local pin = editor.Pins.Pool[pin_idx] local parent_node_rect = editor.Nodes.Pool[pin.ParentNodeIdx].Rect pin.Pos = internal.GetScreenSpacePinCoordinates(parent_node_rect, pin.AttributeRect, pin.Type) local pin_color = pin.ColorStyle.Background if internal.GImNodes.HoveredPinIdx == pin_idx then pin_color = pin.ColorStyle.Hovered end internal.DrawPinShape(pin.Pos, pin, pin_color) end function internal.DrawNode(editor, node_idx) local g = internal.GImNodes local node = editor.Nodes.Pool[node_idx] ImGui.SetCursorPos(node.Origin + editor.Panning) local node_hovered = g.HoveredNodeIdx == node_idx and editor.ClickInteraction.Type ~= internal.ImNodesClickInteractionType.BoxSelection local node_background = node.ColorStyle.Background local titlebar_background = node.ColorStyle.Titlebar if editor.SelectedNodeIndices:contains(node_idx) then node_background = node.ColorStyle.BackgroundSelected titlebar_background = node.ColorStyle.TitlebarSelected elseif node_hovered then node_background = node.ColorStyle.BackgroundHovered titlebar_background = node.ColorStyle.TitlebarHovered end do -- node base g.CanvasDrawList:AddRectFilled(node.Rect.Min, node.Rect.Max, node_background, node.LayoutStyle.CornerRounding) -- title bar: if node.TitleBarContentRect:GetHeight() > 0.0 then local title_bar_rect = internal.GetNodeTitleRect(node) g.CanvasDrawList:AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, titlebar_background, node.LayoutStyle.CornerRounding, G.ImDrawFlags.RoundCornersTop) end if bit32.band(g.Style.Flags, ImNodes.ImNodesStyleFlags.NodeOutline) ~= 0 then g.CanvasDrawList:AddRect(node.Rect.Min, node.Rect.Max, node.ColorStyle.Outline, node.LayoutStyle.CornerRounding, node.LayoutStyle.BorderThickness, G.ImDrawFlags.RoundCornersAll) end end for i = 1, node.PinIndices.Size do internal.DrawPin(editor, node.PinIndices[i]) end if node_hovered then g.HoveredNodeIdx = node_idx end end function internal.DrawLink(editor, link_idx) local g = internal.GImNodes local link = editor.Links.Pool[link_idx] local start_pin = editor.Pins.Pool[link.StartPinIdx] local end_pin = editor.Pins.Pool[link.EndPinIdx] local cubic_bezier = internal.GetCubicBezier(start_pin.Pos, end_pin.Pos, start_pin.Type, g.Style.LinkLineSegmentsPerLength) local link_hovered = g.HoveredLinkIdx == link_idx and editor.ClickInteraction.Type ~= internal.ImNodesClickInteractionType.BoxSelection if link_hovered then g.HoveredLinkIdx = link_idx end -- It's possible for a link to be deleted in begin_link_interaction. A user -- may detach a link, resulting in the link wire snapping to the mouse -- position. -- -- In other words, skip rendering the link if it was deleted. if g.DeletedLinkIdx == link_idx then return end local link_color = link.ColorStyle.Base if editor.SelectedLinkIndices:contains(link_idx) then link_color = link.ColorStyle.Selected elseif link_hovered then link_color = link.ColorStyle.Hovered end g.CanvasDrawList:AddBezierCubic(cubic_bezier.P0, cubic_bezier.P1, cubic_bezier.P2, cubic_bezier.P3, link_color, g.Style.LinkThickness, cubic_bezier.NumSegments) end function internal.BeginPinAttribute(id, type_, shape, node_idx) local g = internal.GImNodes -- Make sure to call BeginNode() before calling -- BeginAttribute() IM_ASSERT(g.CurrentScope == internal.ImNodesScope.Node) g.CurrentScope = internal.ImNodesScope.Attribute ImGui.BeginGroup() ImGui.PushID(id) local editor = internal.EditorContextGet() g.CurrentAttributeId = id local pin_idx = internal.ObjectPoolFindOrCreateIndex(editor.Pins, id) g.CurrentPinIdx = pin_idx local pin = editor.Pins.Pool[pin_idx] pin.Id = id pin.ParentNodeIdx = node_idx pin.Type = type_ pin.Shape = shape pin.Flags = g.CurrentAttributeFlags pin.ColorStyle.Background = g.Style.Colors[Col.Pin] pin.ColorStyle.Hovered = g.Style.Colors[Col.PinHovered] end function internal.EndPinAttribute() local g = internal.GImNodes IM_ASSERT(g.CurrentScope == internal.ImNodesScope.Attribute) g.CurrentScope = internal.ImNodesScope.Node ImGui.PopID() ImGui.EndGroup() if ImGui.IsItemActive() then g.ActiveAttribute = true g.ActiveAttributeId = g.CurrentAttributeId end local editor = internal.EditorContextGet() local pin = editor.Pins.Pool[g.CurrentPinIdx] local node = editor.Nodes.Pool[g.CurrentNodeIdx] pin.AttributeRect = internal.GetItemRect() node.PinIndices:push_back(g.CurrentPinIdx) end end --------------------------------------------------------------------------- -- [SECTION] minimap --------------------------------------------------------------------------- do local Col = ImNodes.ImNodesCol local Loc = ImNodes.ImNodesMiniMapLocation local ClickType = internal.ImNodesClickInteractionType local function ImFloorVec2(v) return ImVec2(math.floor(v.x), math.floor(v.y)) end function internal.IsMiniMapActive() local editor = internal.EditorContextGet() return editor.MiniMapEnabled and editor.MiniMapSizeFraction > 0.0 end function internal.IsMiniMapHovered() local editor = internal.EditorContextGet() return internal.IsMiniMapActive() and ImGui.IsMouseHoveringRect(editor.MiniMapRectScreenSpace.Min, editor.MiniMapRectScreenSpace.Max) end function internal.CalcMiniMapLayout() local g = internal.GImNodes local editor = internal.EditorContextGet() local offset = g.Style.MiniMapOffset local border = g.Style.MiniMapPadding local editor_rect = g.CanvasRectScreenSpace -- Compute the size of the mini-map area local mini_map_size, mini_map_scaling do local max_size = ImFloorVec2(editor_rect:GetSize() * editor.MiniMapSizeFraction - border * 2.0) local max_size_aspect_ratio = max_size.x / max_size.y local grid_content_size = (editor.GridContentBounds:IsInverted() and{max_size }or{(ImFloorVec2(editor.GridContentBounds:GetSize()) )})[1] local grid_content_aspect_ratio = grid_content_size.x / grid_content_size.y mini_map_size = ImFloorVec2((grid_content_aspect_ratio > max_size_aspect_ratio and{(ImVec2(max_size.x, max_size.x / grid_content_aspect_ratio) )}or{(ImVec2(max_size.y * grid_content_aspect_ratio, max_size.y))})[1]) mini_map_scaling = mini_map_size.x / grid_content_size.x end -- Compute location of the mini-map local mini_map_pos do local loc = editor.MiniMapLocation local align = ImVec2( (loc == Loc.BottomRight or loc == Loc.TopRight )and 1.0 or 0.0, (loc == Loc.BottomRight or loc == Loc.BottomLeft )and 1.0 or 0.0) local top_left_pos = editor_rect.Min + offset + border local bottom_right_pos = editor_rect.Max - offset - border - mini_map_size mini_map_pos = ImFloorVec2(ImVec2( top_left_pos.x + (bottom_right_pos.x - top_left_pos.x) * align.x, top_left_pos.y + (bottom_right_pos.y - top_left_pos.y) * align.y)) end editor.MiniMapRectScreenSpace = ImRect(mini_map_pos - border, mini_map_pos + mini_map_size + border) editor.MiniMapContentScreenSpace = ImRect(mini_map_pos, mini_map_pos + mini_map_size) editor.MiniMapScaling = mini_map_scaling end local function MiniMapDrawNode(editor, node_idx) local g = internal.GImNodes local node = editor.Nodes.Pool[node_idx] local node_rect = internal.ScreenSpaceToMiniMapSpaceRect(editor, node.Rect) -- Round to near whole pixel value for corner-rounding to prevent visual glitches local mini_map_node_rounding = math.floor(node.LayoutStyle.CornerRounding * editor.MiniMapScaling) local mini_map_node_background if editor.ClickInteraction.Type == ClickType.None and ImGui.IsMouseHoveringRect(node_rect.Min, node_rect.Max) then mini_map_node_background = g.Style.Colors[Col.MiniMapNodeBackgroundHovered] -- Run user callback when hovering a mini-map node if editor.MiniMapNodeHoveringCallback then editor.MiniMapNodeHoveringCallback(node.Id, editor.MiniMapNodeHoveringCallbackUserData) end elseif editor.SelectedNodeIndices:contains(node_idx) then mini_map_node_background = g.Style.Colors[Col.MiniMapNodeBackgroundSelected] else mini_map_node_background = g.Style.Colors[Col.MiniMapNodeBackground] end local mini_map_node_outline = g.Style.Colors[Col.MiniMapNodeOutline] g.CanvasDrawList:AddRectFilled(node_rect.Min, node_rect.Max, mini_map_node_background, mini_map_node_rounding) g.CanvasDrawList:AddRect(node_rect.Min, node_rect.Max, mini_map_node_outline, mini_map_node_rounding) end local function MiniMapDrawLink(editor, link_idx) local g = internal.GImNodes local link = editor.Links.Pool[link_idx] local start_pin = editor.Pins.Pool[link.StartPinIdx] local end_pin = editor.Pins.Pool[link.EndPinIdx] local cubic_bezier = internal.GetCubicBezier( internal.ScreenSpaceToMiniMapSpace(editor, start_pin.Pos), internal.ScreenSpaceToMiniMapSpace(editor, end_pin.Pos), start_pin.Type, g.Style.LinkLineSegmentsPerLength / editor.MiniMapScaling) -- It's possible for a link to be deleted in begin_link_interaction. A user -- may detach a link, resulting in the link wire snapping to the mouse -- position. -- -- In other words, skip rendering the link if it was deleted. if g.DeletedLinkIdx == link_idx then return end local link_color = g.Style.Colors[(editor.SelectedLinkIndices:contains(link_idx) and{Col.MiniMapLinkSelected }or{Col.MiniMapLink})[1] ] g.CanvasDrawList:AddBezierCubic(cubic_bezier.P0, cubic_bezier.P1, cubic_bezier.P2, cubic_bezier.P3, link_color, g.Style.LinkThickness * editor.MiniMapScaling, cubic_bezier.NumSegments) end function internal.MiniMapUpdate() local g = internal.GImNodes local editor = internal.EditorContextGet() local mini_map_background if internal.IsMiniMapHovered() then mini_map_background = g.Style.Colors[Col.MiniMapBackgroundHovered] else mini_map_background = g.Style.Colors[Col.MiniMapBackground] end -- Create a child window bellow mini-map, so it blocks all mouse interaction on canvas. local flags = G.ImGuiWindowFlags.NoBackground ImGui.SetCursorScreenPos(editor.MiniMapRectScreenSpace.Min) ImGui.BeginChild("minimap", editor.MiniMapRectScreenSpace:GetSize(), false, flags) local mini_map_rect = editor.MiniMapRectScreenSpace -- Draw minimap background and border g.CanvasDrawList:AddRectFilled(mini_map_rect.Min, mini_map_rect.Max, mini_map_background) g.CanvasDrawList:AddRect(mini_map_rect.Min, mini_map_rect.Max, g.Style.Colors[Col.MiniMapOutline]) -- Clip draw list items to mini-map rect (after drawing background/outline) g.CanvasDrawList:PushClipRect(mini_map_rect.Min, mini_map_rect.Max, true --[[ intersect with editor clip-rect ]]) -- Draw links first so they appear under nodes, and we can use the same draw channel for link_idx = 1, editor.Links.Pool.Size do if editor.Links.InUse[link_idx] then MiniMapDrawLink(editor, link_idx) end end for node_idx = 1, editor.Nodes.Pool.Size do if editor.Nodes.InUse[node_idx] then MiniMapDrawNode(editor, node_idx) end end -- Draw editor canvas rect inside mini-map do local canvas_color = g.Style.Colors[Col.MiniMapCanvas] local outline_color = g.Style.Colors[Col.MiniMapCanvasOutline] local rect = internal.ScreenSpaceToMiniMapSpaceRect(editor, g.CanvasRectScreenSpace) g.CanvasDrawList:AddRectFilled(rect.Min, rect.Max, canvas_color) g.CanvasDrawList:AddRect(rect.Min, rect.Max, outline_color) end -- Have to pop mini-map clip rect g.CanvasDrawList:PopClipRect() local mini_map_is_hovered = ImGui.IsWindowHovered() ImGui.EndChild() local center_on_click = mini_map_is_hovered and ImGui.IsMouseDown(G.ImGuiMouseButton.Left) and editor.ClickInteraction.Type == ClickType.None and not g.NodeIdxSubmissionOrder:empty() if center_on_click then local target = internal.MiniMapSpaceToGridSpace(editor, ImGui.GetMousePos()) local center = g.CanvasRectScreenSpace:GetSize() * 0.5 editor.Panning = ImFloorVec2(center - target) end -- Reset callback info after use editor.MiniMapNodeHoveringCallback = nil editor.MiniMapNodeHoveringCallbackUserData = nil end end --------------------------------------------------------------------------- -- [SECTION] selection helpers --------------------------------------------------------------------------- do function internal.SelectObject(objects, selected_indices, id) local idx = internal.ObjectPoolFind(objects, id) IM_ASSERT(idx >= 0) IM_ASSERT(not selected_indices:contains(idx)) selected_indices:push_back(idx) end function internal.ClearObjectSelection(objects, selected_indices, id) local idx = internal.ObjectPoolFind(objects, id) IM_ASSERT(idx >= 0) IM_ASSERT(selected_indices:contains(idx)) selected_indices:find_erase_unsorted(idx) end function internal.IsObjectSelected(objects, selected_indices, id) local idx = internal.ObjectPoolFind(objects, id) return selected_indices:contains(idx) end end --------------------------------------------------------------------------- -- [SECTION] API implementation: editor --------------------------------------------------------------------------- do local Col = ImNodes.ImNodesCol local Scope = internal.ImNodesScope local ClickType = internal.ImNodesClickInteractionType local INVALID_INDEX = internal.INVALID_INDEX function ImNodes.EditorContextMoveToNode(node_id) local editor = internal.EditorContextGet() local node = internal.ObjectPoolFindOrCreateObject(editor.Nodes, node_id) editor.Panning = ImVec2(-node.Origin.x, -node.Origin.y) end function ImNodes.BeginNodeEditor() local g = internal.GImNodes IM_ASSERT(g.CurrentScope == Scope.None) g.CurrentScope = Scope.Editor -- Reset state from previous pass local editor = internal.EditorContextGet() editor.AutoPanningDelta = ImVec2(0, 0) editor.GridContentBounds = ImRect(G.FLT_MAX, G.FLT_MAX, -G.FLT_MAX, -G.FLT_MAX) editor.MiniMapEnabled = false internal.ObjectPoolReset(editor.Nodes) internal.ObjectPoolReset(editor.Pins) internal.ObjectPoolReset(editor.Links) g.HoveredNodeIdx = INVALID_INDEX g.HoveredLinkIdx = INVALID_INDEX g.HoveredPinIdx = INVALID_INDEX g.DeletedLinkIdx = INVALID_INDEX g.SnapLinkIdx = INVALID_INDEX g.NodeIndicesOverlappingWithMouse:clear() g.ImNodesUIState = internal.ImNodesUIState.None local imgui_io = ImGui.GetIO() local emulate = g.Io.EmulateThreeButtonMouse.Modifier g.MousePos = ImVec2(imgui_io.MousePos.x, imgui_io.MousePos.y) g.LeftMouseClicked = ImGui.IsMouseClicked(0) g.LeftMouseReleased = ImGui.IsMouseReleased(0) g.LeftMouseDragging = ImGui.IsMouseDragging(0, 0.0) g.AltMouseClicked = (emulate ~= nil and emulate() and g.LeftMouseClicked) or ImGui.IsMouseClicked(g.Io.AltMouseButton) g.AltMouseDragging = (emulate ~= nil and g.LeftMouseDragging and emulate()) or ImGui.IsMouseDragging(g.Io.AltMouseButton, 0.0) g.AltMouseScrollDelta = imgui_io.MouseWheel if g.Io.MultipleSelectModifier.Modifier ~= nil then g.MultipleSelectModifier = g.Io.MultipleSelectModifier.Modifier() else g.MultipleSelectModifier = imgui_io.KeyCtrl end g.ActiveAttribute = false ImGui.BeginGroup() do ImGui.PushStyleVar(G.ImGuiStyleVar.FramePadding, ImVec2(1.0, 1.0)) ImGui.PushStyleVar(G.ImGuiStyleVar.WindowPadding, ImVec2(0.0, 0.0)) ImGui.PushStyleColor(G.ImGuiCol.ChildBg, g.Style.Colors[Col.GridBackground]) ImGui.BeginChild("scrolling_region", ImVec2(0.0, 0.0), true, bit32.bor(G.ImGuiWindowFlags.NoScrollbar, G.ImGuiWindowFlags.NoMove, G.ImGuiWindowFlags.NoScrollWithMouse)) g.CanvasOriginScreenSpace = ImGui.GetCursorScreenPos() -- NOTE: we have to fetch the canvas draw list *after* we call -- BeginChild(), otherwise the ImGui UI elements are going to be -- rendered into the parent window draw list. internal.DrawListSet(ImGui.GetWindowDrawList()) do local canvas_size = ImGui.GetWindowSize() g.CanvasRectScreenSpace = ImRect(internal.EditorSpaceToScreenSpace(ImVec2(0.0, 0.0)), internal.EditorSpaceToScreenSpace(canvas_size)) if bit32.band(g.Style.Flags, ImNodes.ImNodesStyleFlags.GridLines) ~= 0 then internal.DrawGrid(editor, canvas_size) end end end end function ImNodes.EndNodeEditor() local g = internal.GImNodes IM_ASSERT(g.CurrentScope == Scope.Editor) g.CurrentScope = Scope.None local editor = internal.EditorContextGet() local no_grid_content = editor.GridContentBounds:IsInverted() if no_grid_content then editor.GridContentBounds = internal.ScreenSpaceToGridSpaceRect(editor, g.CanvasRectScreenSpace) end -- Detect ImGui interaction first, because it blocks interaction with the rest of the UI if g.LeftMouseClicked and ImGui.IsAnyItemActive() then editor.ClickInteraction.Type = ClickType.ImGuiItem end -- Detect which UI element is being hovered over. Detection is done in a hierarchical fashion, -- because a UI element being hovered excludes any other as being hovered over. -- Don't do hovering detection for nodes/links/pins when interacting with the mini-map, since -- its an *overlay* with its own interaction behavior and must have precedence during mouse -- interaction. if (editor.ClickInteraction.Type == ClickType.None or editor.ClickInteraction.Type == ClickType.LinkCreation) and internal.MouseInCanvas() and not internal.IsMiniMapHovered() then -- Pins needs some special care. We need to check the depth stack to see which pins are -- being occluded by other nodes. internal.ResolveOccludedPins(editor, g.OccludedPinIndices) g.HoveredPinIdx = internal.ResolveHoveredPin(editor.Pins, g.OccludedPinIndices) if g.HoveredPinIdx == INVALID_INDEX then -- Resolve which node is actually on top and being hovered using the depth stack. g.HoveredNodeIdx = internal.ResolveHoveredNode(editor.NodeDepthOrder) end -- We don't check for hovered pins here, because if we want to detach a link by clicking and -- dragging, we need to have both a link and pin hovered. if g.HoveredNodeIdx == INVALID_INDEX then g.HoveredLinkIdx = internal.ResolveHoveredLink(editor.Links, editor.Pins) end end for node_idx = 1, editor.Nodes.Pool.Size do if editor.Nodes.InUse[node_idx] then internal.DrawListActivateNodeBackground(node_idx) internal.DrawNode(editor, node_idx) end end -- In order to render the links underneath the nodes, we want to first select the bottom draw -- channel. g.CanvasDrawList:ChannelsSetCurrent(0) for link_idx = 1, editor.Links.Pool.Size do if editor.Links.InUse[link_idx] then internal.DrawLink(editor, link_idx) end end -- Render the click interaction UI elements (partial links, box selector) on top of everything -- else. internal.DrawListAppendClickInteractionChannel() internal.DrawListActivateClickInteractionChannel() if internal.IsMiniMapActive() then internal.CalcMiniMapLayout() internal.MiniMapUpdate() end -- Handle node graph interaction if not internal.IsMiniMapHovered() then if g.LeftMouseClicked and g.HoveredLinkIdx ~= INVALID_INDEX then internal.BeginLinkInteraction(editor, g.HoveredLinkIdx, g.HoveredPinIdx) elseif g.LeftMouseClicked and g.HoveredPinIdx ~= INVALID_INDEX then internal.BeginLinkCreation(editor, g.HoveredPinIdx) elseif g.LeftMouseClicked and g.HoveredNodeIdx ~= INVALID_INDEX then internal.BeginNodeSelection(editor, g.HoveredNodeIdx) elseif g.LeftMouseClicked or g.LeftMouseReleased or g.AltMouseClicked or g.AltMouseScrollDelta ~= 0.0 then internal.BeginCanvasInteraction(editor) end local should_auto_pan = editor.ClickInteraction.Type == ClickType.BoxSelection or editor.ClickInteraction.Type == ClickType.LinkCreation or editor.ClickInteraction.Type == ClickType.Node if should_auto_pan and not internal.MouseInCanvas() then local mouse = ImGui.GetMousePos() local center = g.CanvasRectScreenSpace:GetCenter() local direction = center - mouse direction = direction * G.ImInvLength(direction, 0.0) editor.AutoPanningDelta = direction * ImGui.GetIO().DeltaTime * g.Io.AutoPanningSpeed editor.Panning = editor.Panning + editor.AutoPanningDelta end end internal.ClickInteractionUpdate(editor) -- At this point, draw commands have been issued for all nodes (and pins). Update the node pool -- to detect unused node slots and remove those indices from the depth stack before sorting the -- node draw commands by depth. internal.ObjectPoolUpdate(editor.Nodes) internal.ObjectPoolUpdate(editor.Pins) internal.DrawListSortChannelsByDepth(editor.NodeDepthOrder) -- After the links have been rendered, the link pool can be updated as well. internal.ObjectPoolUpdate(editor.Links) -- Finally, merge the draw channels g.CanvasDrawList:ChannelsMerge() -- pop style ImGui.EndChild() -- end scrolling region ImGui.PopStyleColor() -- pop child window background color ImGui.PopStyleVar() -- pop window padding ImGui.PopStyleVar() -- pop frame padding ImGui.EndGroup() end function ImNodes.BeginNode(node_id) local g = internal.GImNodes -- Remember to call BeginNodeEditor before calling BeginNode IM_ASSERT(g.CurrentScope == Scope.Editor) g.CurrentScope = Scope.Node local editor = internal.EditorContextGet() local node_idx = internal.ObjectPoolFindOrCreateIndex(editor.Nodes, node_id) g.CurrentNodeIdx = node_idx local node = editor.Nodes.Pool[node_idx] local c = g.Style.Colors node.ColorStyle.Background = c[Col.NodeBackground] node.ColorStyle.BackgroundHovered = c[Col.NodeBackgroundHovered] node.ColorStyle.BackgroundSelected = c[Col.NodeBackgroundSelected] node.ColorStyle.Outline = c[Col.NodeOutline] node.ColorStyle.Titlebar = c[Col.TitleBar] node.ColorStyle.TitlebarHovered = c[Col.TitleBarHovered] node.ColorStyle.TitlebarSelected = c[Col.TitleBarSelected] node.LayoutStyle.CornerRounding = g.Style.NodeCornerRounding node.LayoutStyle.Padding = ImVec2(g.Style.NodePadding.x, g.Style.NodePadding.y) node.LayoutStyle.BorderThickness = g.Style.NodeBorderThickness -- ImGui::SetCursorPos sets the cursor position, local to the current widget -- (in this case, the child object started in BeginNodeEditor). Use -- ImGui::SetCursorScreenPos to set the screen space coordinates directly. ImGui.SetCursorPos(internal.GridSpaceToEditorSpace(editor, internal.GetNodeTitleBarOrigin(node))) internal.DrawListAddNode(node_idx) internal.DrawListActivateCurrentNodeForeground() ImGui.PushID(node.Id) ImGui.BeginGroup() end function ImNodes.EndNode() local g = internal.GImNodes IM_ASSERT(g.CurrentScope == Scope.Node) g.CurrentScope = Scope.Editor local editor = internal.EditorContextGet() -- The node's rectangle depends on the ImGui UI group size. ImGui.EndGroup() ImGui.PopID() local node = editor.Nodes.Pool[g.CurrentNodeIdx] node.Rect = internal.GetItemRect() node.Rect:Expand(node.LayoutStyle.Padding) editor.GridContentBounds:Add(node.Origin) editor.GridContentBounds:Add(node.Origin + node.Rect:GetSize()) if node.Rect:Contains(g.MousePos) then g.NodeIndicesOverlappingWithMouse:push_back(g.CurrentNodeIdx) end end function ImNodes.GetNodeDimensions(node_id) local editor = internal.EditorContextGet() local node_idx = internal.ObjectPoolFind(editor.Nodes, node_id) IM_ASSERT(node_idx ~= -1) -- invalid node_id return editor.Nodes.Pool[node_idx].Rect:GetSize() end function ImNodes.BeginNodeTitleBar() IM_ASSERT(internal.GImNodes.CurrentScope == Scope.Node) ImGui.BeginGroup() end function ImNodes.EndNodeTitleBar() local g = internal.GImNodes IM_ASSERT(g.CurrentScope == Scope.Node) ImGui.EndGroup() local editor = internal.EditorContextGet() local node = editor.Nodes.Pool[g.CurrentNodeIdx] node.TitleBarContentRect = internal.GetItemRect() ImGui.ItemAdd(internal.GetNodeTitleRect(node), ImGui.GetID("title_bar")) ImGui.SetCursorPos(internal.GridSpaceToEditorSpace(editor, internal.GetNodeContentOrigin(node))) end -- [Port] shape defaults to ImNodesPinShape_CircleFilled, as in imnodes.h function ImNodes.BeginInputAttribute(id, shape) if shape == nil then shape = ImNodes.ImNodesPinShape.CircleFilled end internal.BeginPinAttribute(id, internal.ImNodesAttributeType.Input, shape, internal.GImNodes.CurrentNodeIdx) end function ImNodes.EndInputAttribute() internal.EndPinAttribute() end function ImNodes.BeginOutputAttribute(id, shape) if shape == nil then shape = ImNodes.ImNodesPinShape.CircleFilled end internal.BeginPinAttribute(id, internal.ImNodesAttributeType.Output, shape, internal.GImNodes.CurrentNodeIdx) end function ImNodes.EndOutputAttribute() internal.EndPinAttribute() end function ImNodes.BeginStaticAttribute(id) local g = internal.GImNodes -- Make sure to call BeginNode() before calling BeginAttribute() IM_ASSERT(g.CurrentScope == Scope.Node) g.CurrentScope = Scope.Attribute g.CurrentAttributeId = id ImGui.BeginGroup() ImGui.PushID(id) end function ImNodes.EndStaticAttribute() local g = internal.GImNodes -- Make sure to call BeginNode() before calling BeginAttribute() IM_ASSERT(g.CurrentScope == Scope.Attribute) g.CurrentScope = Scope.Node ImGui.PopID() ImGui.EndGroup() if ImGui.IsItemActive() then g.ActiveAttribute = true g.ActiveAttributeId = g.CurrentAttributeId end end function ImNodes.Link(id, start_attr_id, end_attr_id) local g = internal.GImNodes IM_ASSERT(g.CurrentScope == Scope.Editor) local editor = internal.EditorContextGet() local link = internal.ObjectPoolFindOrCreateObject(editor.Links, id) link.Id = id link.StartPinIdx = internal.ObjectPoolFindOrCreateIndex(editor.Pins, start_attr_id) link.EndPinIdx = internal.ObjectPoolFindOrCreateIndex(editor.Pins, end_attr_id) link.ColorStyle.Base = g.Style.Colors[Col.Link] link.ColorStyle.Hovered = g.Style.Colors[Col.LinkHovered] link.ColorStyle.Selected = g.Style.Colors[Col.LinkSelected] -- Check if this link was created by the current link event local lc = editor.ClickInteraction.LinkCreation if (editor.ClickInteraction.Type == ClickType.LinkCreation and bit32.band(editor.Pins.Pool[link.EndPinIdx].Flags, ImNodes.ImNodesAttributeFlags.EnableLinkCreationOnSnap) ~= 0 and lc.StartPinIdx == link.StartPinIdx and lc.EndPinIdx == link.EndPinIdx) or (lc.StartPinIdx == link.EndPinIdx and lc.EndPinIdx == link.StartPinIdx) then g.SnapLinkIdx = internal.ObjectPoolFindOrCreateIndex(editor.Links, id) end end function ImNodes.SetNodeScreenSpacePos(node_id, screen_space_pos) local editor = internal.EditorContextGet() local node = internal.ObjectPoolFindOrCreateObject(editor.Nodes, node_id) node.Origin = internal.ScreenSpaceToGridSpace(editor, screen_space_pos) end function ImNodes.SetNodeEditorSpacePos(node_id, editor_space_pos) local editor = internal.EditorContextGet() local node = internal.ObjectPoolFindOrCreateObject(editor.Nodes, node_id) node.Origin = internal.EditorSpaceToGridSpace(editor, editor_space_pos) end function ImNodes.SetNodeGridSpacePos(node_id, grid_pos) local editor = internal.EditorContextGet() local node = internal.ObjectPoolFindOrCreateObject(editor.Nodes, node_id) node.Origin = ImVec2(grid_pos.x, grid_pos.y) end function ImNodes.SetNodeDraggable(node_id, draggable) local editor = internal.EditorContextGet() local node = internal.ObjectPoolFindOrCreateObject(editor.Nodes, node_id) node.Draggable = draggable end function ImNodes.GetNodeScreenSpacePos(node_id) local editor = internal.EditorContextGet() local node_idx = internal.ObjectPoolFind(editor.Nodes, node_id) IM_ASSERT(node_idx ~= -1) return internal.GridSpaceToScreenSpace(editor, editor.Nodes.Pool[node_idx].Origin) end function ImNodes.GetNodeEditorSpacePos(node_id) local editor = internal.EditorContextGet() local node_idx = internal.ObjectPoolFind(editor.Nodes, node_id) IM_ASSERT(node_idx ~= -1) return internal.GridSpaceToEditorSpace(editor, editor.Nodes.Pool[node_idx].Origin) end function ImNodes.GetNodeGridSpacePos(node_id) local editor = internal.EditorContextGet() local node_idx = internal.ObjectPoolFind(editor.Nodes, node_id) IM_ASSERT(node_idx ~= -1) local origin = editor.Nodes.Pool[node_idx].Origin return ImVec2(origin.x, origin.y) -- [Port] returned by value end -- [Port] *ToIniString returns the string (data_size dropped: use #s). *IniFile variants not available on Roblox. local function trunc(v) return (v < 0 and{(math.ceil(v) )}or{(math.floor(v) )})[1] end function ImNodes.SaveEditorStateToIniString(editor) IM_ASSERT(editor ~= nil) local out = { string.format("[editor]\npanning=%d,%d\n", trunc(editor.Panning.x), trunc(editor.Panning.y)) } for i = 1, editor.Nodes.Pool.Size do if editor.Nodes.InUse[i] then local node = editor.Nodes.Pool[i] table.insert(out, string.format("\n[node.%d]\norigin=%d,%d\n", node.Id, trunc(node.Origin.x), trunc(node.Origin.y))) end end return table.concat(out) end function ImNodes.SaveCurrentEditorStateToIniString() return ImNodes.SaveEditorStateToIniString(internal.EditorContextGet()) end function ImNodes.LoadEditorStateFromIniString(editor, data) if data == nil or #data == 0 then return end editor = editor or internal.EditorContextGet() local handler = nil for line in __iter(string.gmatch(data, "[^\r\n]+")) do if string.sub(line, 1, 1) ~= ";" then if string.match(line, "^%[.*%]$") then if string.sub(line, 2, 5) == "node" then handler = "node" elseif line == "[editor]" then handler = "editor" end end if handler == "node" then local id = tonumber(string.match(line, "^%[node%.(%-?%d+)")) if id then local node_idx = internal.ObjectPoolFindOrCreateIndex(editor.Nodes, id) internal.GImNodes.CurrentNodeIdx = node_idx editor.Nodes.Pool[node_idx].Id = id else local x, y = string.match(line, "^origin=(%-?%d+),(%-?%d+)") if x then editor.Nodes.Pool[internal.GImNodes.CurrentNodeIdx].Origin = internal.SnapOriginToGrid(ImVec2(tonumber(x), tonumber(y))) end end elseif handler == "editor" then local x, y = string.match(line, "^panning=([^,]+),(.+)$") if x and tonumber(x) and tonumber(y) then editor.Panning = ImVec2(tonumber(x), tonumber(y)) end end end end end function ImNodes.LoadCurrentEditorStateFromIniString(data) ImNodes.LoadEditorStateFromIniString(internal.EditorContextGet(), data) end function ImNodes.MiniMap(minimap_size_fraction, location, node_hovering_callback, node_hovering_callback_data) minimap_size_fraction = minimap_size_fraction or 0.2 location = location or ImNodes.ImNodesMiniMapLocation.TopLeft -- Check that editor size fraction is sane; must be in the range (0, 1] IM_ASSERT(minimap_size_fraction > 0.0 and minimap_size_fraction <= 1.0) -- Remember to call before EndNodeEditor IM_ASSERT(internal.GImNodes.CurrentScope == Scope.Editor) local editor = internal.EditorContextGet() editor.MiniMapEnabled = true editor.MiniMapSizeFraction = minimap_size_fraction editor.MiniMapLocation = location -- Set node hovering callback information editor.MiniMapNodeHoveringCallback = node_hovering_callback editor.MiniMapNodeHoveringCallbackUserData = node_hovering_callback_data -- Actual drawing/updating of the MiniMap is done in EndNodeEditor so that -- mini map is draw over everything and all pin/link positions are updated -- correctly relative to their respective nodes. end function ImNodes.PushAttributeFlag(flag) local g = internal.GImNodes g.CurrentAttributeFlags = bit32.bor(g.CurrentAttributeFlags, flag) g.AttributeFlagStack:push_back(g.CurrentAttributeFlags) end function ImNodes.PopAttributeFlag() local g = internal.GImNodes -- PopAttributeFlag called without a matching PushAttributeFlag! -- The bottom value is always the default value, pushed in Initialize(). IM_ASSERT(g.AttributeFlagStack.Size > 1) g.AttributeFlagStack:pop_back() g.CurrentAttributeFlags = g.AttributeFlagStack:back() end function ImNodes.SnapNodeToGrid(node_id) local editor = internal.EditorContextGet() local node = internal.ObjectPoolFindOrCreateObject(editor.Nodes, node_id) node.Origin = internal.SnapOriginToGrid(node.Origin) end function ImNodes.IsEditorHovered() return internal.MouseInCanvas() end -- [Port] int* out-params become return values: IsNodeHovered() -> hovered, node_id function ImNodes.IsNodeHovered() local g = internal.GImNodes IM_ASSERT(g.CurrentScope == Scope.None) if g.HoveredNodeIdx == INVALID_INDEX then return false, nil end return true, internal.EditorContextGet().Nodes.Pool[g.HoveredNodeIdx].Id end function ImNodes.IsLinkHovered() local g = internal.GImNodes IM_ASSERT(g.CurrentScope == Scope.None) if g.HoveredLinkIdx == INVALID_INDEX then return false, nil end return true, internal.EditorContextGet().Links.Pool[g.HoveredLinkIdx].Id end function ImNodes.IsPinHovered() local g = internal.GImNodes IM_ASSERT(g.CurrentScope == Scope.None) if g.HoveredPinIdx == INVALID_INDEX then return false, nil end return true, internal.EditorContextGet().Pins.Pool[g.HoveredPinIdx].Id end function ImNodes.NumSelectedNodes() IM_ASSERT(internal.GImNodes.CurrentScope == Scope.None) return internal.EditorContextGet().SelectedNodeIndices.Size end function ImNodes.NumSelectedLinks() IM_ASSERT(internal.GImNodes.CurrentScope == Scope.None) return internal.EditorContextGet().SelectedLinkIndices.Size end -- [Port] returns a new array of ids instead of filling an int* buffer function ImNodes.GetSelectedNodes() local editor = internal.EditorContextGet() local node_ids = table.create(editor.SelectedNodeIndices.Size) for i = 1, editor.SelectedNodeIndices.Size do node_ids[i] = editor.Nodes.Pool[editor.SelectedNodeIndices[i] ].Id end return node_ids end function ImNodes.GetSelectedLinks() local editor = internal.EditorContextGet() local link_ids = table.create(editor.SelectedLinkIndices.Size) for i = 1, editor.SelectedLinkIndices.Size do link_ids[i] = editor.Links.Pool[editor.SelectedLinkIndices[i] ].Id end return link_ids end -- [Port] ClearNodeSelection() / ClearNodeSelection(node_id) overloads merged on nil function ImNodes.ClearNodeSelection(node_id) local editor = internal.EditorContextGet() if node_id == nil then editor.SelectedNodeIndices:clear() else internal.ClearObjectSelection(editor.Nodes, editor.SelectedNodeIndices, node_id) end end function ImNodes.ClearLinkSelection(link_id) local editor = internal.EditorContextGet() if link_id == nil then editor.SelectedLinkIndices:clear() else internal.ClearObjectSelection(editor.Links, editor.SelectedLinkIndices, link_id) end end function ImNodes.SelectNode(node_id) local editor = internal.EditorContextGet() internal.SelectObject(editor.Nodes, editor.SelectedNodeIndices, node_id) end function ImNodes.SelectLink(link_id) local editor = internal.EditorContextGet() internal.SelectObject(editor.Links, editor.SelectedLinkIndices, link_id) end function ImNodes.IsNodeSelected(node_id) local editor = internal.EditorContextGet() return internal.IsObjectSelected(editor.Nodes, editor.SelectedNodeIndices, node_id) end function ImNodes.IsLinkSelected(link_id) local editor = internal.EditorContextGet() return internal.IsObjectSelected(editor.Links, editor.SelectedLinkIndices, link_id) end function ImNodes.IsAttributeActive() local g = internal.GImNodes IM_ASSERT(bit32.band(g.CurrentScope, Scope.Node) ~= 0) if not g.ActiveAttribute then return false end return g.ActiveAttributeId == g.CurrentAttributeId end -- -> active, attribute_id function ImNodes.IsAnyAttributeActive() local g = internal.GImNodes IM_ASSERT(bit32.band(g.CurrentScope, bit32.bor(Scope.Node, Scope.Attribute)) == 0) if not g.ActiveAttribute then return false, nil end return true, g.ActiveAttributeId end -- -> started, started_at_id function ImNodes.IsLinkStarted() local g = internal.GImNodes -- Call this function after EndNodeEditor()! IM_ASSERT(g.CurrentScope == Scope.None) if bit32.band(g.ImNodesUIState, internal.ImNodesUIState.LinkStarted) == 0 then return false, nil end local editor = internal.EditorContextGet() return true, editor.Pins.Pool[editor.ClickInteraction.LinkCreation.StartPinIdx].Id end -- -> dropped, started_at_id function ImNodes.IsLinkDropped(including_detached_links) local g = internal.GImNodes -- Call this function after EndNodeEditor()! IM_ASSERT(g.CurrentScope == Scope.None) if including_detached_links == nil then including_detached_links = true end local editor = internal.EditorContextGet() local link_dropped = bit32.band(g.ImNodesUIState, internal.ImNodesUIState.LinkDropped) ~= 0 and (including_detached_links or editor.ClickInteraction.LinkCreation.Type ~= internal.ImNodesLinkCreationType.FromDetach) if not link_dropped then return false, nil end return true, editor.Pins.Pool[editor.ClickInteraction.LinkCreation.StartPinIdx].Id end -- Returns created, start_pin, start_node, end_pin, end_node, from_snap (start is always the output pin) local function LinkCreatedInfo() local g = internal.GImNodes IM_ASSERT(g.CurrentScope == Scope.None) if bit32.band(g.ImNodesUIState, internal.ImNodesUIState.LinkCreated) == 0 then return false end local editor = internal.EditorContextGet() local lc = editor.ClickInteraction.LinkCreation local start_pin = editor.Pins.Pool[lc.StartPinIdx] local end_pin = editor.Pins.Pool[lc.EndPinIdx] if start_pin.Type ~= internal.ImNodesAttributeType.Output then start_pin, end_pin = end_pin, start_pin end local from_snap = editor.ClickInteraction.Type == ClickType.LinkCreation return true, start_pin.Id, editor.Nodes.Pool[start_pin.ParentNodeIdx].Id, end_pin.Id, editor.Nodes.Pool[end_pin.ParentNodeIdx].Id, from_snap end -- [Port] -> created, started_at_attribute_id, ended_at_attribute_id, created_from_snap function ImNodes.IsLinkCreated() local created, start_pin, _, end_pin, _, from_snap = LinkCreatedInfo() return created, start_pin, end_pin, from_snap end -- [Port] node-id overload -> created, started_at_node_id, started_at_attribute_id, -- ended_at_node_id, ended_at_attribute_id, created_from_snap function ImNodes.IsLinkCreatedWithNodes() local created, start_pin, start_node, end_pin, end_node, from_snap = LinkCreatedInfo() return created, start_node, start_pin, end_node, end_pin, from_snap end -- -> destroyed, link_id function ImNodes.IsLinkDestroyed() local g = internal.GImNodes IM_ASSERT(g.CurrentScope == Scope.None) if g.DeletedLinkIdx == INVALID_INDEX then return false, nil end return true, internal.EditorContextGet().Links.Pool[g.DeletedLinkIdx].Id end end return ImNodes end