From 6824176a537537c059c649c8798b836b4d10b08a Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 17 Oct 2026 04:38:57 -0500 Subject: [PATCH] Port object pools, node editor, nodes, attributes, links, hover, node dragging, panning --- ImNodes.lua | 1394 ++++++++++++++++++++++++++++++++++++++++++- tests/t_editor.luau | 91 +++ 2 files changed, 1480 insertions(+), 5 deletions(-) create mode 100644 tests/t_editor.luau diff --git a/ImNodes.lua b/ImNodes.lua index 5a629de..57cb05d 100644 --- a/ImNodes.lua +++ b/ImNodes.lua @@ -197,8 +197,9 @@ return function(G) --------------------------------------------------------------------------- do -- [Port] ImObjectPool: IdMap is a plain table (id -> index) instead of ImGuiStorage; pool indices are 1-based. - function internal.ImObjectPool() - return { Pool = ImVector(), InUse = ImVector(), FreeList = ImVector(), IdMap = {} } + -- [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. @@ -275,9 +276,9 @@ return function(G) do function internal.ImNodesEditorContext() return { - Nodes = internal.ImObjectPool(), - Pins = internal.ImObjectPool(), - Links = internal.ImObjectPool(), + Nodes = internal.ImObjectPool(internal.ImNodeData), + Pins = internal.ImObjectPool(internal.ImPinData), + Links = internal.ImObjectPool(internal.ImLinkData), NodeDepthOrder = ImVector(), @@ -676,5 +677,1388 @@ return function(G) 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 + + -- [Port] TODO: RectangleOverlapsLineSegment / RectangleOverlapsBezier / RectangleOverlapsLink (box selection) + + 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 + + -- [Port] TODO: MiniMapSpaceToGridSpace / ScreenSpaceToMiniMapSpace (minimap) + 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 + + -- [Port] TODO: BeginLinkSelection / BeginLinkDetach / BeginLinkCreation / BeginLinkInteraction (link creation, selection) + + 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 + -- [Port] TODO: box selection (ImNodesClickInteractionType_BoxSelection) + end + end + + -- [Port] TODO: BoxSelectorUpdateSelection + + 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] TODO: LinkPredicate / FindDuplicateLink / ShouldLinkSnapToPin (link creation) + + function internal.ClickInteractionUpdate(editor) + local g = internal.GImNodes + local t = editor.ClickInteraction.Type + if t == ClickType.BoxSelection then + -- [Port] TODO: box selection + if g.LeftMouseReleased then + 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 + -- [Port] TODO: link creation (partial link drawing, snapping, LinkCreated/LinkDropped events) + if g.LeftMouseReleased then + editor.ClickInteraction.Type = ClickType.None + end + 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 + + -- [Port] TODO: [SECTION] minimap (IsMiniMapActive, CalcMiniMapLayout, MiniMapUpdate, ...) + function internal.IsMiniMapActive() + return false + end + + function internal.IsMiniMapHovered() + return false + 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() + + -- [Port] TODO: minimap (CalcMiniMapLayout / MiniMapUpdate) + + -- Handle node graph interaction + + if not internal.IsMiniMapHovered() then + if g.LeftMouseClicked and g.HoveredLinkIdx ~= INVALID_INDEX then + -- [Port] TODO: BeginLinkInteraction (link selection / detach) + elseif g.LeftMouseClicked and g.HoveredPinIdx ~= INVALID_INDEX then + -- [Port] TODO: BeginLinkCreation + 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] TODO: MiniMap, PushAttributeFlag/PopAttributeFlag, IsEditorHovered/IsNodeHovered/..., selection API, + -- IsLinkStarted/Dropped/Created/Destroyed, SaveCurrentEditorStateToIniString/Load* + end + return ImNodes end diff --git a/tests/t_editor.luau b/tests/t_editor.luau new file mode 100644 index 0000000..7c0cbd0 --- /dev/null +++ b/tests/t_editor.luau @@ -0,0 +1,91 @@ +local RS = game:GetService("ReplicatedStorage") +local G = require(RS:WaitForChild("ImGui")) +local ImNodes = require(RS:WaitForChild("ImNodes"))(G) +local ImGui, ImVec2 = G.ImGui, G.ImVec2 +local Impl = G.ImGui_ImplRoblox + +ImGui.CreateContext() +Impl.Init() +Impl.SetRenderRate(0) +ImNodes.CreateContext() +local io = ImGui.GetIO() + +local function frame(n, before) + Impl.NewFrame() + io.DeltaTime = 1 / 60 + if before then + before() + end + ImGui.NewFrame() + ImGui.SetNextWindowPos(ImVec2(0, 0), G.ImGuiCond.Always) + ImGui.SetNextWindowSize(ImVec2(800, 600), G.ImGuiCond.Always) + ImGui.Begin("editor") + ImNodes.BeginNodeEditor() + if n == 1 then + ImNodes.SetNodeGridSpacePos(1, ImVec2(50, 50)) + ImNodes.SetNodeGridSpacePos(2, ImVec2(300, 100)) + end + ImNodes.BeginNode(1) + ImNodes.BeginNodeTitleBar() + ImGui.Text("node A") + ImNodes.EndNodeTitleBar() + ImNodes.BeginOutputAttribute(11) + ImGui.Text("out") + ImNodes.EndOutputAttribute() + ImNodes.BeginStaticAttribute(12) + ImGui.Text("static") + ImNodes.EndStaticAttribute() + ImNodes.EndNode() + ImNodes.BeginNode(2) + ImNodes.BeginNodeTitleBar() + ImGui.Text("node B") + ImNodes.EndNodeTitleBar() + ImNodes.BeginInputAttribute(21, ImNodes.ImNodesPinShape.Quad) + ImGui.Text("in") + ImNodes.EndInputAttribute() + ImNodes.EndNode() + ImNodes.Link(100, 11, 21) + ImNodes.EndNodeEditor() + ImGui.End() + ImGui.Render() + local dd = ImGui.GetDrawData() + Impl.RenderDrawData(dd) + return dd.TotalVtxCount +end + +local vtx = 0 +for n = 1, 20 do + vtx = frame(n) +end +assert(vtx > 0, "no vertices") +local dims = ImNodes.GetNodeDimensions(1) +assert(dims.x > 0 and dims.y > 0) + +-- drag node 1 by its title bar +local p0 = ImNodes.GetNodeGridSpacePos(1) +local s = ImNodes.GetNodeScreenSpacePos(1) +local tx, ty = s.x + 12, s.y + 10 +frame(21, function() io:AddMousePosEvent(tx, ty) end) +frame(22, function() io:AddMouseButtonEvent(0, true) end) +for i = 1, 5 do + frame(22 + i, function() io:AddMousePosEvent(tx + i * 10, ty + i * 4) end) +end +frame(28, function() io:AddMouseButtonEvent(0, false) end) +local p1 = ImNodes.GetNodeGridSpacePos(1) +assert(math.abs(p1.x - p0.x - 50) < 1e-3 and math.abs(p1.y - p0.y - 20) < 1e-3, `node not dragged: {p0.x},{p0.y} -> {p1.x},{p1.y}`) +assert(ImNodes.GetNodeGridSpacePos(2).x == 300) + +-- pan with middle mouse on empty canvas +local pan0 = ImNodes.EditorContextGetPanning() +frame(29, function() io:AddMousePosEvent(700, 500) end) +frame(30, function() io:AddMouseButtonEvent(2, true) end) +frame(31, function() io:AddMousePosEvent(680, 490) end) +frame(32, function() io:AddMouseButtonEvent(2, false) end) +local pan1 = ImNodes.EditorContextGetPanning() +assert(pan1.x - pan0.x == -20 and pan1.y - pan0.y == -10, `pan: {pan1.x},{pan1.y}`) + +ImNodes.EditorContextMoveToNode(2) +assert(ImNodes.EditorContextGetPanning().x == -300) + +ImNodes.DestroyContext() +print("OK")