Ember
Loading...
Searching...
No Matches
TreeVisualization.cpp
Go to the documentation of this file.
3#include "Utils/Logger.h"
6#include <algorithm>
7#include <cmath>
8#include <set>
9#include <wx/filename.h>
10#include <wx/stdpaths.h>
11
12namespace EmberCore {
13
21
22 TreeVisualization::TreeVisualization(wxWindow *parent, wxWindowID id)
23 : wxPanel(parent, id), title_font_(12, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL) {
24 SetBackgroundColour(config_.background_color);
25 SetCanFocus(true); // Enable keyboard events
26
27 // Load preferences for zoom/pan behavior
28 LoadPreferences();
29
30 // Load node type icons
31 wxString icon_dir = EmberForge::ResourcePath::GetDir("icons/tree_nodes");
32
33 icon_action_.LoadFile(icon_dir + "action_node_30.png", wxBITMAP_TYPE_PNG);
34 icon_control_.LoadFile(icon_dir + "control_node_30.png", wxBITMAP_TYPE_PNG);
35 icon_condition_.LoadFile(icon_dir + "condition_node_30.png", wxBITMAP_TYPE_PNG);
36 icon_decorator_.LoadFile(icon_dir + "decorator_node_30.png", wxBITMAP_TYPE_PNG);
37 icon_tree_.LoadFile(icon_dir + "tree_node_30.png", wxBITMAP_TYPE_PNG);
38 icon_warning_.LoadFile(icon_dir + "warning_30.png", wxBITMAP_TYPE_PNG);
39
40 // Initialize scaled icons cache
41 UpdateScaledIcons();
42
43 // Initialize frame timing
44 last_frame_time_ = wxGetUTCTimeMillis();
45
46 // Create timer for regular performance monitoring updates
47 m_performanceTimer = new wxTimer(this, wxID_ANY);
48 m_performanceTimer->Start(33); // ~30 FPS for consistent frame timing
49
50 // Bind timer event
51 Bind(wxEVT_TIMER, [this](wxTimerEvent &) {
52 // Calculate delta time for FPS-independent smoothing
53 wxLongLong currentTime = wxGetUTCTimeMillis();
54 double deltaTime = (currentTime - last_frame_time_).ToDouble() / 1000.0; // Convert to seconds
55 last_frame_time_ = currentTime;
56
57 // Clamp deltaTime to prevent huge jumps if window was minimized/frozen
58 if (deltaTime > 0.1)
59 deltaTime = 0.033; // Cap at ~30 FPS worth of time
60
61 // Smooth pan interpolation (FPS-independent)
62 if (enable_smooth_panning_) {
63 float dx = target_offset_.x - view_offset_.x;
64 float dy = target_offset_.y - view_offset_.y;
65
66 // Only interpolate if there's a meaningful distance
67 if (std::abs(dx) > 0.1f || std::abs(dy) > 0.1f) {
68 // Convert smoothness percentage to smooth speed
69 // Higher smoothness = slower movement (more smooth)
70 // 0% = instant (speed = 100), 100% = very smooth (speed = 1)
71 float smoothSpeed = 100.0f - pan_smoothness_; // Invert so higher % is smoother
72 smoothSpeed = std::max(1.0f, smoothSpeed); // Clamp minimum
73
74 // Exponential decay interpolation (FPS-independent)
75 float alpha = 1.0f - exp(-smoothSpeed * 0.05f * deltaTime);
76
77 view_offset_.x += static_cast<int>(dx * alpha);
78 view_offset_.y += static_cast<int>(dy * alpha);
79 } else {
80 // Snap to target when close enough
81 view_offset_ = target_offset_;
82 }
83 } else {
84 // Instant panning when smoothing is disabled
85 view_offset_ = target_offset_;
86 }
87
88 // Trigger a redraw to get frame timing measurements
89 Refresh();
90 });
91}
92
94 // CRITICAL: Stop and delete timer to prevent crash
96 m_performanceTimer->Stop();
97 delete m_performanceTimer;
98 m_performanceTimer = nullptr;
99 }
100}
101
102void TreeVisualization::SetBehaviorTree(std::shared_ptr<ITreeStructure> tree) {
103 tree_ = tree;
104 selected_node_ = nullptr;
105 hovered_node_ = nullptr;
106 ClearWidthCache(); // Clear cache when tree changes
107 ResetView();
108 Refresh();
109}
110
112 // Store the original node pointer directly to preserve identity for comparison
113 if (node) {
114 // Use a non-deleting shared_ptr to preserve the original pointer identity
115 selected_node_ = std::shared_ptr<ITreeNode>(node, [](ITreeNode *) {});
116 } else {
117 selected_node_.reset();
118 }
119
120 // Call the callback if set
123 }
124
125 Refresh();
126}
127
129 // Get default zoom level from preferences
131 zoom_factor_ = prefs.GetMainPanelSettings().defaultZoomLevel;
132
133 // Center the tree in the view
134 wxSize panel_size = GetSize();
135 view_offset_ = {panel_size.GetWidth() / 2, 100}; // Center horizontally, some top margin
136 target_offset_ = view_offset_; // Sync target to avoid smooth transition on reset
137
138 Refresh();
139}
140
142 if (!node || !tree_)
143 return;
144
145 wxSize panel_size = GetSize();
146
147 // Find the world position of the target node
148 wxPoint node_world_pos = FindNodeWorldPosition(node);
149
150 if (node_world_pos.x != -1 && node_world_pos.y != -1) {
151 // Center the view on this node by adjusting view_offset
152 // The formula: screen_center = world_pos * zoom + view_offset
153 // So: view_offset = screen_center - world_pos * zoom
154 view_offset_ = {panel_size.x / 2 - static_cast<int>(node_world_pos.x * zoom_factor_),
155 panel_size.y / 2 - static_cast<int>(node_world_pos.y * zoom_factor_)};
156 target_offset_ = view_offset_; // Sync target for instant snap
157 } else {
158 // Fallback to root if node not found
159 wxPoint root_pos = CalculateRootPosition();
160 view_offset_ = {panel_size.x / 2 - static_cast<int>(root_pos.x * zoom_factor_),
161 panel_size.y / 2 - static_cast<int>(root_pos.y * zoom_factor_)};
162 target_offset_ = view_offset_; // Sync target for instant snap
163 }
164
165 Refresh();
166}
167
169 zoom_factor_ = std::max(min_zoom_, std::min(max_zoom_, zoom));
170 UpdateScaledIcons(); // Update icon cache when zoom changes
171 Refresh();
172}
173
175 // Only update if zoom changed significantly (avoid constant rescaling)
176 // But always update if cache is uninitialized (cached_icon_zoom_ == 0)
177 if (cached_icon_zoom_ != 0.0f && std::abs(zoom_factor_ - cached_icon_zoom_) < 0.05f) {
178 return;
179 }
180
182
183 // Helper lambda to scale a single icon with high quality
184 auto scaleIcon = [this](const wxBitmap &original) -> wxBitmap {
185 if (!original.IsOk())
186 return wxBitmap();
187
188 wxImage img = original.ConvertToImage();
189 int new_size = static_cast<int>(30 * zoom_factor_);
190 new_size = std::max(4, std::min(300, new_size)); // Clamp to reasonable range
191
192 if (new_size != 30) {
193 img = img.Scale(new_size, new_size, wxIMAGE_QUALITY_BICUBIC);
194 }
195 return wxBitmap(img);
196 };
197
198 // Scale all icons
203 scaled_icon_tree_ = scaleIcon(icon_tree_);
205}
206
207// Event Handlers
208void TreeVisualization::OnPaint(wxPaintEvent &event) {
209 // Begin frame timing for main rendering
211
212 // Time the entire paint operation
213 PERF_TIME_BEGIN(tree_visualization_paint);
214
215 wxPaintDC dc(this);
216
217 // Clear background
218 PERF_TIME_BEGIN(background_clear);
219 dc.SetBackground(wxBrush(config_.background_color));
220 dc.Clear();
221 PERF_TIME_END(background_clear);
222
223 // Apply zoom transformation
224 dc.SetUserScale(zoom_factor_, zoom_factor_);
225 dc.SetDeviceOrigin(view_offset_.x, view_offset_.y);
226
227 // Draw grid
228 PERF_TIME_BEGIN(grid_drawing);
229 DrawGrid(dc);
230 PERF_TIME_END(grid_drawing);
231
232 // Build path to selected node if highlighting is enabled
233 // Use node IDs instead of pointers because tree uses different adapter instances
234 path_to_selected_ids_.clear();
236 collapse_arrows_to_draw_.clear(); // Clear arrows for this frame
238 const auto &mainPanelSettings = prefs.GetMainPanelSettings();
239 if (mainPanelSettings.highlightPathToSelected && selected_node_) {
240 ITreeNode *current = selected_node_.get();
241 while (current) {
242 path_to_selected_ids_.insert(current->GetId());
243 current = current->GetParent();
244 }
245 }
246
247 // Draw behavior tree
248 if (tree_ && tree_->HasRootNode()) {
249 PERF_TIME_BEGIN(tree_drawing);
250 wxPoint root_pos = CalculateRootPosition();
251 DrawNode(dc, tree_->GetRootNode(), root_pos.x, root_pos.y, 0);
252 PERF_TIME_END(tree_drawing);
253 }
254
255 // Draw highlighted path segments on top (after all normal connections)
256 if (!highlighted_path_segments_.empty()) {
257 wxColour pathColor(mainPanelSettings.pathHighlightColor.r, mainPanelSettings.pathHighlightColor.g,
258 mainPanelSettings.pathHighlightColor.b);
259 dc.SetPen(wxPen(pathColor, 4)); // Thicker for highlighted path
260 for (const auto &seg : highlighted_path_segments_) {
261 dc.DrawLine(seg.x1, seg.y1, seg.x2, seg.y2);
262 }
263 }
264
265 // Draw all collapse arrows on top of everything for proper z-order
266 for (const auto &arrow_info : collapse_arrows_to_draw_) {
267 DrawCollapseArrow(dc, arrow_info.node, arrow_info.x, arrow_info.y);
268 }
269
270 // Draw navigation info in screen coordinates (reset transformation)
271 PERF_TIME_BEGIN(ui_overlay_drawing);
273 PERF_TIME_END(ui_overlay_drawing);
274
275 // Record performance metrics
277 if (monitor.IsEnabled()) {
278 // Record tree-specific metrics
279 if (tree_ && tree_->HasRootNode()) {
280 monitor.RecordMetric("Tree Nodes", static_cast<float>(tree_->GetNodeCount()), "nodes");
281 monitor.RecordMetric("Tree Depth", static_cast<float>(tree_->GetMaxDepth()), "levels");
282 }
283 monitor.RecordMetric("Zoom Level", zoom_factor_ * 100.0f, "%");
284 }
285
286 PERF_TIME_END(tree_visualization_paint);
287
288 // End frame timing
290}
291
292void TreeVisualization::OnSize(wxSizeEvent &event) {
293 Refresh();
294 event.Skip();
295}
296
297void TreeVisualization::OnMouseLeftDown(wxMouseEvent &event) {
298 // Always grab focus when clicked to ensure arrow keys work
299 SetFocus();
300
301 // If left mouse button is configured for panning, don't handle node selection
302 if (pan_key_code_ == -1 && pan_mouse_button_ == 1) {
303 // Panning will be handled in OnMouseMotion
304 event.Skip(); // Allow event to continue for drag handling
305 return;
306 }
307
308 // Handle node selection
309 if (!tree_ || !tree_->HasRootNode()) {
310 event.Skip();
311 return;
312 }
313
314 wxPoint mouse_pos = event.GetPosition();
315 wxPoint world_pos = ScreenToWorld(mouse_pos);
316 wxPoint root_pos = CalculateRootPosition();
317
318 ITreeNode *clicked_node = FindNodeAtPosition(tree_->GetRootNode(), root_pos, world_pos);
319
320 SetSelectedNode(clicked_node);
321
322 // Don't skip - we handled the event
323}
324
325void TreeVisualization::OnMouseLeftDClick(wxMouseEvent &event) {
326 if (!tree_ || !tree_->HasRootNode())
327 return;
328
329 // Find the node that was double-clicked
330 wxPoint mouse_pos = event.GetPosition();
331 wxPoint world_pos = ScreenToWorld(mouse_pos);
332 wxPoint root_pos = CalculateRootPosition();
333 ITreeNode *clicked_node = FindNodeAtPosition(tree_->GetRootNode(), root_pos, world_pos);
334
335 // Center view on the double-clicked node
336 if (clicked_node) {
337 SetSelectedNode(clicked_node);
338 CenterOnNode(clicked_node);
339 }
340}
341
342void TreeVisualization::OnMouseRightDown(wxMouseEvent &event) {
343 // Could implement context menu here
344 LOG_INFO("TreeVisualization", "Right click on visualization at (" + std::to_string(event.GetX()) + ", " +
345 std::to_string(event.GetY()) + ")");
346}
347
348void TreeVisualization::OnMouseMotion(wxMouseEvent &event) {
349 wxPoint mouse_pos = event.GetPosition();
350
351 // Check if panning is active (either by key or mouse button)
352 bool shouldPan = false;
353
354 if (pan_key_code_ == -1) {
355 // Using mouse button for panning
356 if (pan_mouse_button_ == 1) {
357 shouldPan = event.LeftIsDown();
358 } else if (pan_mouse_button_ == 2) {
359 shouldPan = event.MiddleIsDown();
360 } else if (pan_mouse_button_ == 3) {
361 shouldPan = event.RightIsDown();
362 }
363 } else {
364 // Using keyboard key for panning
365 shouldPan = pan_key_held_;
366 }
367
368 // Handle panning if pan key/button is held down
369 if (shouldPan) {
370 if (!is_panning_) {
371 is_panning_ = true;
372 last_mouse_pos_ = mouse_pos;
373 } else {
374 wxPoint delta = mouse_pos - last_mouse_pos_;
375 // Apply pan sensitivity
376 delta.x = static_cast<int>(delta.x * pan_sensitivity_);
377 delta.y = static_cast<int>(delta.y * pan_sensitivity_);
378 view_offset_ += delta;
379 target_offset_ = view_offset_; // Keep target in sync during drag
380 last_mouse_pos_ = mouse_pos;
381 Refresh();
382 }
383 return;
384 }
385
386 // Stop panning if key/button was released
387 if (is_panning_) {
388 is_panning_ = false;
389 }
390
391 // Update hovered node (convert mouse position to world coordinates)
392 if (tree_ && tree_->HasRootNode()) {
393 wxPoint world_pos = ScreenToWorld(mouse_pos);
394 wxPoint root_pos = CalculateRootPosition();
395 ITreeNode *new_hovered = FindNodeAtPosition(tree_->GetRootNode(), root_pos, world_pos);
396
397 if (new_hovered != hovered_node_) {
398 hovered_node_ = new_hovered;
399 Refresh();
400 }
401 }
402}
403
404void TreeVisualization::OnMouseWheel(wxMouseEvent &event) {
405 float old_zoom = zoom_factor_;
406
407 // Apply zoom step and mouse wheel sensitivity from preferences
408 float zoom_delta = (event.GetWheelRotation() > 0 ? zoom_step_ : -zoom_step_) * mouse_wheel_sensitivity_;
409 zoom_factor_ += zoom_delta;
410
411 zoom_factor_ = std::max(min_zoom_, std::min(max_zoom_, zoom_factor_));
412
413 if (old_zoom != zoom_factor_) {
415 // Zoom towards cursor position
416 wxPoint mouse_screen = event.GetPosition();
417
418 // Convert mouse position to world coordinates using the OLD zoom level
419 wxPoint mouse_world = {static_cast<int>((mouse_screen.x - view_offset_.x) / old_zoom),
420 static_cast<int>((mouse_screen.y - view_offset_.y) / old_zoom)};
421
422 // Calculate where that world point should appear with the NEW zoom level
423 // to keep it under the mouse cursor
424 view_offset_.x = mouse_screen.x - mouse_world.x * zoom_factor_;
425 view_offset_.y = mouse_screen.y - mouse_world.y * zoom_factor_;
426 target_offset_ = view_offset_; // Keep target in sync for zoom
427 }
428 // else: zoom towards center (view_offset stays unchanged)
429
430 Refresh();
431 }
432}
433
434void TreeVisualization::OnMouseMiddleDown(wxMouseEvent &event) {
435 is_panning_ = true;
436 last_mouse_pos_ = event.GetPosition();
437}
438
439void TreeVisualization::OnMouseMiddleUp(wxMouseEvent &event) { is_panning_ = false; }
440
441void TreeVisualization::OnKeyDown(wxKeyEvent &event) {
442 int keyCode = event.GetKeyCode();
443
444 // Check if this is the pan key
445 if (keyCode == pan_key_code_) {
446 pan_key_held_ = true;
447 return; // Don't process other actions when pan key is pressed
448 }
449
450 // Get the configured hotkeys from preferences
452 const auto &btViewSettings = prefs.GetBehaviorTreeViewSettings();
453
454 // Helper lambda to check if a key matches a hotkey string
455 auto matchesHotkey = [&](const EmberCore::String &hotkey) -> bool {
456 if (hotkey.length() == 1) {
457 // Single character hotkey
458 char hotkeyChar = hotkey[0];
459 return (keyCode == toupper(hotkeyChar));
460 } else if (hotkey == "Delete") {
461 return (keyCode == WXK_DELETE);
462 } else if (hotkey == "F5") {
463 return (keyCode == WXK_F5);
464 } else if (hotkey == "Up") {
465 return (keyCode == WXK_UP);
466 } else if (hotkey == "Down") {
467 return (keyCode == WXK_DOWN);
468 } else if (hotkey == "Left") {
469 return (keyCode == WXK_LEFT);
470 } else if (hotkey == "Right") {
471 return (keyCode == WXK_RIGHT);
472 }
473 // Add more special keys as needed
474 return false;
475 };
476
477 // Handle arrow key navigation for panning (using configured hotkeys)
478 const float arrow_pan_step = pan_step_size_ * pan_sensitivity_;
479 bool handled = false;
480
481 if (matchesHotkey(btViewSettings.panUpHotkey)) {
482 target_offset_.y += static_cast<int>(arrow_pan_step);
483 handled = true;
484 } else if (matchesHotkey(btViewSettings.panDownHotkey)) {
485 target_offset_.y -= static_cast<int>(arrow_pan_step);
486 handled = true;
487 } else if (matchesHotkey(btViewSettings.panLeftHotkey)) {
488 target_offset_.x += static_cast<int>(arrow_pan_step);
489 handled = true;
490 } else if (matchesHotkey(btViewSettings.panRightHotkey)) {
491 target_offset_.x -= static_cast<int>(arrow_pan_step);
492 handled = true;
493 }
494
495 if (handled) {
496 // Don't call Refresh() here - the timer will handle it
497 return;
498 }
499
500 // Check reset view hotkey
501 if (matchesHotkey(btViewSettings.resetViewHotkey)) {
502 ResetView();
503 return;
504 }
505
506 // Check expand/collapse hotkey (previously center on node)
507 if (matchesHotkey(btViewSettings.centerOnNodeHotkey)) {
508 if (selected_node_ && selected_node_->GetChildCount() > 0) {
509 bool current_visibility = selected_node_->AreChildrenVisible();
510 selected_node_->SetChildrenVisible(!current_visibility);
512 Refresh();
513 }
514 return;
515 }
516
517 // Check delete node hotkey
518 if (matchesHotkey(btViewSettings.deleteNodeHotkey)) {
519 if (selected_node_) {
520 LOG_INFO("TreeVisualization", "Delete key pressed for node: " + selected_node_->GetName());
521 }
522 return;
523 }
524
525 // IMPORTANT: Consume arrow key events to prevent them from propagating
526 // to parent/sibling controls (like the SceneHierarchyTab tree control)
527 if (keyCode == WXK_UP || keyCode == WXK_DOWN || keyCode == WXK_LEFT || keyCode == WXK_RIGHT) {
528 // Arrow key pressed but not configured as a hotkey - still consume it
529 // to prevent unwanted tree navigation in other controls
530 return;
531 }
532
533 // For other keys, let the event propagate (e.g., Tab for focus navigation)
534 event.Skip();
535}
536
537// Drawing Methods
539 // Don't draw grid if disabled in preferences
540 if (!show_grid_) {
541 return;
542 }
543
544 // Calculate world space bounds visible on screen
545 wxSize panel_size = GetSize();
546 wxPoint topLeft = ScreenToWorld({0, 0});
547 wxPoint bottomRight = ScreenToWorld({panel_size.x, panel_size.y});
548
549 // Get grid colors from preferences
551 const auto &mainPanelSettings = prefs.GetMainPanelSettings();
552 wxColour gridBgColor(mainPanelSettings.gridBackgroundColor.r, mainPanelSettings.gridBackgroundColor.g,
553 mainPanelSettings.gridBackgroundColor.b);
554 wxColour gridLineColor(mainPanelSettings.gridLineColor.r, mainPanelSettings.gridLineColor.g,
555 mainPanelSettings.gridLineColor.b);
556
557 // Draw grid background
558 dc.SetBrush(wxBrush(gridBgColor));
559 dc.SetPen(*wxTRANSPARENT_PEN);
560 dc.DrawRectangle(topLeft.x, topLeft.y, bottomRight.x - topLeft.x, bottomRight.y - topLeft.y);
561
562 // Draw grid lines
563 dc.SetPen(wxPen(gridLineColor, 1));
564 dc.SetBrush(*wxTRANSPARENT_BRUSH);
565
566 // Adjust grid spacing based on zoom level for better visibility
567 int gridSpacing = grid_size_;
568 if (zoom_factor_ < 0.5f)
569 gridSpacing = grid_size_ * 4; // Sparse grid when zoomed out
570 else if (zoom_factor_ < 0.8f)
571 gridSpacing = grid_size_ * 2; // Medium grid
572 else if (zoom_factor_ > 2.0f)
573 gridSpacing = grid_size_ / 2; // Dense grid when zoomed in
574
575 // Draw vertical grid lines in world coordinates
576 int startX = (topLeft.x / gridSpacing) * gridSpacing;
577 int endX = bottomRight.x;
578 for (int x = startX; x <= endX; x += gridSpacing) {
579 dc.DrawLine(x, topLeft.y, x, bottomRight.y);
580 }
581
582 // Draw horizontal grid lines in world coordinates
583 int startY = (topLeft.y / gridSpacing) * gridSpacing;
584 int endY = bottomRight.y;
585 for (int y = startY; y <= endY; y += gridSpacing) {
586 dc.DrawLine(topLeft.x, y, bottomRight.x, y);
587 }
588}
589
590void TreeVisualization::DrawNode(wxDC &dc, ITreeNode *node, wxCoord x, wxCoord y, int level, bool draw_children) {
591 if (!node)
592 return;
593
594 // VIEWPORT CULLING: Check if this node is in viewport (if culling is enabled)
595 bool nodeInViewport = !enable_viewport_culling_ || IsNodeInViewport(x, y);
596
597 // Only draw the node itself if it's in the viewport
598 if (nodeInViewport) {
599 // No coordinate conversion needed - draw directly in world coordinates
600 // The DC already has zoom/pan transformation applied in OnPaint
601
602 // Draw node box and text
603 DrawNodeBox(dc, node, x, y);
604 DrawNodeText(dc, node, x, y);
605
606 // Collect collapse arrow for later drawing (on top of everything)
607 if (node->GetChildCount() > 0) {
608 collapse_arrows_to_draw_.push_back({node, x, y});
609 }
610 }
611
612 // Always check and draw children (they might be visible even if parent isn't)
613 if (draw_children && node->AreChildrenVisible() && node->GetChildCount() > 0) {
614 int total_width = CalculateSubtreeWidth(node);
615 wxCoord child_x = x - total_width / 2;
616 wxCoord child_y = y + config_.node_height + config_.vertical_spacing;
617
618 // First pass: check if we need to draw connections by checking if any child will be drawn
619 bool shouldDrawConnections = nodeInViewport; // Always draw if parent is visible
620
621 if (!shouldDrawConnections) {
622 // Check if the child row intersects viewport (check the whole horizontal span)
623 wxRect viewport = GetViewportBounds();
624 int margin = static_cast<int>(viewport_culling_margin_ / zoom_factor_);
625 viewport.Inflate(margin);
626
627 // Check if child Y position is in viewport vertical range
628 if (child_y >= viewport.GetTop() && child_y <= viewport.GetBottom()) {
629 // Check if any part of the child row's horizontal span intersects viewport
630 int leftmost_x = child_x;
631 int rightmost_x = child_x + total_width;
632 if (rightmost_x >= viewport.GetLeft() && leftmost_x <= viewport.GetRight()) {
633 shouldDrawConnections = true;
634 }
635 }
636 }
637
638 // Draw connections if needed
639 if (shouldDrawConnections) {
640 DrawNodeConnections(dc, node, x, y);
641 }
642
643 // Draw all children (they will individually check their viewport visibility)
644 for (size_t i = 0; i < node->GetChildCount(); ++i) {
645 ITreeNode *child = node->GetChild(i);
646 if (child) {
647 int subtree_width = CalculateSubtreeWidth(child);
648 wxCoord center_x = child_x + subtree_width / 2;
649
650 // Recursively draw child (it will check its own viewport visibility)
651 DrawNode(dc, child, center_x, child_y, level + 1, draw_children);
652
653 child_x += subtree_width;
654 }
655 }
656 }
657}
658
659void TreeVisualization::DrawNodeBox(wxDC &dc, ITreeNode *node, wxCoord x, wxCoord y) {
660 // Get preferences
662 const auto &mainPanelSettings = prefs.GetMainPanelSettings();
663
664 // Base node background color
665 wxColour base_color(mainPanelSettings.idleNodeBgColor.r, mainPanelSettings.idleNodeBgColor.g,
666 mainPanelSettings.idleNodeBgColor.b);
667
668 wxColour fill_color = base_color;
669 wxColour border_color(mainPanelSettings.idleNodeBorderColor.r, mainPanelSettings.idleNodeBorderColor.g,
670 mainPanelSettings.idleNodeBorderColor.b);
671 int border_width = 1;
672
673 // Use ONLY pointer comparison for exact node identity
674 bool isSelected = false;
675 if (selected_node_) {
676 // Match by pointer comparison only - ensures we highlight the exact clicked node
677 isSelected = (node == selected_node_.get());
678 }
679
680 // Helper lambda to apply tint to a color
681 auto applyTint = [](const wxColour &color, float tint) -> wxColour {
682 int r = color.Red();
683 int g = color.Green();
684 int b = color.Blue();
685
686 if (tint > 0) {
687 // Lighten: blend towards white
688 r = r + static_cast<int>((255 - r) * tint);
689 g = g + static_cast<int>((255 - g) * tint);
690 b = b + static_cast<int>((255 - b) * tint);
691 } else {
692 // Darken: blend towards black
693 r = r + static_cast<int>(r * tint);
694 g = g + static_cast<int>(g * tint);
695 b = b + static_cast<int>(b * tint);
696 }
697
698 return wxColour(r, g, b);
699 };
700
701 // Check if this is a SubTree reference node
702 bool isSubTree = node->IsSubTreeReference();
703
704 if (isSelected) {
705 // Apply selected tint to base color
706 fill_color = applyTint(base_color, mainPanelSettings.selectedNodeBgTint);
707 border_color = wxColour(mainPanelSettings.selectedNodeColor.r, mainPanelSettings.selectedNodeColor.g,
708 mainPanelSettings.selectedNodeColor.b);
709 border_width = 3;
710 } else if (node == hovered_node_) {
711 // Apply hovered tint to base color
712 fill_color = applyTint(base_color, mainPanelSettings.hoveredNodeBgTint);
713 border_color = wxColour(mainPanelSettings.hoveredNodeColor.r, mainPanelSettings.hoveredNodeColor.g,
714 mainPanelSettings.hoveredNodeColor.b);
715 border_width = 2;
716 }
717
718 // SubTree nodes get a subtle blue tint to distinguish them
719 if (isSubTree && !isSelected && node != hovered_node_) {
720 fill_color = applyTint(base_color, -0.05f); // Slightly darker
721 // Add a blue tint to the border
722 border_color = wxColour(100, 150, 255); // Light blue
723 border_width = 2;
724 }
725
726 dc.SetBrush(wxBrush(fill_color));
727
728 // Use dashed pen for SubTree nodes
729 if (isSubTree) {
730 wxPen pen(border_color, border_width, wxPENSTYLE_SHORT_DASH);
731 dc.SetPen(pen);
732 } else {
733 dc.SetPen(wxPen(border_color, border_width));
734 }
735
736 wxRect node_rect(x - config_.node_width / 2, y, config_.node_width, config_.node_height);
737
738 dc.DrawRoundedRectangle(node_rect, 5);
739}
740
741void TreeVisualization::DrawNodeText(wxDC &dc, ITreeNode *node, wxCoord x, wxCoord y) {
742 dc.SetFont(title_font_);
743
744 // Get preferences
746 const auto &mainPanelSettings = prefs.GetMainPanelSettings();
747
748 // Determine text color based on state (default to idle color)
749 wxColour text_color(mainPanelSettings.idleNodeTextColor.r, mainPanelSettings.idleNodeTextColor.g,
750 mainPanelSettings.idleNodeTextColor.b);
751
752 // Check if node is selected
753 bool isSelected = false;
754 if (selected_node_) {
755 isSelected = (node == selected_node_.get());
756 if (!isSelected && node->GetId() == selected_node_->GetId() && node->GetName() == selected_node_->GetName()) {
757 isSelected = true;
758 }
759 }
760
761 if (isSelected) {
762 text_color = wxColour(mainPanelSettings.selectedNodeTextColor.r, mainPanelSettings.selectedNodeTextColor.g,
763 mainPanelSettings.selectedNodeTextColor.b);
764 } else if (node == hovered_node_) {
765 text_color = wxColour(mainPanelSettings.hoveredNodeTextColor.r, mainPanelSettings.hoveredNodeTextColor.g,
766 mainPanelSettings.hoveredNodeTextColor.b);
767 }
768
769 dc.SetTextForeground(text_color);
770
771 EmberCore::String text = node->GetName();
772 wxCoord text_width, text_height;
773 dc.GetTextExtent(text, &text_width, &text_height);
774
775 // Truncate text if too long
776 if (text_width > config_.node_width - 10) {
777 while (text_width > config_.node_width - 20 && text.length() > 3) {
778 text = text.substr(0, text.length() - 1);
779 dc.GetTextExtent(text + "...", &text_width, &text_height);
780 }
781 text += "...";
782 }
783
784 // Draw text centered in node
785 wxCoord text_x = x - text_width / 2;
786 wxCoord text_y = y + config_.title_padding.y;
787
788 dc.DrawText(text, text_x, text_y);
789
790 // Draw node type icon (centered between name and type/status)
791 // Use pre-scaled high-quality icons for better appearance
792 wxBitmap *icon_to_draw = nullptr;
793
794 if (node->IsSubTreeReference() && !node->IsUnimplementedReference()) {
795 icon_to_draw = &scaled_icon_tree_;
796 } else if (node->IsUnimplementedReference()) {
797 icon_to_draw = &scaled_icon_warning_;
798 } else {
799 // Determine icon based on node type
800 switch (node->GetType()) {
802 icon_to_draw = &scaled_icon_action_;
803 break;
805 icon_to_draw = &scaled_icon_control_;
806 break;
808 icon_to_draw = &scaled_icon_condition_;
809 break;
811 icon_to_draw = &scaled_icon_decorator_;
812 break;
814 icon_to_draw = &scaled_icon_tree_;
815 break;
816 default:
817 // No icon for other types
818 break;
819 }
820 }
821
822 // Draw the icon if we have one
823 if (icon_to_draw && icon_to_draw->IsOk()) {
824 int icon_width = icon_to_draw->GetWidth();
825
826 // Calculate icon center position in world coordinates (slightly below center)
827 int icon_center_x = x; // Use node center x
828 int icon_center_y = y + config_.node_height / 2 + 8; // Slightly lower than center
829
830 // Convert center position to screen coordinates
831 wxPoint screen_center = WorldToScreen(wxPoint(icon_center_x, icon_center_y));
832
833 // Calculate top-left corner in screen space (offset by half icon size)
834 int screen_x = screen_center.x - icon_width / 2;
835 int screen_y = screen_center.y - icon_width / 2; // Icons are square
836
837 // Draw pre-scaled bitmap without DC transformation
838 double old_scale_x, old_scale_y;
839 dc.GetUserScale(&old_scale_x, &old_scale_y);
840 wxPoint old_origin = dc.GetDeviceOrigin();
841
842 // Temporarily remove transformations to draw at screen coordinates
843 dc.SetUserScale(1.0, 1.0);
844 dc.SetDeviceOrigin(0, 0);
845
846 dc.DrawBitmap(*icon_to_draw, screen_x, screen_y, true);
847
848 // Restore transformations
849 dc.SetUserScale(old_scale_x, old_scale_y);
850 dc.SetDeviceOrigin(old_origin.x, old_origin.y);
851 }
852}
853
854void TreeVisualization::DrawNodeConnections(wxDC &dc, ITreeNode *node, wxCoord x, wxCoord y) {
855 if (!node->AreChildrenVisible() || node->GetChildCount() == 0)
856 return;
857
858 // Get connection line color from preferences
860 const auto &mainPanelSettings = prefs.GetMainPanelSettings();
861 wxColour connectionColor(mainPanelSettings.connectionLineColor.r, mainPanelSettings.connectionLineColor.g,
862 mainPanelSettings.connectionLineColor.b);
863
864 int total_width = CalculateSubtreeWidth(node);
865 wxCoord child_y = y + config_.node_height + config_.vertical_spacing;
866
867 // Check if this parent is part of the path to selected node (by ID, not pointer)
868 bool parentInPath = path_to_selected_ids_.find(node->GetId()) != path_to_selected_ids_.end();
869
870 // First pass: check if any child is in the path to determine if we need to collect segments
871 bool anyChildInPath = false;
872 if (parentInPath) {
873 for (size_t i = 0; i < node->GetChildCount(); ++i) {
874 ITreeNode *child = node->GetChild(i);
875 if (child && path_to_selected_ids_.find(child->GetId()) != path_to_selected_ids_.end()) {
876 anyChildInPath = true;
877 break;
878 }
879 }
880 }
881
882 // Always draw normal connections first
883 dc.SetPen(wxPen(connectionColor, 2));
884
885 // Draw vertical line from parent
886 dc.DrawLine(x, y + config_.node_height, x, child_y - 10);
887
888 // If this is part of the highlighted path, store segment for later drawing on top
889 if (parentInPath && anyChildInPath) {
890 highlighted_path_segments_.push_back({x, y + config_.node_height, x, child_y - 10});
891 }
892
893 // Draw horizontal distribution line and connections to children
894 wxCoord child_x = x - total_width / 2;
895
896 for (size_t i = 0; i < node->GetChildCount(); ++i) {
897 ITreeNode *child = node->GetChild(i);
898 if (child) {
899 int subtree_width = CalculateSubtreeWidth(child);
900 wxCoord center_x = child_x + subtree_width / 2;
901
902 // Check if this specific child is in the path (by ID, not pointer)
903 bool childInPath = path_to_selected_ids_.find(child->GetId()) != path_to_selected_ids_.end();
904
905 // Draw normal connections
906 dc.SetPen(wxPen(connectionColor, 2));
907
908 // Horizontal line
909 dc.DrawLine(x, child_y - 10, center_x, child_y - 10);
910
911 // Vertical line to child
912 dc.DrawLine(center_x, child_y - 10, center_x, child_y);
913
914 // If part of highlighted path, store segments for later drawing on top
915 if (parentInPath && childInPath) {
916 highlighted_path_segments_.push_back({x, child_y - 10, center_x, child_y - 10});
917 highlighted_path_segments_.push_back({center_x, child_y - 10, center_x, child_y});
918 }
919
920 child_x += subtree_width;
921 }
922 }
923}
924
926 // This function is kept for future use if needed
927 // Currently, collection happens inline in DrawNodeConnections
928}
929
930void TreeVisualization::DrawCollapseArrow(wxDC &dc, ITreeNode *node, wxCoord x, wxCoord y) {
931 if (node->GetChildCount() == 0)
932 return;
933
934 // Draw circular background for better visibility
935 int circle_radius = 8;
936
937 // Position circle on the bottom border of the node
938 wxCoord arrow_x = x;
939 wxCoord arrow_y = y + config_.node_height; // At bottom border
940
941 // Background circle with subtle fill
942 dc.SetBrush(wxBrush(wxColour(70, 70, 70))); // Darker background
943 dc.SetPen(wxPen(wxColour(100, 100, 100), 1)); // Subtle border
944 dc.DrawCircle(arrow_x, arrow_y, circle_radius);
945
946 // Draw the arrow triangle
947 wxPoint triangle[3];
948
949 if (node->AreChildrenVisible()) {
950 // Down arrow (expanded) - larger and better positioned
951 int arrow_size = 5;
952 triangle[0] = {arrow_x - arrow_size, arrow_y - 2};
953 triangle[1] = {arrow_x + arrow_size, arrow_y - 2};
954 triangle[2] = {arrow_x, arrow_y + 3};
955
956 dc.SetPen(wxPen(wxColour(120, 200, 255), 1)); // Light blue for expanded
957 dc.SetBrush(wxBrush(wxColour(120, 200, 255)));
958 } else {
959 // Right arrow (collapsed) - larger and better positioned
960 int arrow_size = 5;
961 triangle[0] = {arrow_x - 2, arrow_y - arrow_size};
962 triangle[1] = {arrow_x - 2, arrow_y + arrow_size};
963 triangle[2] = {arrow_x + 3, arrow_y};
964
965 dc.SetPen(wxPen(wxColour(180, 180, 180), 1)); // Light gray for collapsed
966 dc.SetBrush(wxBrush(wxColour(180, 180, 180)));
967 }
968
969 dc.DrawPolygon(3, triangle);
970}
971
973 // Reset transformation for screen-space drawing
974 dc.SetUserScale(1.0, 1.0);
975 dc.SetDeviceOrigin(0, 0);
976
977 wxSize panel_size = GetSize();
978
979 // Get preferences for debug text customization
981 const auto &btViewSettings = prefs.GetBehaviorTreeViewSettings();
982
983 // Helper lambda to calculate position based on anchor
984 auto calculatePosition = [&panel_size](EmberForge::AppPreferences::TextAnchor anchor, int offsetX,
985 int offsetY) -> wxPoint {
986 switch (anchor) {
988 return wxPoint(offsetX, offsetY);
990 return wxPoint(panel_size.x - offsetX, offsetY);
992 return wxPoint(offsetX, panel_size.y - offsetY);
994 return wxPoint(panel_size.x - offsetX, panel_size.y - offsetY);
995 default:
996 return wxPoint(offsetX, offsetY);
997 }
998 };
999
1000 // Draw Coordinate System Info (Zoom and Pan)
1001 if (btViewSettings.showCoordinateInfo) {
1002 wxColour color(btViewSettings.coordinateInfoColor.r, btViewSettings.coordinateInfoColor.g,
1003 btViewSettings.coordinateInfoColor.b);
1004 dc.SetTextForeground(color);
1005 dc.SetFont(wxFont(btViewSettings.coordinateInfoFontSize, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL,
1006 wxFONTWEIGHT_NORMAL));
1007
1008 wxString zoomText =
1009 wxString::Format("Zoom: %.0f%% | Pan: (%d, %d)", zoom_factor_ * 100, view_offset_.x, view_offset_.y);
1010 wxPoint pos = calculatePosition(btViewSettings.coordinateInfoAnchor, btViewSettings.coordinateInfoX,
1011 btViewSettings.coordinateInfoY);
1012 dc.DrawText(zoomText, pos.x, pos.y);
1013 }
1014
1015 // Draw Selected Node Info
1016 if (btViewSettings.showSelectedNodeInfo && selected_node_) {
1017 wxColour color(btViewSettings.selectedNodeInfoColor.r, btViewSettings.selectedNodeInfoColor.g,
1018 btViewSettings.selectedNodeInfoColor.b);
1019 dc.SetTextForeground(color);
1020 dc.SetFont(wxFont(btViewSettings.selectedNodeInfoFontSize, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL,
1021 wxFONTWEIGHT_NORMAL));
1022
1023 EmberCore::String selectedText =
1024 "Selected: " + selected_node_->GetName() + " [" + selected_node_->GetTypeString() + "]";
1025 wxPoint pos = calculatePosition(btViewSettings.selectedNodeInfoAnchor, btViewSettings.selectedNodeInfoX,
1026 btViewSettings.selectedNodeInfoY);
1027 dc.DrawText(selectedText, pos.x, pos.y);
1028 }
1029
1030 // Draw Tree Statistics Info
1031 if (btViewSettings.showTreeInfo && tree_ && tree_->HasRootNode()) {
1032 wxColour color(btViewSettings.treeInfoColor.r, btViewSettings.treeInfoColor.g, btViewSettings.treeInfoColor.b);
1033 dc.SetTextForeground(color);
1034 dc.SetFont(
1035 wxFont(btViewSettings.treeInfoFontSize, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
1036
1037 wxString statsText =
1038 wxString::Format("Tree: %lu nodes total", static_cast<unsigned long>(tree_->GetNodeCount()));
1039 wxPoint pos =
1040 calculatePosition(btViewSettings.treeInfoAnchor, btViewSettings.treeInfoX, btViewSettings.treeInfoY);
1041 dc.DrawText(statsText, pos.x, pos.y);
1042 }
1043
1044 // Draw FPS Display
1045 if (btViewSettings.showFPS) {
1046 wxColour color(btViewSettings.fpsColor.r, btViewSettings.fpsColor.g, btViewSettings.fpsColor.b);
1047 dc.SetTextForeground(color);
1048 dc.SetFont(wxFont(btViewSettings.fpsFontSize, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD));
1049
1051 float fps = monitor.GetCurrentFPS();
1052 wxString fpsText = wxString::Format("FPS: %.1f", fps);
1053 wxPoint pos = calculatePosition(btViewSettings.fpsAnchor, btViewSettings.fpsX, btViewSettings.fpsY);
1054 dc.DrawText(fpsText, pos.x, pos.y);
1055 }
1056
1057 // Draw Controls Help Text
1058 if (btViewSettings.showControlsHelp) {
1059 wxColour color(btViewSettings.controlsHelpColor.r, btViewSettings.controlsHelpColor.g,
1060 btViewSettings.controlsHelpColor.b);
1061 dc.SetTextForeground(color);
1062 dc.SetFont(
1063 wxFont(btViewSettings.controlsHelpFontSize, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
1064
1065 EmberCore::String helpText =
1066 "Controls: Left-click=Select | Double-click=Center View | Middle-drag=Pan | Wheel=Zoom | " +
1067 btViewSettings.resetViewHotkey + "=Reset View | " + btViewSettings.centerOnNodeHotkey +
1068 "=Expand/Collapse | " + btViewSettings.deleteNodeHotkey + "=Delete Node";
1069 wxPoint pos = calculatePosition(btViewSettings.controlsHelpAnchor, btViewSettings.controlsHelpX,
1070 btViewSettings.controlsHelpY);
1071 dc.DrawText(helpText, pos.x, pos.y);
1072 }
1073}
1074
1075// Utility Methods
1077 if (!node)
1078 return 0;
1079
1080 // Check cache first - HUGE performance win for large trees
1081 auto it = width_cache_.find(node);
1082 if (it != width_cache_.end()) {
1083 return it->second;
1084 }
1085
1086 int width;
1087 if (!node->AreChildrenVisible() || node->GetChildCount() == 0) {
1088 width = config_.node_width + config_.horizontal_spacing;
1089 } else {
1090 int total_width = 0;
1091 for (size_t i = 0; i < node->GetChildCount(); ++i) {
1092 ITreeNode *child = node->GetChild(i);
1093 if (child) {
1094 total_width += CalculateSubtreeWidth(child);
1095 }
1096 }
1097 width = std::max(total_width, config_.node_width + config_.horizontal_spacing);
1098 }
1099
1100 // Cache the result
1101 width_cache_[node] = width;
1102 return width;
1103}
1104
1106 // Return world coordinates for root node position
1107 // This gets transformed by the zoom/pan in OnPaint
1108 wxCoord x = 0; // Center horizontally in world space
1109 wxCoord y = 50; // Start near top in world space
1110 return {x, y};
1111}
1112
1113ITreeNode *TreeVisualization::FindNodeAtPosition(ITreeNode *node, wxPoint node_pos, wxPoint target_pos, int level) {
1114 if (!node)
1115 return nullptr;
1116
1117 // Check if target is within this node's bounds (all in world coordinates)
1118 wxRect node_rect(node_pos.x - config_.node_width / 2, node_pos.y, config_.node_width, config_.node_height);
1119
1120 if (node_rect.Contains(target_pos)) {
1121 return node;
1122 }
1123
1124 // Check children if visible
1125 if (node->AreChildrenVisible() && node->GetChildCount() > 0) {
1126 int total_width = CalculateSubtreeWidth(node);
1127 wxCoord child_x = node_pos.x - total_width / 2;
1128 wxCoord child_y = node_pos.y + config_.node_height + config_.vertical_spacing;
1129
1130 for (size_t i = 0; i < node->GetChildCount(); ++i) {
1131 ITreeNode *child = node->GetChild(i);
1132 if (child) {
1133 int subtree_width = CalculateSubtreeWidth(child);
1134 wxCoord center_x = child_x + subtree_width / 2;
1135
1136 ITreeNode *found = FindNodeAtPosition(child, {center_x, child_y}, target_pos, level + 1);
1137 if (found) {
1138 return found;
1139 }
1140
1141 child_x += subtree_width;
1142 }
1143 }
1144 }
1145
1146 return nullptr;
1147}
1148
1150 if (!target_node || !tree_ || !tree_->HasRootNode())
1151 return {-1, -1};
1152
1153 // Recursive function to find the world position of a node
1154 std::function<wxPoint(ITreeNode *, wxPoint, int)> findPosition = [&](ITreeNode *node, wxPoint node_pos,
1155 int level) -> wxPoint {
1156 if (!node)
1157 return {-1, -1};
1158
1159 // Check if this is the target node (use hybrid comparison like in DrawNodeBox)
1160 bool isTargetNode = (node == target_node);
1161 if (!isTargetNode && target_node && node->GetId() == target_node->GetId() &&
1162 node->GetName() == target_node->GetName()) {
1163 isTargetNode = true;
1164 }
1165
1166 if (isTargetNode) {
1167 return node_pos;
1168 }
1169
1170 // Search in children if visible
1171 if (node->AreChildrenVisible() && node->GetChildCount() > 0) {
1172 int total_width = CalculateSubtreeWidth(node);
1173 wxCoord child_x = node_pos.x - total_width / 2;
1174 wxCoord child_y = node_pos.y + config_.node_height + config_.vertical_spacing;
1175
1176 for (size_t i = 0; i < node->GetChildCount(); ++i) {
1177 ITreeNode *child = node->GetChild(i);
1178 if (child) {
1179 int subtree_width = CalculateSubtreeWidth(child);
1180 wxCoord center_x = child_x + subtree_width / 2;
1181
1182 wxPoint found = findPosition(child, {center_x, child_y}, level + 1);
1183 if (found.x != -1 && found.y != -1) {
1184 return found;
1185 }
1186
1187 child_x += subtree_width;
1188 }
1189 }
1190 }
1191
1192 return {-1, -1};
1193 };
1194
1195 wxPoint root_pos = CalculateRootPosition();
1196 return findPosition(tree_->GetRootNode(), root_pos, 0);
1197}
1198
1199bool TreeVisualization::IsPointInViewport(wxCoord x, wxCoord y) const {
1200 wxSize panel_size = GetSize();
1201 return x >= -100 && x <= panel_size.x + 100 && y >= -100 && y <= panel_size.y + 100;
1202}
1203
1204wxPoint TreeVisualization::ScreenToWorld(const wxPoint &screen_pos) const {
1205 return {static_cast<int>((screen_pos.x - view_offset_.x) / zoom_factor_),
1206 static_cast<int>((screen_pos.y - view_offset_.y) / zoom_factor_)};
1207}
1208
1209wxPoint TreeVisualization::WorldToScreen(const wxPoint &world_pos) const {
1210 return {static_cast<int>(world_pos.x * zoom_factor_ + view_offset_.x),
1211 static_cast<int>(world_pos.y * zoom_factor_ + view_offset_.y)};
1212}
1213
1215 // Calculate the visible viewport bounds in world coordinates
1216 wxSize panel_size = GetSize();
1217 wxPoint topLeft = ScreenToWorld({0, 0});
1218 wxPoint bottomRight = ScreenToWorld({panel_size.x, panel_size.y});
1219
1220 return wxRect(topLeft.x, topLeft.y, bottomRight.x - topLeft.x, bottomRight.y - topLeft.y);
1221}
1222
1223bool TreeVisualization::IsNodeInViewport(wxCoord x, wxCoord y) const {
1224 // Get viewport bounds in world coordinates
1225 wxRect viewport = GetViewportBounds();
1226
1227 // Calculate node bounds in world coordinates
1228 wxRect nodeBounds(x - config_.node_width / 2, y, config_.node_width, config_.node_height);
1229
1230 // Add margin for smoother culling (render nodes slightly outside viewport)
1231 // Scale margin inversely with zoom: when zoomed out, we need larger margin in world space
1232 // This keeps the margin consistent in screen space regardless of zoom level
1233 // Use configurable margin from preferences
1234 int margin = static_cast<int>(viewport_culling_margin_ / zoom_factor_);
1235 viewport.Inflate(margin);
1236
1237 // Check if node bounds intersect with viewport
1238 return viewport.Intersects(nodeBounds);
1239}
1240
1243 const auto &btViewSettings = prefs.GetBehaviorTreeViewSettings();
1244 const auto &mainPanelSettings = prefs.GetMainPanelSettings();
1245 const auto &perfSettings = prefs.GetPerformanceSettings();
1246
1247 // Load zoom/pan preferences
1248 zoom_step_ = btViewSettings.zoomStepSize;
1249 mouse_wheel_sensitivity_ = btViewSettings.mouseWheelSensitivity;
1250 pan_sensitivity_ = btViewSettings.panSensitivity;
1251 zoom_follows_cursor_ = btViewSettings.zoomFollowsCursor;
1252
1253 // Load pan key
1254 pan_key_code_ = ParseHotkeyString(btViewSettings.panKey);
1255
1256 // Load smooth panning preferences
1257 enable_smooth_panning_ = btViewSettings.enableSmoothPanning;
1258 pan_smoothness_ = btViewSettings.panSmoothness;
1259 pan_step_size_ = btViewSettings.panStepSize;
1260
1261 // Load grid preferences
1262 show_grid_ = mainPanelSettings.showGrid;
1263 grid_size_ = mainPanelSettings.gridSize;
1264 config_.grid_size = mainPanelSettings.gridSize;
1265 config_.grid_color = wxColour(mainPanelSettings.gridLineColor.r, mainPanelSettings.gridLineColor.g,
1266 mainPanelSettings.gridLineColor.b);
1267
1268 // Load viewport culling preferences
1269 enable_viewport_culling_ = perfSettings.enableViewportCulling;
1270 viewport_culling_margin_ = perfSettings.viewportCullingMargin;
1271
1272 wxString panType = (pan_key_code_ == -1) ? wxString::Format("mouse_button=%d", pan_mouse_button_)
1273 : wxString::Format("key_code=%d", pan_key_code_);
1274
1275 LOG_INFO(
1276 "TreeVisualization",
1277 wxString::Format("Loaded preferences: zoom_step=%.2f, wheel_sens=%.2f, pan_sens=%.2f, pan=%s, "
1278 "zoom_follows_cursor=%s, show_grid=%s, grid_size=%d, viewport_culling=%s, culling_margin=%d",
1280 zoom_follows_cursor_ ? "true" : "false", show_grid_ ? "true" : "false", grid_size_,
1282 .ToStdString());
1283}
1284
1285int TreeVisualization::ParseHotkeyString(const std::string &hotkey) {
1286 // Check for mouse buttons first (return -1 to indicate mouse button, not keyboard)
1287 if (hotkey == "Left Mouse Button") {
1289 return -1;
1290 }
1291 if (hotkey == "Middle Mouse Button") {
1293 return -1;
1294 }
1295 if (hotkey == "Right Mouse Button") {
1297 return -1;
1298 }
1299
1300 // Simple key name to key code conversion
1301 // Handle common keys that users might want to use for panning
1302 if (hotkey == "Space")
1303 return WXK_SPACE;
1304 if (hotkey == "Shift")
1305 return WXK_SHIFT;
1306 if (hotkey == "Ctrl")
1307 return WXK_CONTROL;
1308 if (hotkey == "Alt")
1309 return WXK_ALT;
1310 if (hotkey == "Tab")
1311 return WXK_TAB;
1312 if (hotkey == "Z")
1313 return 'Z';
1314 if (hotkey == "X")
1315 return 'X';
1316 if (hotkey == "C")
1317 return 'C';
1318 if (hotkey == "V")
1319 return 'V';
1320
1321 // For single character keys
1322 if (hotkey.length() == 1) {
1323 char c = hotkey[0];
1324 if (c >= 'A' && c <= 'Z')
1325 return c;
1326 if (c >= 'a' && c <= 'z')
1327 return toupper(c);
1328 }
1329
1330 // Default to Middle Mouse Button if unrecognized
1332 return -1;
1333}
1334
1335void TreeVisualization::OnKeyUp(wxKeyEvent &event) {
1336 int keyCode = event.GetKeyCode();
1337
1338 // Check if this is the pan key being released
1339 if (keyCode == pan_key_code_) {
1340 pan_key_held_ = false;
1341 is_panning_ = false;
1342 return;
1343 }
1344
1345 event.Skip();
1346}
1347
1348} // namespace EmberCore
BehaviorTreeProjectDialog::OnProjectNameChanged BehaviorTreeProjectDialog::OnRemoveFiles wxEND_EVENT_TABLE() BehaviorTreeProjectDialog
#define LOG_INFO(category, message)
Definition Logger.h:114
#define PERF_TIME_END(name)
#define PERF_TIME_BEGIN(name)
#define PERF_END_FRAME()
#define PERF_BEGIN_FRAME()
Centralized resource path management for EmberForge.
Abstract interface for tree nodes that can be visualized.
Definition ITreeNode.h:31
virtual bool IsUnimplementedReference() const
Check if this node references an unimplemented tree.
Definition ITreeNode.h:106
virtual bool IsSubTreeReference() const
Check if this node is a SubTree reference.
Definition ITreeNode.h:100
virtual size_t GetId() const =0
virtual size_t GetChildCount() const =0
virtual NodeType GetType() const =0
virtual ITreeNode * GetParent() const =0
virtual bool AreChildrenVisible() const =0
virtual const String & GetName() const =0
virtual ITreeNode * GetChild(size_t index) const =0
Tree visualization panel that renders behavior trees in a grid-based layout.
void DrawCollapseArrow(wxDC &dc, ITreeNode *node, wxCoord x, wxCoord y)
void OnMouseLeftDClick(wxMouseEvent &event)
void OnSize(wxSizeEvent &event)
ITreeNode * FindNodeAtPosition(ITreeNode *node, wxPoint node_pos, wxPoint target_pos, int level=0)
wxPoint ScreenToWorld(const wxPoint &screen_pos) const
std::shared_ptr< ITreeNode > selected_node_
bool IsNodeInViewport(wxCoord x, wxCoord y) const
void DrawNodeText(wxDC &dc, ITreeNode *node, wxCoord x, wxCoord y)
void DrawNodeConnections(wxDC &dc, ITreeNode *node, wxCoord x, wxCoord y)
wxPoint WorldToScreen(const wxPoint &world_pos) const
void SetBehaviorTree(std::shared_ptr< ITreeStructure > tree)
void OnMouseWheel(wxMouseEvent &event)
void DrawNodeBox(wxDC &dc, ITreeNode *node, wxCoord x, wxCoord y)
void SetSelectedNode(ITreeNode *node)
void OnMouseMotion(wxMouseEvent &event)
int CalculateSubtreeWidth(ITreeNode *node)
std::vector< LineSegment > highlighted_path_segments_
void OnMouseLeftDown(wxMouseEvent &event)
void CollectHighlightedConnections(ITreeNode *node, wxCoord x, wxCoord y)
void DrawNode(wxDC &dc, ITreeNode *node, wxCoord x, wxCoord y, int level, bool draw_children=true)
void OnMouseMiddleUp(wxMouseEvent &event)
std::map< ITreeNode *, int > width_cache_
bool IsPointInViewport(wxCoord x, wxCoord y) const
NodeSelectionCallback m_nodeSelectionCallback
int ParseHotkeyString(const std::string &hotkey)
void OnPaint(wxPaintEvent &event)
void CenterOnNode(ITreeNode *node)
std::shared_ptr< ITreeStructure > tree_
void OnMouseRightDown(wxMouseEvent &event)
void OnKeyUp(wxKeyEvent &event)
std::vector< CollapseArrowInfo > collapse_arrows_to_draw_
void OnMouseMiddleDown(wxMouseEvent &event)
void OnKeyDown(wxKeyEvent &event)
wxPoint FindNodeWorldPosition(ITreeNode *target_node)
static AppPreferencesManager & GetInstance()
BehaviorTreeViewSettings & GetBehaviorTreeViewSettings()
MainPanelSettings & GetMainPanelSettings()
TextAnchor
Text anchor position for debug info overlay.
System performance monitoring class.
void RecordMetric(const std::string &name, float value, const std::string &unit="")
static PerformanceMonitor & GetInstance()
static wxString GetDir(const wxString &relativeDir)
Get the full path to a resource directory.
Main types header for EmberCore.
std::string String
Framework-agnostic string type.
Definition String.h:14
wxBEGIN_EVENT_TABLE(TreeVisualization, wxPanel) EVT_PAINT(TreeVisualization