Skip to content
Draft
62 changes: 39 additions & 23 deletions src/lib/litegraph/src/LGraphCanvas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,9 @@ export class LGraphCanvas implements CustomEventDispatcher<LGraphCanvasEventMap>
* performant than {@link visible_nodes} for visibility checks.
*/
private _visible_node_ids: Set<SerializedNodeId> = new Set()

/** Cached per-frame link render context to avoid rebuilding per-link. */
private _cachedLinkRenderContext: LinkRenderContext | null = null
node_over?: LGraphNode
node_capturing_input?: LGraphNode | null
highlighted_links: Dictionary<boolean> = {}
Expand Down Expand Up @@ -5083,6 +5086,9 @@ export class LGraphCanvas implements CustomEventDispatcher<LGraphCanvasEventMap>
if (!this.canvas || this.canvas.width == 0 || this.canvas.height == 0)
return

// Reset per-frame caches so stale data is never used if a code path is skipped.
this._cachedLinkRenderContext = null

// fps counting
const now = LiteGraph.getTime()
this.render_time = (now - this.last_draw_time) * 0.001
Expand Down Expand Up @@ -5117,10 +5123,11 @@ export class LGraphCanvas implements CustomEventDispatcher<LGraphCanvasEventMap>
getCurrentGraphNodesInFrameOrder(),
this.visible_nodes
)
// Update visible node IDs
this._visible_node_ids = new Set(
this.visible_nodes.map((node) => node.id)
)
// Update visible node IDs (reuse existing Set to avoid allocation)
this._visible_node_ids.clear()
for (const node of this.visible_nodes) {
this._visible_node_ids.add(node.id)
}

// Arrange subgraph IO nodes
const { subgraph } = this
Expand Down Expand Up @@ -5351,10 +5358,7 @@ export class LGraphCanvas implements CustomEventDispatcher<LGraphCanvasEventMap>
colour,
fromDirection,
dragDirection,
{
...this.buildLinkRenderContext(),
linkMarkerShape: LinkMarkerShape.None
}
this._cachedLinkRenderContext ?? this.buildLinkRenderContext()
)
}
if (renderLink instanceof MovingInputLink) this.setDirty(false, true)
Expand Down Expand Up @@ -6136,6 +6140,9 @@ export class LGraphCanvas implements CustomEventDispatcher<LGraphCanvasEventMap>
this.renderedPaths.clear()
if (this.links_render_mode === LinkRenderType.HIDDEN_LINK) return

// Cache the link render context once per frame
this._cachedLinkRenderContext = this.buildLinkRenderContext()

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const { graph, subgraph } = this
if (!graph) throw new NullGraphError()

Expand Down Expand Up @@ -6414,19 +6421,28 @@ export class LGraphCanvas implements CustomEventDispatcher<LGraphCanvasEventMap>

// Get all points this link passes through
const reroutes = LLink.getReroutes(graph, link)
const points: [Point, ...Point[], Point] = [
startPos,
...reroutes.map((x) => x.pos),
endPos
]

// Bounding box of all points (bezier overshoot on long links will be cut)
const pointsX = points.map((x) => x[0])
const pointsY = points.map((x) => x[1])
link_bounding[0] = Math.min(...pointsX)
link_bounding[1] = Math.min(...pointsY)
link_bounding[2] = Math.max(...pointsX) - link_bounding[0]
link_bounding[3] = Math.max(...pointsY) - link_bounding[1]
// Compute bounding box inline to avoid allocating temporary arrays
let minX = startPos[0]
let minY = startPos[1]
let maxX = minX
let maxY = minY
for (let i = 0; i < reroutes.length; i++) {
const pos = reroutes[i].pos
if (pos[0] < minX) minX = pos[0]
else if (pos[0] > maxX) maxX = pos[0]
if (pos[1] < minY) minY = pos[1]
else if (pos[1] > maxY) maxY = pos[1]
}
if (endPos[0] < minX) minX = endPos[0]
else if (endPos[0] > maxX) maxX = endPos[0]
if (endPos[1] < minY) minY = endPos[1]
else if (endPos[1] > maxY) maxY = endPos[1]

link_bounding[0] = minX
link_bounding[1] = minY
link_bounding[2] = maxX - minX
link_bounding[3] = maxY - minY

// skip links outside of the visible area of the canvas
if (!overlapBounding(link_bounding, margin_area)) return
Expand Down Expand Up @@ -6494,8 +6510,7 @@ export class LGraphCanvas implements CustomEventDispatcher<LGraphCanvasEventMap>
// Skip the last segment if it is being dragged
if (link._dragging) return

// Use runtime fallback; TypeScript cannot evaluate this correctly.
const segmentStartPos = points.at(-2) ?? startPos
const segmentStartPos = reroutes.at(-1)?.pos ?? startPos

// Render final link segment
this.renderLink(
Expand Down Expand Up @@ -6616,7 +6631,8 @@ export class LGraphCanvas implements CustomEventDispatcher<LGraphCanvasEventMap>
} = {}
): void {
if (this.linkRenderer) {
const context = this.buildLinkRenderContext()
const context =
this._cachedLinkRenderContext ?? this.buildLinkRenderContext()
this.linkRenderer.renderLinkDirect(
ctx,
a,
Expand Down
126 changes: 126 additions & 0 deletions src/lib/litegraph/src/LGraphNode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -877,6 +877,132 @@ describe('LGraphNode', () => {
expect(out[3]).toBe(120 + LiteGraph.NODE_TITLE_HEIGHT)
})
})
describe('_slotsDirty flag', () => {
test('starts dirty', () => {
const n = new LGraphNode('Test')
expect(n._slotsDirty).toBe(true)
})

test('is cleared by _setConcreteSlots', () => {
const n = new LGraphNode('Test')
n._setConcreteSlots()
expect(n._slotsDirty).toBe(false)
})

test('skips work when clean', () => {
const n = new LGraphNode('Test')
n.addInput('in', 'number')
n._setConcreteSlots()
expect(n._slotsDirty).toBe(false)

const concreteInput = n.inputs[0]
n._setConcreteSlots()
expect(n.inputs[0]).toBe(concreteInput)
})

test('is set by addInput', () => {
const n = new LGraphNode('Test')
n._setConcreteSlots()
n.addInput('in', 'number')
expect(n._slotsDirty).toBe(true)
})

test('is set by removeInput', () => {
const n = new LGraphNode('Test')
n.addInput('in', 'number')
n._setConcreteSlots()
n.removeInput(0)
expect(n._slotsDirty).toBe(true)
})

test('is set by addOutput', () => {
const n = new LGraphNode('Test')
n._setConcreteSlots()
n.addOutput('out', 'number')
expect(n._slotsDirty).toBe(true)
})

test('is set by removeOutput', () => {
const n = new LGraphNode('Test')
n.addOutput('out', 'number')
n._setConcreteSlots()
n.removeOutput(0)
expect(n._slotsDirty).toBe(true)
})

test('refreshes drawn slots after direct array mutations', () => {
const n = new LGraphNode('Test')
n.addInput('old input', 'number')
n.addOutput('old output', 'number')
n._setConcreteSlots()

const oldInput = n.inputs[0]
const oldOutput = n.outputs[0]
expect(oldInput).toBeInstanceOf(NodeInputSlot)
expect(oldOutput).toBeInstanceOf(NodeOutputSlot)
if (!(oldInput instanceof NodeInputSlot)) throw new Error('Invalid input')
if (!(oldOutput instanceof NodeOutputSlot))
throw new Error('Invalid output')
const oldInputDraw = vi.spyOn(oldInput, 'draw')
const oldOutputDraw = vi.spyOn(oldOutput, 'draw')

n.inputs.splice(
0,
1,
new NodeInputSlot({ name: 'new input', type: 'number', link: null }, n)
)
n.outputs.splice(
0,
1,
new NodeOutputSlot(
{ name: 'new output', type: 'number', links: null },
n
)
)
expect(n._slotsDirty).toBe(true)

n._setConcreteSlots()
const newInput = n.inputs[0]
const newOutput = n.outputs[0]
expect(newInput).toBeInstanceOf(NodeInputSlot)
expect(newOutput).toBeInstanceOf(NodeOutputSlot)
if (!(newInput instanceof NodeInputSlot)) throw new Error('Invalid input')
if (!(newOutput instanceof NodeOutputSlot))
throw new Error('Invalid output')
const newInputDraw = vi
.spyOn(newInput, 'draw')
.mockImplementation(() => {})
const newOutputDraw = vi
.spyOn(newOutput, 'draw')
.mockImplementation(() => {})

n.drawSlots(createMockCanvasRenderingContext2D(), {
colorContext: {
getConnectedColor: () => '#fff',
getDisconnectedColor: () => '#fff'
},
editorAlpha: 1,
lowQuality: false
})

expect(oldInputDraw).not.toHaveBeenCalled()
expect(oldOutputDraw).not.toHaveBeenCalled()
expect(newInputDraw).toHaveBeenCalledOnce()
expect(newOutputDraw).toHaveBeenCalledOnce()
})

test('is set by configure', () => {
const n = new LGraphNode('Test')
n._setConcreteSlots()
n.configure(
getMockISerialisedNode({
inputs: [{ name: 'a', type: 'number', link: null }],
outputs: [{ name: 'b', type: 'number', links: null }]
})
)
expect(n._slotsDirty).toBe(true)
})
})
})

describe('snapToGrid', () => {
Expand Down
70 changes: 42 additions & 28 deletions src/lib/litegraph/src/LGraphNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ import {
} from './node/slotLinks'
import {
createInputSlotView,
createOutputSlotView,
resolveInputSlotView
} from './node/slotDescriptorView'
import { initializeWidgetsView } from './node/widgetsView'
Expand Down Expand Up @@ -406,6 +407,8 @@ export class LGraphNode

private _concreteInputs: NodeInputSlot[] = []
private _concreteOutputs: NodeOutputSlot[] = []
/** @internal Set when inputs/outputs change; cleared by {@link _setConcreteSlots}. */
_slotsDirty: boolean = true
Comment thread
christian-byrne marked this conversation as resolved.
Resolved

get properties(): Dictionary<NodeProperty | undefined> {
return this._state.properties
Expand Down Expand Up @@ -1011,7 +1014,7 @@ export class LGraphNode
initializeWidgetsView(this)
this._state = createNodeShellState(title, type, this.title_mode)
this._inputs = createInputSlotView(this, this._state.inputs)
this._outputs = this._state.outputs
this._outputs = createOutputSlotView(this, this._state.outputs)
for (const property of [
'inputs',
'outputs',
Expand Down Expand Up @@ -1094,6 +1097,7 @@ export class LGraphNode
this.inputs = this.inputs.map((input) =>
toClass(NodeInputSlot, input, this)
)
this._slotsDirty = true
for (const [i, input] of this.inputs.entries()) {
const serialisedLink = info.inputs?.[i]?.link
const link =
Expand Down Expand Up @@ -1886,6 +1890,7 @@ export class LGraphNode

this.outputs ||= []
this.outputs.push(output)
this._slotsDirty = true
const added = this.outputs.at(-1) as NodeOutputSlot & TProperties
this.onOutputAdded?.(added)

Expand All @@ -1907,6 +1912,7 @@ export class LGraphNode
}
const { outputs } = this
outputs.splice(slot, 1)
this._slotsDirty = true

// Only update link indices if node is part of a graph. Ascending order:
// each decrement re-keys the link to an already-processed slot index.
Expand Down Expand Up @@ -1953,6 +1959,7 @@ export class LGraphNode

this.inputs ||= []
this.inputs.push(input)
this._slotsDirty = true
const added = this.inputs.at(-1) as NodeInputSlot & TProperties
this.expandToFitContent()

Expand Down Expand Up @@ -1991,6 +1998,7 @@ export class LGraphNode
} else {
inputs.splice(slot, 1)
}
this._slotsDirty = true
this.onInputRemoved?.(slot, slotInfo)
this.setDirtyCanvas(true, true)
}
Expand Down Expand Up @@ -4300,33 +4308,36 @@ export class LGraphNode
ctx: CanvasRenderingContext2D,
{ fromSlot, colorContext, editorAlpha, lowQuality }: DrawSlotsOptions
) {
for (const slot of [...this._concreteInputs, ...this._concreteOutputs]) {
const isValidTarget = fromSlot && slot.isValidTarget(fromSlot)
const isMouseOverSlot = this._isMouseOverSlot(slot)

// change opacity of incompatible slots when dragging a connection
const isValid = !fromSlot || isValidTarget
const highlight = isValid && isMouseOverSlot

// Show slot if it's not a widget input slot
// or if it's a widget input slot and satisfies one of the following:
// - the mouse is over the widget
// - the slot is valid during link drop
// - the slot is connected
if (
isMouseOverSlot ||
isValidTarget ||
!slot.isWidgetInputSlot ||
this._isMouseOverWidget(this.getWidgetFromSlot(slot)) ||
slot.isConnected ||
slot.alwaysVisible
) {
ctx.globalAlpha = isValid ? editorAlpha : 0.4 * editorAlpha
slot.draw(ctx, {
colorContext,
lowQuality,
highlight
})
for (const slots of [this._concreteInputs, this._concreteOutputs]) {
for (let s = 0; s < slots.length; s++) {
const slot = slots[s]
const isValidTarget = fromSlot && slot.isValidTarget(fromSlot)
const isMouseOverSlot = this._isMouseOverSlot(slot)

// change opacity of incompatible slots when dragging a connection
const isValid = !fromSlot || isValidTarget
const highlight = isValid && isMouseOverSlot

// Show slot if it's not a widget input slot
// or if it's a widget input slot and satisfies one of the following:
// - the mouse is over the widget
// - the slot is valid during link drop
// - the slot is connected
if (
isMouseOverSlot ||
isValidTarget ||
!slot.isWidgetInputSlot ||
this._isMouseOverWidget(this.getWidgetFromSlot(slot)) ||
slot.isConnected ||
slot.alwaysVisible
) {
ctx.globalAlpha = isValid ? editorAlpha : 0.4 * editorAlpha
slot.draw(ctx, {
colorContext,
lowQuality,
highlight
})
}
}
}
}
Expand Down Expand Up @@ -4458,6 +4469,8 @@ export class LGraphNode
* invalidate slot-array subscribers.
*/
_setConcreteSlots(): void {
if (!this._slotsDirty) return
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

const { inputs, outputs } = this
this._concreteInputs = inputs.map((slot, i) => {
const concrete = toClass(NodeInputSlot, slot, this)
Expand All @@ -4469,6 +4482,7 @@ export class LGraphNode
if (concrete !== slot) outputs[i] = concrete
return concrete
})
this._slotsDirty = false
}

/**
Expand Down
Loading
Loading