-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLayoutCalculator.cpp
More file actions
1368 lines (1137 loc) · 51.3 KB
/
LayoutCalculator.cpp
File metadata and controls
1368 lines (1137 loc) · 51.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "LayoutCalculator.h"
#include <map>
#include <algorithm>
#include <stdexcept>
#include "CKAll.h"
#undef min
#undef max
LayoutCalculator::LayoutCalculator(InterfaceData &targetData, CKContext *context)
: m_Data(targetData), m_Context(context) {}
void LayoutCalculator::CalculateLayout(CKBehavior *script) {
// Get ordered behavior IDs for consistent processing
const auto behaviorIds = std::move(GetBehaviorIds());
// Clear graph state
InitializeGraphState();
// Phase 1: Calculate behavior positions
CalculateBehaviorLayouts(behaviorIds);
// Phase 2: Calculate operation and parameter positions
CalculateElementPositions(behaviorIds);
// Phase 3: Finalize script layout and recalculate absolute positions
FinalizeScriptLayout(script);
// Phase 4: Calculate link routes
CalculateAllLinkRoutes();
// Notify observers of changes
m_Data.NotifyObservers(nullptr, InterfaceData::ElementAction::Modified);
}
void LayoutCalculator::InitializeGraphState() {
m_Vertices.clear();
m_DistanceFromRoot.clear();
m_RequiredSize.clear();
m_PredecessorEdge.clear();
m_Edges.clear();
m_MovedOperations.clear();
}
void LayoutCalculator::CalculateBehaviorLayouts(const std::vector<CK_ID> &behaviorIds) {
// Create a map to store behavior depth information for sorting
std::map<int, std::vector<std::pair<BehaviorData *, CKBehavior *>>> behaviorsByDepth;
// Collect behaviors and store them by depth
for (auto &behaviorId : behaviorIds) {
BehaviorData *behaviorData = GetBehaviorData(behaviorId);
auto *behavior = (CKBehavior *) m_Context->GetObject(behaviorId);
if (!behaviorData || !behavior) {
m_Context->OutputToConsoleEx((CKSTRING) "Behavior not found: %d", behaviorId);
continue;
}
// Group behaviors by depth to ensure parent behaviors are processed before children
behaviorsByDepth[behaviorData->depth].emplace_back(behaviorData, behavior);
}
// First pass: Calculate sizes for all behaviors, processing by depth (root first)
for (const auto &depthGroup : behaviorsByDepth) {
for (const auto &pair : depthGroup.second) {
CalculateBehaviorSize(*pair.first, pair.second);
}
}
// Second pass: Calculate positions, ensuring parents are positioned before children
for (const auto &depthGroup : behaviorsByDepth) {
for (const auto &pair : depthGroup.second) {
CalculateBehaviorPositions(*pair.first, pair.second, pair.first->depth == 0);
}
}
}
void LayoutCalculator::CalculateBehaviorSize(BehaviorData &behaviorData, CKBehavior *behavior) {
if (behaviorData.depth <= 0) return;
// Calculate height with better scaling for behaviors with many inputs/outputs
int inputCount = behavior->GetInputCount();
int outputCount = behavior->GetOutputCount();
// More sophisticated height calculation
int height = std::max(inputCount, outputCount);
if (height <= 1) {
height = 1;
}
// Calculate width considering parameter counts and name length
int paramInputCount = behavior->GetInputParameterCount();
int paramOutputCount = behavior->GetOutputParameterCount();
// Base width on parameter counts
int width = std::max(paramInputCount, paramOutputCount);
// Consider name length in width calculation
const char *name = behavior->GetName();
const size_t nameLength = name ? strlen(name) : 0;
const int nameWidth = static_cast<int>(std::floor(nameLength * 0.4 + 1));
width = std::max(width, nameWidth);
width = std::max(width, 2);
// Set size
behaviorData.rect.hSize = static_cast<float>(width) * HORIZONTAL_SPACING;
behaviorData.rect.vSize = static_cast<float>(height) * VERTICAL_SPACING;
if (behaviorData.isUsingTarget) {
behaviorData.rect.hSize += HORIZONTAL_SPACING;
}
// Set expanded size for behavior graphs
if (behaviorData.isBehaviorGraph) {
float expansionFactor = BEHAVIOR_EXPANSION_FACTOR;
if (behavior->GetSubBehaviorCount() > 10) {
expansionFactor *= 1.5f; // More space for very complex behavior graphs
}
behaviorData.hExpandSize = behaviorData.rect.hSize * expansionFactor;
behaviorData.vExpandSize = behaviorData.rect.vSize * expansionFactor;
}
}
void LayoutCalculator::CalculateElementPositions(const std::vector<CK_ID> &behaviorIds) {
for (auto &behaviorId : behaviorIds) {
BehaviorData *behaviorData = GetBehaviorData(behaviorId);
if (behaviorData && behaviorData->isBehaviorGraph) {
// Apply multiple passes of operation positioning
for (int i = 0; i < MAX_FIX_STACK_OPS; ++i) {
CalculateOperationPositions(*behaviorData);
}
// Calculate parameter positions
CalculateLocalParameterPositions(*behaviorData, false); // Outputs
CalculateLocalParameterPositions(*behaviorData, true); // Inputs
}
}
}
void LayoutCalculator::FinalizeScriptLayout(CKBehavior *script) {
// Calculate the total height of the behavior graph
Rect &requiredSize = m_RequiredSize[script->GetID()];
// Ensure we have a valid size
if (requiredSize.vSize <= 0) {
// Calculate fallback size based on behavior count
float totalHeight = 0;
for (const auto &behavior : m_Data.behaviors) {
totalHeight += behavior.rect.vSize + VERTICAL_SPACING;
}
requiredSize.vSize = std::max(totalHeight, VERTICAL_SPACING * 5.0f);
}
float behaviorHeight = requiredSize.vSize + VERTICAL_SPACING * EXPANSION_PADDING;
// Calculate the vertical center position for the start point
float startVertical = (behaviorHeight - VERTICAL_SPACING) / 2.0f;
// Set start information and recalculate positions
SetStart(m_Data.rootBehavior, startVertical, behaviorHeight);
RecalculateAbsolutePositions(m_Data.rootBehavior, script, 0.0f, 0.0f);
}
void LayoutCalculator::CalculateAllLinkRoutes() {
for (auto &behavior : m_Data.behaviors) {
CalculateLinkRoutes(behavior);
}
CalculateLinkRoutes(m_Data.rootBehavior);
}
//------------------------------------------------------
// Utility Methods
//------------------------------------------------------
BehaviorData *LayoutCalculator::GetBehaviorData(CK_ID id) const {
return m_Data.FindBehavior(id);
}
Operation *LayoutCalculator::GetOperation(CK_ID id) const {
return m_Data.FindOperation(id);
}
bool LayoutCalculator::IsOperation(CK_ID id) const {
CKObject *obj = m_Context->GetObject(id);
return obj && obj->GetClassID() == CKCID_PARAMETEROPERATION;
}
std::vector<CK_ID> LayoutCalculator::GetBehaviorIds() const {
std::vector<CK_ID> behaviorIds;
// Add script root
behaviorIds.push_back(m_Data.rootBehavior.id);
// Add all behaviors
for (const auto &behavior : m_Data.behaviors) {
behaviorIds.push_back(behavior.id);
}
return behaviorIds;
}
std::vector<CK_ID> LayoutCalculator::GetOperationIds() const {
std::vector<CK_ID> operationIds;
// Add script root operations
operationIds.reserve(m_Data.rootBehavior.operations.size());
for (const auto &op : m_Data.rootBehavior.operations) {
operationIds.push_back(op.id);
}
// Add all behavior operations
for (const auto &behavior : m_Data.behaviors) {
for (const auto &op : behavior.operations) {
operationIds.push_back(op.id);
}
}
return operationIds;
}
//------------------------------------------------------
// Graph Construction and Analysis
//------------------------------------------------------
void LayoutCalculator::ConstructGraph(BehaviorData &behaviorGraph, CKBehavior *behavior) {
// Initialize graph structures
m_Vertices.clear();
m_Edges.clear();
// Create vertices for root and all sub-behaviors
CreateGraphVertices(behavior);
// Get sub-behavior count
const int subBehaviorCount = behavior->GetSubBehaviorCount();
if (subBehaviorCount == 0) {
return; // No sub-behaviors to connect
}
// Get valid behavior links
std::vector<Link *> validBehaviorLinks = GetValidBehaviorLinks(behaviorGraph);
// Handle the case where no valid links exist
if (validBehaviorLinks.empty()) {
ConnectDisconnectedBehaviorsToRoot(behavior);
return;
}
// Sort and add links to the graph
SortBehaviorLinks(validBehaviorLinks);
AddBehaviorLinksToGraph(validBehaviorLinks);
// Connect any orphaned behaviors
ConnectOrphanedBehaviors(behaviorGraph, behavior->GetID());
}
void LayoutCalculator::CreateGraphVertices(CKBehavior *behavior) {
// Create root vertex
const CK_ID rootId = behavior->GetID();
m_Vertices[rootId] = Vertex();
// Create vertices for all sub-behaviors
const int subBehaviorCount = behavior->GetSubBehaviorCount();
for (int i = 0; i < subBehaviorCount; ++i) {
CKBehavior *subBehavior = behavior->GetSubBehavior(i);
if (subBehavior) {
m_Vertices[subBehavior->GetID()] = Vertex();
}
}
}
std::vector<Link *> LayoutCalculator::GetValidBehaviorLinks(BehaviorData &behaviorGraph) {
std::vector<Link *> validLinks;
for (auto &link : behaviorGraph.links) {
if (link.IsBehaviorLink()) {
// Only include links between known behaviors
if (m_Vertices.find(link.start.id) != m_Vertices.end() &&
m_Vertices.find(link.end.id) != m_Vertices.end()) {
validLinks.push_back(&link);
}
}
}
return validLinks;
}
void LayoutCalculator::AddBehaviorLinksToGraph(const std::vector<Link *> &behaviorLinks) {
for (Link *link : behaviorLinks) {
AddGraphEdge(link->start.id, link->end.id);
}
}
void LayoutCalculator::AddGraphEdge(CK_ID sourceId, CK_ID targetId) {
Edge edge = {};
edge.sourceId = sourceId;
edge.targetId = targetId;
edge.nextEdgeIndex = m_Vertices[sourceId].firstEdgeIndex;
m_Vertices[sourceId].firstEdgeIndex = m_Edges.size();
m_Vertices[targetId].incomingEdgeCount++;
m_Edges.push_back(edge);
}
void LayoutCalculator::SortBehaviorLinks(std::vector<Link *> &behaviorLinks) {
// Sort links by:
// 1. Source behavior ID (descending)
// 2. Output index (descending)
// 3. Target behavior ID (descending)
// 4. Input index (descending)
std::sort(behaviorLinks.begin(), behaviorLinks.end(),
[](const Link *a, const Link *b) {
// Compare source behaviors
if (a->start.id != b->start.id) {
return a->start.id > b->start.id;
}
// Compare output indices
if (a->start.index != b->start.index) {
return a->start.index > b->start.index;
}
// Compare target behaviors
if (a->end.id != b->end.id) {
return a->end.id > b->end.id;
}
// Compare input indices
if (a->end.index != b->end.index) {
return a->end.index > b->end.index;
}
// Use link ID for stable sorting
return a->id > b->id;
});
}
void LayoutCalculator::ConnectDisconnectedBehaviorsToRoot(CKBehavior *behavior) {
// For an empty graph, connect all behaviors to root in sequential chain
CK_ID prevId = behavior->GetID();
const int subCount = behavior->GetSubBehaviorCount();
for (int i = 0; i < subCount; ++i) {
CKBehavior *subBehavior = behavior->GetSubBehavior(i);
if (subBehavior) {
CK_ID currentId = subBehavior->GetID();
AddGraphEdge(prevId, currentId);
prevId = currentId;
}
}
}
void LayoutCalculator::ConnectOrphanedBehaviors(BehaviorData &behaviorGraph, CK_ID rootId) {
// Find behaviors without incoming edges and connect them
std::vector<OrphanedBehavior> orphanedBehaviors = FindOrphanedBehaviors(behaviorGraph, rootId);
// Sort orphaned behaviors by vertical position (descending)
SortOrphanedBehaviors(orphanedBehaviors);
// Connect orphaned behaviors to form a chain
ConnectOrphanedBehaviorsChain(orphanedBehaviors, rootId);
}
std::vector<LayoutCalculator::OrphanedBehavior> LayoutCalculator::FindOrphanedBehaviors(
BehaviorData &behaviorGraph, CK_ID rootId) {
std::vector<OrphanedBehavior> orphanedBehaviors;
for (const auto &vertexPair : m_Vertices) {
CK_ID behaviorId = vertexPair.first;
const Vertex &vertex = vertexPair.second;
// Skip root and behaviors with incoming edges
if (behaviorId != rootId && vertex.incomingEdgeCount == 0) {
float vPos = GetBehaviorVerticalPosition(behaviorGraph, behaviorId);
orphanedBehaviors.push_back({behaviorId, vPos});
}
}
return orphanedBehaviors;
}
float LayoutCalculator::GetBehaviorVerticalPosition(BehaviorData &behaviorGraph, CK_ID behaviorId) {
// Find the behavior data to get vertical position
BehaviorData *behaviorData = nullptr;
if (behaviorId == behaviorGraph.id) {
behaviorData = &behaviorGraph;
} else {
behaviorData = GetBehaviorData(behaviorId);
}
// Return vertical position if behavior data was found
return behaviorData ? behaviorData->rect.vPos : 0.0f;
}
void LayoutCalculator::SortOrphanedBehaviors(std::vector<OrphanedBehavior> &orphanedBehaviors) {
std::sort(orphanedBehaviors.begin(), orphanedBehaviors.end(),
[](const OrphanedBehavior &a, const OrphanedBehavior &b) {
return a.verticalPosition > b.verticalPosition;
});
}
void LayoutCalculator::ConnectOrphanedBehaviorsChain(
const std::vector<OrphanedBehavior> &orphanedBehaviors, CK_ID rootId) {
CK_ID sourceId = rootId;
for (const auto &orphan : orphanedBehaviors) {
AddGraphEdge(sourceId, orphan.id);
sourceId = orphan.id;
}
}
void LayoutCalculator::CalculateDistancesFromQueue(std::queue<CK_ID> &nodeQueue) {
while (!nodeQueue.empty()) {
CK_ID currentId = nodeQueue.front();
nodeQueue.pop();
// Process all outgoing edges from this node
for (int edgeIndex = m_Vertices[currentId].firstEdgeIndex;
edgeIndex != -1;
edgeIndex = m_Edges[edgeIndex].nextEdgeIndex) {
CK_ID targetId = m_Edges[edgeIndex].targetId;
// If destination not yet visited, compute distance and enqueue
if (m_DistanceFromRoot.find(targetId) == m_DistanceFromRoot.end()) {
m_DistanceFromRoot[targetId] = m_DistanceFromRoot[currentId] + 1;
m_PredecessorEdge[targetId] = edgeIndex;
nodeQueue.push(targetId);
}
}
}
}
void LayoutCalculator::CalculateGraphDistances(BehaviorData &behaviorGraph) {
m_DistanceFromRoot.clear();
m_PredecessorEdge.clear();
// Start with root node at distance 0
m_DistanceFromRoot[behaviorGraph.id] = 0;
std::queue<CK_ID> nodeQueue;
nodeQueue.push(behaviorGraph.id);
CalculateDistancesFromQueue(nodeQueue);
// Check for disconnected components (rare case)
// for (const auto &vertex : m_Vertices) {
// CK_ID vertexId = vertex.first;
// if (m_DistanceFromRoot.find(vertexId) == m_DistanceFromRoot.end()) {
// // Node not reachable - ignored as it should be handled by virtual edges
// }
// }
}
//------------------------------------------------------
// Size and Position Calculation
//------------------------------------------------------
Rect LayoutCalculator::CalculateSubgraphSize(BehaviorData &behaviorData, bool isRoot) {
CK_ID currentId = behaviorData.id;
Rect size = behaviorData.rect;
// Reset size for root node
if (isRoot) {
size.hSize = 0.0f;
size.vSize = 0.0f;
}
// Calculate size contribution from child nodes
int childCount = 0;
float totalVerticalSize = 0;
float maxHorizontalSize = 0;
for (int edgeIndex = m_Vertices[currentId].firstEdgeIndex;
edgeIndex != -1;
edgeIndex = m_Edges[edgeIndex].nextEdgeIndex) {
CK_ID targetId = m_Edges[edgeIndex].targetId;
BehaviorData *targetData = GetBehaviorData(targetId);
if (!targetData) continue;
// Only consider nodes that are direct children in the shortest path tree
if (m_PredecessorEdge.find(targetId) != m_PredecessorEdge.end() &&
m_PredecessorEdge[targetId] == edgeIndex) {
Rect childSize = CalculateSubgraphSize(*targetData, false);
totalVerticalSize += childSize.vSize + VERTICAL_SPACING * 2;
maxHorizontalSize = std::max(maxHorizontalSize, childSize.hSize);
childCount++;
}
}
// Adjust vertical size (remove extra padding if multiple children)
if (childCount > 0) {
totalVerticalSize -= VERTICAL_SPACING * 2;
}
// Calculate final size
size.hSize = size.hSize + (maxHorizontalSize > 0.0f ? maxHorizontalSize + HORIZONTAL_SPACING * 2 : 0.0f);
size.vSize = std::max(size.vSize, totalVerticalSize);
// Store required size and return
m_RequiredSize[behaviorData.id] = size;
return size;
}
void LayoutCalculator::PlaceBehaviorInParent(BehaviorData &behaviorData, float hPos, float vPos, bool isRoot) {
// Position the behavior (unless it's the root)
if (!isRoot) {
behaviorData.rect.hPos = hPos;
// Center the behavior vertically within its allocated space
float verticalCenter = (m_RequiredSize[behaviorData.id].vSize - behaviorData.rect.vSize) / 2;
behaviorData.rect.vPos = vPos + verticalCenter;
}
// Position all children
int childCount = 0;
float currentVerticalOffset = 0;
CK_ID currentId = behaviorData.id;
for (int edgeIndex = m_Vertices[currentId].firstEdgeIndex;
edgeIndex != -1;
edgeIndex = m_Edges[edgeIndex].nextEdgeIndex) {
CK_ID targetId = m_Edges[edgeIndex].targetId;
BehaviorData *targetData = GetBehaviorData(targetId);
if (!targetData) continue;
// Only consider nodes that are direct children in the shortest path tree
if (m_PredecessorEdge.find(targetId) != m_PredecessorEdge.end() &&
m_PredecessorEdge[targetId] == edgeIndex) {
const Rect &childSize = m_RequiredSize[targetId];
// Calculate horizontal position based on parent type (BEHAVIOR_PADDING is already pixels)
float childHorizontalPos;
if (isRoot) {
childHorizontalPos = hPos + HORIZONTAL_SPACING;
} else {
childHorizontalPos = hPos + behaviorData.rect.hSize + BEHAVIOR_PADDING;
}
// Place the child behavior
PlaceBehaviorInParent(
*targetData,
childHorizontalPos,
vPos + currentVerticalOffset,
false
);
// Update vertical offset for next child (BEHAVIOR_PADDING is already pixels)
currentVerticalOffset += childSize.vSize + BEHAVIOR_PADDING;
childCount++;
}
}
}
float LayoutCalculator::CalculateBehaviorPositions(BehaviorData &behaviorGraph, CKBehavior *behavior, bool isScript) {
if (!behaviorGraph.isBehaviorGraph)
return 0.0f;
// Build the graph representation
ConstructGraph(behaviorGraph, behavior);
// Calculate minimum distances from root
CalculateGraphDistances(behaviorGraph);
// Calculate required sizes for all nodes
const Rect size = CalculateSubgraphSize(behaviorGraph, true);
// Calculate expanded sizes
behaviorGraph.hExpandSize = size.hSize + HORIZONTAL_SPACING * EXPANSION_PADDING;
behaviorGraph.vExpandSize = size.vSize + VERTICAL_SPACING * EXPANSION_PADDING;
// Place behaviors within the graph (constants are already in pixels)
float horizontalOffset = isScript ? BEHAVIOR_H_START_OFFSET : BEHAVIOR_PADDING;
PlaceBehaviorInParent(
behaviorGraph,
horizontalOffset,
BEHAVIOR_V_START_OFFSET,
true
);
// Return vertical center position
return size.vSize / 2;
}
void LayoutCalculator::RecalculateAbsolutePositions(BehaviorData &behaviorData, CKBehavior *behavior,
float startHorizontal, float startVertical) {
// Reset position for root behavior
if (behaviorData.depth == 0) {
behaviorData.rect.hPos = 0;
behaviorData.rect.vPos = 0;
}
// Apply offset
behaviorData.rect.hPos += startHorizontal;
behaviorData.rect.vPos += startVertical;
// Process sub-behaviors and operations if this is a behavior graph
if (behaviorData.isBehaviorGraph) {
// Process sub-behaviors
const int subBehaviorCount = behavior->GetSubBehaviorCount();
for (int i = 0; i < subBehaviorCount; ++i) {
CKBehavior *subBeh = behavior->GetSubBehavior(i);
if (!subBeh) continue;
BehaviorData *subBehData = GetBehaviorData(subBeh->GetID());
if (!subBehData) continue;
RecalculateAbsolutePositions(
*subBehData, subBeh,
behaviorData.rect.hPos, behaviorData.rect.vPos
);
}
// Process operations
for (auto &op : behaviorData.operations) {
op.hPos += behaviorData.rect.hPos;
op.vPos += behaviorData.rect.vPos;
}
// Process parameters (stored as int grid indices)
// Parameters are positioned in the local coordinate space of the behavior graph,
// but serialized as integer (col,row) indices in the 20px grid. When converting
// to absolute space, translate them by the parent's pixel offset expressed in grid units.
const int dx = static_cast<int>(std::lround(behaviorData.rect.hPos / HORIZONTAL_SPACING));
const int dy = static_cast<int>(std::lround(behaviorData.rect.vPos / VERTICAL_SPACING));
for (auto ¶m : behaviorData.localParams) {
param.hPos += dx;
param.vPos += dy;
}
for (auto ¶m : behaviorData.sharedParams) {
param.hPos += dx;
param.vPos += dy;
}
}
}
void LayoutCalculator::SetStart(BehaviorData &script, float verticalStartPos, float verticalSize) {
auto &header = m_Data.header;
header.id = script.id;
header.vSize = verticalSize;
header.vStartPos = verticalStartPos;
header.vStart = 0;
}
//------------------------------------------------------
// Operation and Parameter Layout
//------------------------------------------------------
// UNIFIED PIXEL COORDINATE SYSTEM:
// - All functions use PIXEL coordinates
// - Parameter: serialized as int grid indices (col/row) in 20px grid
// - Operation: stored as float pixels, snapped to 20.0 grid
// - Binary-verified snap formula: (int)((rel - grid*0.5) / grid + 1) * grid
//------------------------------------------------------
void LayoutCalculator::MoveParameterToPosition(Parameter ¶meter, const Point &pixelPos) {
// Input: pixel coordinates
// Output: integer (col,row) grid indices in 20px grid (binary-accurate serialization)
if (std::isfinite(pixelPos.h) && std::isfinite(pixelPos.v)) {
parameter.hPos = static_cast<int>(std::lround(pixelPos.h / HORIZONTAL_SPACING));
parameter.vPos = static_cast<int>(std::lround(pixelPos.v / VERTICAL_SPACING));
} else {
m_Context->OutputToConsoleEx((CKSTRING) "Warning: Invalid parameter position (%f, %f)", pixelPos.h, pixelPos.v);
}
}
void LayoutCalculator::MoveOperationToPosition(Operation &operation, const Point &pixelPos) {
// Input: pixel coordinates (target position for operation's input)
// Output: float pixels snapped to 20.0 grid
operation.hPos = SnapToGrid(pixelPos.h, HORIZONTAL_SPACING);
operation.vPos = SnapToGrid(pixelPos.v, VERTICAL_SPACING);
}
Point LayoutCalculator::GetInputParamPosition(CK_ID targetId, int inputIndex) {
// Returns PIXEL coordinates for input parameter position
Point position;
if (IsOperation(targetId)) {
Operation *operation = GetOperation(targetId);
if (operation) {
// Operation input parameters: horizontal offset by index * 2 * spacing
position.h = operation->hPos + static_cast<float>(inputIndex) * HORIZONTAL_SPACING * 2.0f;
position.v = operation->vPos;
}
} else {
BehaviorData *behaviorData = GetBehaviorData(targetId);
if (behaviorData) {
// Behavior input parameters: above the behavior block
float offset = behaviorData->isUsingTarget ? HORIZONTAL_SPACING : GRID_HALF_CELL;
position.h = behaviorData->rect.hPos + offset + HORIZONTAL_SPACING * static_cast<float>(inputIndex);
position.v = behaviorData->rect.vPos - HORIZONTAL_SPACING; // One grid cell above
}
}
return position;
}
Point LayoutCalculator::GetOutputParamPosition(CK_ID targetId, int outputIndex) {
// Returns PIXEL coordinates for output parameter position
Point position;
if (IsOperation(targetId)) {
Operation *operation = GetOperation(targetId);
if (operation) {
// Operation output: below the operation
position.h = operation->hPos + HORIZONTAL_SPACING;
position.v = operation->vPos + HORIZONTAL_SPACING * 2.0f;
}
} else {
BehaviorData *behaviorData = GetBehaviorData(targetId);
if (behaviorData) {
// Behavior output parameters: below the behavior block
float offset = behaviorData->isUsingTarget ? HORIZONTAL_SPACING : GRID_HALF_CELL;
position.h = behaviorData->rect.hPos + offset + HORIZONTAL_SPACING * static_cast<float>(outputIndex);
position.v = behaviorData->rect.vPos + behaviorData->rect.vSize + HORIZONTAL_SPACING;
}
}
return position;
}
void LayoutCalculator::CalculateOperationPositions(BehaviorData &behaviorGraph) {
// Position operations based on their parameter links
for (auto ¶mLink : behaviorGraph.links) {
if (paramLink.type != LINK_TYPE_PARAMETER)
continue;
// Parameter link
if (paramLink.start.type == ENDPOINT_POUT && IsOperation(paramLink.start.id)) {
// Skip if already moved
if (m_MovedOperations.find(paramLink.start.id) != m_MovedOperations.end()) {
continue;
}
Operation *startOperation = GetOperation(paramLink.start.id);
if (!startOperation) {
continue;
}
// Position based on destination
if (paramLink.end.type == ENDPOINT_PIN) {
// Ensure destination exists before getting position
BehaviorData *behaviorData = GetBehaviorData(paramLink.end.id);
if (behaviorData || IsOperation(paramLink.end.id)) {
// Normal input
MoveOperationToPosition(*startOperation,
GetInputParamPosition(paramLink.end.id, paramLink.end.index));
m_MovedOperations.insert(paramLink.start.id);
}
} else if (paramLink.end.type == ENDPOINT_TARGET_PIN) {
// Ensure destination exists before getting position
BehaviorData *behaviorData = GetBehaviorData(paramLink.end.id);
if (behaviorData) {
// Target input
MoveOperationToPosition(*startOperation,
GetInputParamPosition(paramLink.end.id, -1));
m_MovedOperations.insert(paramLink.start.id);
}
}
}
}
}
void LayoutCalculator::CalculateLocalParameterPositions(BehaviorData &behaviorGraph, bool isInputDirection) {
// Maintain a set of parameters we've already positioned to avoid overwrites
std::unordered_set<Parameter *> processedParams;
for (auto ¶mLink : behaviorGraph.links) {
if (paramLink.type != LINK_TYPE_PARAMETER)
continue;
// Parameter link
if (isInputDirection) {
// Position source parameters (inputs)
Parameter *startParam = nullptr;
if (paramLink.start.type == ENDPOINT_PLOCAL) {
// Local parameter
if (paramLink.start.index >= 0 &&
paramLink.start.index < static_cast<int>(behaviorGraph.localParams.size())) {
startParam = &behaviorGraph.localParams[paramLink.start.index];
}
} else if (paramLink.start.type == ENDPOINT_POUT_SHORTCUT) {
// Shared parameter
if (paramLink.start.index >= 0 &&
paramLink.start.index < static_cast<int>(behaviorGraph.sharedParams.size())) {
startParam = &behaviorGraph.sharedParams[paramLink.start.index];
}
}
if (startParam && processedParams.find(startParam) == processedParams.end()) {
if (paramLink.end.type == ENDPOINT_PIN) {
// Normal input
MoveParameterToPosition(*startParam, GetInputParamPosition(paramLink.end.id, paramLink.end.index));
processedParams.insert(startParam);
} else if (paramLink.end.type == ENDPOINT_TARGET_PIN) {
// Target input
MoveParameterToPosition(*startParam, GetInputParamPosition(paramLink.end.id, -1));
processedParams.insert(startParam);
}
}
} else {
// Position destination parameters (outputs)
Parameter *endParam = nullptr;
if (paramLink.end.type == ENDPOINT_PLOCAL) {
// Local parameter
if (paramLink.end.index >= 0 &&
paramLink.end.index < static_cast<int>(behaviorGraph.localParams.size())) {
endParam = &behaviorGraph.localParams[paramLink.end.index];
}
}
if (endParam && processedParams.find(endParam) == processedParams.end()) {
if (paramLink.start.type == ENDPOINT_POUT) {
// From output
MoveParameterToPosition(
*endParam, GetOutputParamPosition(paramLink.start.id, paramLink.start.index));
processedParams.insert(endParam);
}
}
}
}
}
void LayoutCalculator::CalculateLinkRoutes(BehaviorData &behaviorData) {
// Process each link in the behavior
for (auto &link : behaviorData.links) {
RouteLink(link);
}
}
void LayoutCalculator::RouteLink(Link &link) {
// Get endpoint positions
const Point startPos = GetEndpointPosition(link.start);
const Point endPos = GetEndpointPosition(link.end);
if (startPos.Zero() || endPos.Zero()) {
// Invalid start or end position
m_Context->OutputToConsoleEx((CKSTRING) "Warning: Invalid start or end position for link %d", link.id);
return;
}
// Create a path connecting the points - exclude start and end positions
link.points = CreatePath(startPos, endPos, link);
}
LayoutCalculator::LinkCharacteristics LayoutCalculator::DetermineRoutingCharacteristics(const Link &link) {
LinkCharacteristics result;
// Determine link type
if (link.IsBehaviorLink()) {
result.linkType = LinkType::BehaviorFlow;
} else if (link.IsParameterOpLink()) {
result.linkType = LinkType::ParameterOperation;
} else {
result.linkType = LinkType::ParameterData;
}
// Check if this is a self-connection
result.isSelfConnection = (link.start.id == link.end.id);
// Check if this is a start link
result.isStartLink = link.start.IsStartBehaviorInput();
// Determine endpoint types
result.isSourceBehaviorOutput = link.start.IsBehaviorOutput();
result.isSourceParameterOutput = link.start.IsParameterOutput();
result.isTargetBehaviorInput = link.end.IsBehaviorInput();
result.isTargetParameterInput = link.end.IsParameterInput();
// Check for operation involvement
result.isSourceOperation = IsOperation(link.start.id);
result.isTargetOperation = IsOperation(link.end.id);
// Check for parameter shortcuts
result.isParameterShortcut = link.start.IsParameterShortCut();
return result;
}
Point LayoutCalculator::GetEndpointPosition(const LinkEndpoint &endpoint) {
// Handle different endpoint types based on their category
if (endpoint.IsParameterInput()) {
return GetParameterInputPosition(endpoint);
} else if (endpoint.IsParameterOutput()) {
return GetParameterOutputPosition(endpoint);
} else if (endpoint.IsParameterLocal()) {
return GetLocalParameterPosition(endpoint);
} else if (endpoint.IsBehaviorInput()) {
return GetBehaviorInputPosition(endpoint);
} else if (endpoint.IsBehaviorOutput()) {
return GetBehaviorOutputPosition(endpoint);
}
// Unknown endpoint type - use default position
m_Context->OutputToConsoleEx((CKSTRING) "Warning: Unknown endpoint type %d", endpoint.type);
return {};
}
Point LayoutCalculator::GetParameterInputPosition(const LinkEndpoint &endpoint) {
Point position;
if (endpoint.type == ENDPOINT_TARGET_PIN) {
// Target parameter is special
BehaviorData *behaviorData = GetBehaviorData(endpoint.id);
if (!behaviorData) {
m_Context->OutputToConsoleEx((CKSTRING) "Error: Behavior data not found for ID %d", endpoint.id);
return position;
}
// Left side, middle of the block
position.h = behaviorData->rect.hPos;
position.v = behaviorData->rect.vPos;
} else if (IsOperation(endpoint.id)) {
// Parameter input on operation
Operation *operation = GetOperation(endpoint.id);
if (!operation) {
m_Context->OutputToConsoleEx((CKSTRING) "Error: Operation with ID %d not found", endpoint.id);
return position;
}
// Position based on input index
position.h = operation->hPos;
position.v = operation->vPos;
if (endpoint.index == 0) {
// First input is on left side
position.h -= GRID_HALF_CELL;
} else if (endpoint.index == 1) {
// Second input is on right side
position.h += GRID_HALF_CELL;
}
} else {
// Parameter input on behavior
BehaviorData *behaviorData = GetBehaviorData(endpoint.id);
if (!behaviorData) {
m_Context->OutputToConsoleEx((CKSTRING) "Error: Behavior data not found for ID %d", endpoint.id);
return position;
}
float offset = (behaviorData->isUsingTarget) ? HORIZONTAL_SPACING : GRID_HALF_CELL;
position.h = behaviorData->rect.hPos + offset + HORIZONTAL_SPACING * endpoint.index;
position.v = behaviorData->rect.vPos;
}
return position;
}
Point LayoutCalculator::GetParameterOutputPosition(const LinkEndpoint &endpoint) {
Point position;
if (endpoint.type == ENDPOINT_POUT_SHORTCUT) {
// Parameter output shortcut
BehaviorData *behaviorData = GetBehaviorData(endpoint.id);
if (!behaviorData) {
m_Context->OutputToConsoleEx((CKSTRING) "Error: Behavior data not found for ID %d", endpoint.id);
return position;
}
// Validate index is within bounds
if (endpoint.index < 0 || endpoint.index >= static_cast<int>(behaviorData->sharedParams.size())) {
m_Context->OutputToConsoleEx((CKSTRING) "Error: Parameter shortcut index %d out of bounds (size %d)",
endpoint.index, behaviorData->sharedParams.size());
return position;
}
// Get the parameter position
Parameter ¶m = behaviorData->sharedParams[endpoint.index];
position.h = static_cast<float>(param.hPos) * HORIZONTAL_SPACING;
position.v = static_cast<float>(param.vPos) * VERTICAL_SPACING;
} else if (IsOperation(endpoint.id)) {
// Parameter output on operation
Operation *operation = GetOperation(endpoint.id);
if (!operation) {
m_Context->OutputToConsoleEx((CKSTRING) "Error: Operation with ID %d not found", endpoint.id);
return position;
}
// Output of operation - center with slight vertical offset
position.h = operation->hPos;
position.v = operation->vPos + PARAMETER_LINK_VERTICAL_OFFSET;
} else {
// Parameter output on behavior
BehaviorData *behaviorData = GetBehaviorData(endpoint.id);
if (!behaviorData) {
m_Context->OutputToConsoleEx((CKSTRING) "Error: Behavior data not found for ID %d", endpoint.id);
return position;
}
float offset = (behaviorData->isUsingTarget) ? HORIZONTAL_SPACING : GRID_HALF_CELL;
position.h = behaviorData->rect.hPos + offset + HORIZONTAL_SPACING * endpoint.index;
position.v = behaviorData->rect.vPos + behaviorData->rect.vSize;
}
return position;
}
Point LayoutCalculator::GetLocalParameterPosition(const LinkEndpoint &endpoint) {
Point position;
BehaviorData *behaviorData = GetBehaviorData(endpoint.id);
if (!behaviorData) {
m_Context->OutputToConsoleEx((CKSTRING) "Error: Behavior data not found for ID %d", endpoint.id);