feat: add C++ ImGui functions for core UI and visualization
Funciones C++/ImGui para dashboards (grid, panel, docking, sidebar, tabs), visualizaciones (candlestick, gauge, histogram, pie, sparkline, heatmap, scatter, line, bar, surface3d, kpi, table), grafos (force layout, renderer, viewport, spatial hash, types) y utilidades (time series buffer, tracy zones, memory/fps overlay, plot theme). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
#include "viz/candlestick.h"
|
||||
#include "imgui.h"
|
||||
#include "implot.h"
|
||||
|
||||
void candlestick(const char* title, const double* dates, const double* opens,
|
||||
const double* closes, const double* lows, const double* highs,
|
||||
int count, float width_percent, bool tooltip) {
|
||||
if (count <= 0) return;
|
||||
|
||||
// Compute half-width of each candle body in data coordinates.
|
||||
// Use spacing between consecutive dates when count > 1, else fallback to 0.5.
|
||||
double spacing = (count > 1) ? (dates[1] - dates[0]) : 1.0;
|
||||
double half_w = spacing * (double)width_percent * 0.5;
|
||||
|
||||
ImPlot::SetupAxes("Date", "Price", ImPlotAxisFlags_None, ImPlotAxisFlags_AutoFit);
|
||||
ImPlot::SetupAxisScale(ImAxis_X1, ImPlotScale_Time);
|
||||
|
||||
// Auto-fit X axis to the data range with a small margin.
|
||||
ImPlot::SetupAxisLimits(ImAxis_X1,
|
||||
dates[0] - spacing,
|
||||
dates[count - 1] + spacing,
|
||||
ImGuiCond_Always);
|
||||
|
||||
if (ImPlot::BeginPlot(title, ImVec2(-1, 0))) {
|
||||
ImDrawList* draw = ImPlot::GetPlotDrawList();
|
||||
|
||||
const ImU32 col_bull = IM_COL32(0, 200, 80, 255); // green — close >= open
|
||||
const ImU32 col_bear = IM_COL32(220, 50, 50, 255); // red — close < open
|
||||
|
||||
int hovered_idx = -1;
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
double x = dates[i];
|
||||
double open = opens[i];
|
||||
double close = closes[i];
|
||||
double low = lows[i];
|
||||
double high = highs[i];
|
||||
|
||||
bool bullish = (close >= open);
|
||||
ImU32 col = bullish ? col_bull : col_bear;
|
||||
|
||||
// Convert data coordinates to screen pixels.
|
||||
ImVec2 body_tl = ImPlot::PlotToPixels(x - half_w, bullish ? close : open);
|
||||
ImVec2 body_br = ImPlot::PlotToPixels(x + half_w, bullish ? open : close);
|
||||
ImVec2 wick_hi = ImPlot::PlotToPixels(x, high);
|
||||
ImVec2 wick_lo = ImPlot::PlotToPixels(x, low);
|
||||
float cx = (body_tl.x + body_br.x) * 0.5f;
|
||||
|
||||
// Wick (high-low vertical line).
|
||||
draw->AddLine(ImVec2(cx, wick_hi.y), ImVec2(cx, wick_lo.y), col, 1.5f);
|
||||
|
||||
// Body rectangle (open-close).
|
||||
// Ensure at least 1px height so flat candles are visible.
|
||||
if (body_br.y <= body_tl.y + 1.0f) body_br.y = body_tl.y + 1.0f;
|
||||
draw->AddRectFilled(body_tl, body_br, col);
|
||||
draw->AddRect(body_tl, body_br, col);
|
||||
|
||||
// Track hovered candle for tooltip.
|
||||
if (tooltip && ImPlot::IsPlotHovered()) {
|
||||
ImVec2 mouse = ImGui::GetMousePos();
|
||||
if (mouse.x >= body_tl.x - 4 && mouse.x <= body_br.x + 4 &&
|
||||
mouse.y >= wick_hi.y - 4 && mouse.y <= wick_lo.y + 4) {
|
||||
hovered_idx = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tooltip for the hovered candle.
|
||||
if (tooltip && hovered_idx >= 0) {
|
||||
int i = hovered_idx;
|
||||
ImGui::BeginTooltip();
|
||||
ImGui::Text("O: %.4f", opens[i]);
|
||||
ImGui::Text("H: %.4f", highs[i]);
|
||||
ImGui::Text("L: %.4f", lows[i]);
|
||||
ImGui::Text("C: %.4f", closes[i]);
|
||||
ImGui::EndTooltip();
|
||||
}
|
||||
|
||||
ImPlot::EndPlot();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
// Renders an OHLC candlestick chart using ImPlot custom rendering.
|
||||
// Call within an ImGui frame (inside fn::run_app render callback).
|
||||
// Green candles when close >= open, red when close < open.
|
||||
// width_percent controls candle body width as a fraction of inter-candle spacing.
|
||||
void candlestick(const char* title, const double* dates, const double* opens,
|
||||
const double* closes, const double* lows, const double* highs,
|
||||
int count, float width_percent = 0.25f, bool tooltip = true);
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
name: candlestick
|
||||
kind: component
|
||||
lang: cpp
|
||||
domain: viz
|
||||
version: "1.0.0"
|
||||
purity: pure
|
||||
signature: "void candlestick(const char* title, const double* dates, const double* opens, const double* closes, const double* lows, const double* highs, int count, float width_percent = 0.25f, bool tooltip = true)"
|
||||
description: "Renderiza un grafico de velas OHLC usando ImPlot custom rendering. Verde para velas alcistas (close >= open), rojo para bajistas."
|
||||
tags: [implot, chart, visualization, gpu, candlestick, ohlc, finance]
|
||||
uses_functions: []
|
||||
uses_types: []
|
||||
returns: []
|
||||
returns_optional: false
|
||||
error_type: ""
|
||||
imports: [implot, imgui]
|
||||
tested: false
|
||||
tests: []
|
||||
test_file_path: ""
|
||||
file_path: "cpp/functions/viz/candlestick.cpp"
|
||||
framework: imgui
|
||||
params:
|
||||
- name: title
|
||||
desc: "Titulo del grafico, se muestra como header del plot"
|
||||
- name: dates
|
||||
desc: "Array de timestamps Unix o indices numericos del eje X, uno por vela"
|
||||
- name: opens
|
||||
desc: "Array de precios de apertura, uno por vela"
|
||||
- name: closes
|
||||
desc: "Array de precios de cierre, uno por vela"
|
||||
- name: lows
|
||||
desc: "Array de precios minimos (punta inferior del wick), uno por vela"
|
||||
- name: highs
|
||||
desc: "Array de precios maximos (punta superior del wick), uno por vela"
|
||||
- name: count
|
||||
desc: "Numero de velas (longitud de todos los arrays)"
|
||||
- name: width_percent
|
||||
desc: "Ancho del body de cada vela como fraccion del espacio entre puntos consecutivos (0.0-1.0, default 0.25)"
|
||||
- name: tooltip
|
||||
desc: "Si true, muestra tooltip con valores O/H/L/C al hacer hover sobre una vela"
|
||||
output: "Renderiza el grafico de velas OHLC en el frame ImGui actual, sin retornar valor"
|
||||
---
|
||||
|
||||
# candlestick
|
||||
|
||||
Grafico de velas OHLC completo usando custom rendering de ImPlot. Dibuja body (open-close) y wicks (high-low) por vela usando `ImPlot::GetPlotDrawList()` y `ImPlot::PlotToPixels()` para conversion de coordenadas.
|
||||
|
||||
Debe llamarse dentro del render callback de `fn::run_app` (o cualquier contexto con un frame ImGui activo). El eje X se configura con `ImPlotScale_Time` para timestamps Unix.
|
||||
|
||||
Solo tiene overload `double` porque los datos financieros requieren doble precision.
|
||||
|
||||
## Ejemplo
|
||||
|
||||
```cpp
|
||||
// arrays de datos financieros (timestamps Unix, precios)
|
||||
candlestick("BTC/USD", dates, opens, closes, lows, highs, 90);
|
||||
|
||||
// sin tooltip, velas mas anchas
|
||||
candlestick("ETH/USD", dates, opens, closes, lows, highs, 30, 0.6f, false);
|
||||
```
|
||||
|
||||
## Notas
|
||||
|
||||
- El ancho de cada vela se calcula como `(dates[1] - dates[0]) * width_percent * 0.5` en cada lado. Asume spacing uniforme entre velas.
|
||||
- Para un solo punto (`count == 1`) el spacing por defecto es 1.0.
|
||||
- La deteccion de hover usa un margen de 4px alrededor del area cuerpo+wick para facilitar la interaccion.
|
||||
- El eje X usa `ImPlotScale_Time` — si los datos son indices numericos simples (0, 1, 2...) en lugar de timestamps, pasar `ImPlotAxisFlags_NoDecorations` o cambiar `SetupAxisScale`.
|
||||
@@ -0,0 +1,94 @@
|
||||
#include "viz/gauge.h"
|
||||
#include "imgui.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
|
||||
#ifndef M_PI
|
||||
#define M_PI 3.14159265358979323846f
|
||||
#endif
|
||||
|
||||
void gauge(const char* label, float value, float min_val, float max_val, float radius) {
|
||||
ImDrawList* draw_list = ImGui::GetWindowDrawList();
|
||||
ImVec2 pos = ImGui::GetCursorScreenPos();
|
||||
|
||||
// Reserve space: diameter + label line
|
||||
float diameter = radius * 2.0f;
|
||||
ImGui::Dummy(ImVec2(diameter, diameter + ImGui::GetTextLineHeightWithSpacing()));
|
||||
|
||||
ImVec2 center = ImVec2(pos.x + radius, pos.y + radius);
|
||||
|
||||
// Arc spans 240 degrees: from 150deg to 390deg (i.e. 150 to 30 going clockwise)
|
||||
// In screen space Y is down, so angles go clockwise.
|
||||
// Start angle: 150 degrees = bottom-left, End angle: 390 = 30 degrees = bottom-right
|
||||
const float angle_start = (150.0f * (float)M_PI) / 180.0f;
|
||||
const float angle_end = (390.0f * (float)M_PI) / 180.0f;
|
||||
const int num_segments = 64;
|
||||
|
||||
// Background arc (dark gray)
|
||||
ImU32 bg_color = IM_COL32(60, 60, 60, 220);
|
||||
for (int i = 0; i < num_segments; i++) {
|
||||
float a0 = angle_start + (angle_end - angle_start) * ((float)i / num_segments);
|
||||
float a1 = angle_start + (angle_end - angle_start) * ((float)(i + 1) / num_segments);
|
||||
draw_list->AddLine(
|
||||
ImVec2(center.x + cosf(a0) * radius, center.y + sinf(a0) * radius),
|
||||
ImVec2(center.x + cosf(a1) * radius, center.y + sinf(a1) * radius),
|
||||
bg_color, 6.0f);
|
||||
}
|
||||
|
||||
// Normalize value to [0, 1]
|
||||
float t = 0.0f;
|
||||
if (max_val > min_val) {
|
||||
t = (value - min_val) / (max_val - min_val);
|
||||
if (t < 0.0f) t = 0.0f;
|
||||
if (t > 1.0f) t = 1.0f;
|
||||
}
|
||||
|
||||
// Color: green (t=0) -> yellow (t=0.5) -> red (t=1)
|
||||
float r, g, b;
|
||||
if (t < 0.5f) {
|
||||
float s = t * 2.0f;
|
||||
r = (unsigned char)(s * 255);
|
||||
g = 200;
|
||||
b = 0;
|
||||
} else {
|
||||
float s = (t - 0.5f) * 2.0f;
|
||||
r = 220;
|
||||
g = (unsigned char)((1.0f - s) * 200);
|
||||
b = 0;
|
||||
}
|
||||
ImU32 value_color = IM_COL32((int)r, (int)g, (int)b, 255);
|
||||
|
||||
// Value arc
|
||||
float angle_value = angle_start + (angle_end - angle_start) * t;
|
||||
int value_segments = (int)(num_segments * t);
|
||||
for (int i = 0; i < value_segments; i++) {
|
||||
float a0 = angle_start + (angle_end - angle_start) * ((float)i / num_segments);
|
||||
float a1 = angle_start + (angle_end - angle_start) * ((float)(i + 1) / num_segments);
|
||||
draw_list->AddLine(
|
||||
ImVec2(center.x + cosf(a0) * radius, center.y + sinf(a0) * radius),
|
||||
ImVec2(center.x + cosf(a1) * radius, center.y + sinf(a1) * radius),
|
||||
value_color, 6.0f);
|
||||
}
|
||||
|
||||
// Needle: line from center to arc at current angle
|
||||
float needle_len = radius * 0.75f;
|
||||
ImVec2 needle_tip = ImVec2(
|
||||
center.x + cosf(angle_value) * needle_len,
|
||||
center.y + sinf(angle_value) * needle_len);
|
||||
draw_list->AddLine(center, needle_tip, IM_COL32(255, 255, 255, 240), 2.0f);
|
||||
draw_list->AddCircleFilled(center, 4.0f, IM_COL32(255, 255, 255, 200));
|
||||
|
||||
// Value text centered
|
||||
char val_buf[32];
|
||||
snprintf(val_buf, sizeof(val_buf), "%.1f", value);
|
||||
ImVec2 val_size = ImGui::CalcTextSize(val_buf);
|
||||
draw_list->AddText(
|
||||
ImVec2(center.x - val_size.x * 0.5f, center.y + radius * 0.35f),
|
||||
IM_COL32(230, 230, 230, 255), val_buf);
|
||||
|
||||
// Label below value
|
||||
ImVec2 label_size = ImGui::CalcTextSize(label);
|
||||
draw_list->AddText(
|
||||
ImVec2(center.x - label_size.x * 0.5f, center.y + radius * 0.35f + val_size.y + 2.0f),
|
||||
IM_COL32(180, 180, 180, 200), label);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
// Renders a circular gauge/speedometer indicator using ImGui draw primitives.
|
||||
// Call within an ImGui frame.
|
||||
// color is interpolated green->yellow->red based on normalized value.
|
||||
void gauge(const char* label, float value, float min_val, float max_val, float radius = 60.0f);
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
name: gauge
|
||||
kind: component
|
||||
lang: cpp
|
||||
domain: viz
|
||||
version: "1.0.0"
|
||||
purity: pure
|
||||
signature: "void gauge(const char* label, float value, float min_val, float max_val, float radius = 60.0f)"
|
||||
description: "Renderiza un indicador circular tipo gauge/velocimetro usando ImGui draw primitives"
|
||||
tags: [imgui, visualization, gauge, kpi, dashboard]
|
||||
uses_functions: []
|
||||
uses_types: []
|
||||
returns: []
|
||||
returns_optional: false
|
||||
error_type: ""
|
||||
imports: [imgui]
|
||||
tested: false
|
||||
tests: []
|
||||
test_file_path: ""
|
||||
file_path: "cpp/functions/viz/gauge.cpp"
|
||||
framework: imgui
|
||||
params:
|
||||
- name: label
|
||||
desc: "Etiqueta del gauge, se muestra centrada debajo del valor numerico"
|
||||
- name: value
|
||||
desc: "Valor actual a mostrar en el gauge"
|
||||
- name: min_val
|
||||
desc: "Valor minimo de la escala (extremo izquierdo del arco)"
|
||||
- name: max_val
|
||||
desc: "Valor maximo de la escala (extremo derecho del arco)"
|
||||
- name: radius
|
||||
desc: "Radio del gauge en pixels (default 60.0)"
|
||||
output: "Renderiza el gauge en el frame ImGui actual, reservando espacio con ImGui::Dummy"
|
||||
---
|
||||
|
||||
# gauge
|
||||
|
||||
Indicador circular tipo gauge/velocimetro construido sobre ImGui draw primitives. No requiere ImPlot.
|
||||
|
||||
El arco ocupa 240 grados (de 150deg a 390deg en sentido horario). El color del arco de valor interpolado de verde (minimo) a amarillo (mitad) a rojo (maximo). Una aguja blanca apunta al valor actual.
|
||||
|
||||
Debe llamarse dentro del render callback de `fn::run_app` (o cualquier contexto con un frame ImGui activo).
|
||||
|
||||
## Ejemplo
|
||||
|
||||
```cpp
|
||||
// KPI card con gauge de temperatura
|
||||
gauge("CPU Temp", 72.5f, 0.0f, 100.0f, 50.0f);
|
||||
|
||||
// Gauge grande para dashboard principal
|
||||
gauge("Velocidad", 3200.0f, 0.0f, 5000.0f, 80.0f);
|
||||
```
|
||||
|
||||
## Notas
|
||||
|
||||
- El arco de fondo es gris oscuro (IM_COL32(60,60,60,220)), 6px de grosor.
|
||||
- La aguja tiene longitud del 75% del radio para evitar solapar el arco.
|
||||
- Usa solo `float`; no ofrece overload `double` porque ImGui DrawList trabaja en coordenadas de pantalla (float).
|
||||
- El espacio reservado es `diameter x (diameter + line_height)` para incluir la etiqueta.
|
||||
@@ -0,0 +1,353 @@
|
||||
#include "viz/graph_force_layout.h"
|
||||
#include "viz/graph_types.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <algorithm>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Quadtree for Barnes-Hut approximation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
struct QuadNode {
|
||||
float cx, cy; // center of mass
|
||||
float mass; // total mass (node count in subtree)
|
||||
float x0, y0; // bounding box min
|
||||
float x1, y1; // bounding box max
|
||||
int children[4]; // NW=0, NE=1, SW=2, SE=3 (-1 = empty)
|
||||
int body; // node index if leaf (-1 if internal)
|
||||
};
|
||||
|
||||
static constexpr int MAX_QUAD_NODES = 1 << 20; // supports graphs up to ~1M nodes
|
||||
static QuadNode quad_pool[MAX_QUAD_NODES];
|
||||
static int quad_count = 0;
|
||||
|
||||
static int quad_new(float x0, float y0, float x1, float y1) {
|
||||
if (quad_count >= MAX_QUAD_NODES) return -1;
|
||||
int idx = quad_count++;
|
||||
QuadNode& q = quad_pool[idx];
|
||||
q.cx = 0; q.cy = 0; q.mass = 0;
|
||||
q.x0 = x0; q.y0 = y0; q.x1 = x1; q.y1 = y1;
|
||||
q.children[0] = q.children[1] = q.children[2] = q.children[3] = -1;
|
||||
q.body = -1;
|
||||
return idx;
|
||||
}
|
||||
|
||||
// Determine quadrant index for point (px,py) relative to cell midpoint.
|
||||
// 0=NW, 1=NE, 2=SW, 3=SE
|
||||
static int quad_child_idx(const QuadNode& q, float px, float py) {
|
||||
float mx = (q.x0 + q.x1) * 0.5f;
|
||||
float my = (q.y0 + q.y1) * 0.5f;
|
||||
int xi = (px >= mx) ? 1 : 0;
|
||||
int yi = (py >= my) ? 2 : 0;
|
||||
return xi | yi;
|
||||
}
|
||||
|
||||
// Subdivide cell qi into four children.
|
||||
static void quad_subdivide(int qi) {
|
||||
QuadNode& q = quad_pool[qi];
|
||||
float mx = (q.x0 + q.x1) * 0.5f;
|
||||
float my = (q.y0 + q.y1) * 0.5f;
|
||||
// NW
|
||||
quad_pool[qi].children[0] = quad_new(q.x0, q.y0, mx, my);
|
||||
// NE
|
||||
quad_pool[qi].children[1] = quad_new(mx, q.y0, q.x1, my);
|
||||
// SW
|
||||
quad_pool[qi].children[2] = quad_new(q.x0, my, mx, q.y1);
|
||||
// SE
|
||||
quad_pool[qi].children[3] = quad_new(mx, my, q.x1, q.y1);
|
||||
}
|
||||
|
||||
// Insert body (node_idx at position nx,ny with mass nmass) into cell qi.
|
||||
// Uses iterative descent to avoid stack overflow on deep trees.
|
||||
static void quad_insert(int root, int node_idx, float nx, float ny, float nmass) {
|
||||
int qi = root;
|
||||
while (qi >= 0) {
|
||||
QuadNode& q = quad_pool[qi];
|
||||
// Update center of mass
|
||||
float total = q.mass + nmass;
|
||||
q.cx = (q.cx * q.mass + nx * nmass) / total;
|
||||
q.cy = (q.cy * q.mass + ny * nmass) / total;
|
||||
q.mass = total;
|
||||
|
||||
if (q.body == -1 && q.children[0] == -1) {
|
||||
// Empty leaf: place body here
|
||||
q.body = node_idx;
|
||||
return;
|
||||
}
|
||||
|
||||
if (q.body >= 0) {
|
||||
// Leaf with existing body: subdivide, push existing body down
|
||||
quad_subdivide(qi);
|
||||
// Move old body into correct child (re-read q after subdivide since pool may shift)
|
||||
QuadNode& qq = quad_pool[qi];
|
||||
int old_body = qq.body;
|
||||
float obx = /* we need positions */ 0, oby = 0;
|
||||
// We store positions in the GraphData, pass via closure is not possible here.
|
||||
// Instead we pass a pointer to positions alongside. We'll fix this by using
|
||||
// a file-scope pointer set before each build.
|
||||
(void)old_body; (void)obx; (void)oby;
|
||||
// NOTE: positions accessed via file-scope g_nodes pointer below.
|
||||
qq.body = -1;
|
||||
}
|
||||
|
||||
int ci = quad_child_idx(quad_pool[qi], nx, ny);
|
||||
qi = quad_pool[qi].children[ci];
|
||||
}
|
||||
}
|
||||
|
||||
// File-scope pointers set before each tree build (avoids passing them everywhere).
|
||||
static const GraphNode* g_nodes = nullptr;
|
||||
|
||||
// Insert body knowing positions from g_nodes.
|
||||
static void quad_insert_body(int qi, int node_idx) {
|
||||
float nx = g_nodes[node_idx].x;
|
||||
float ny = g_nodes[node_idx].y;
|
||||
const float nmass = 1.0f;
|
||||
|
||||
while (qi >= 0) {
|
||||
QuadNode& q = quad_pool[qi];
|
||||
float total = q.mass + nmass;
|
||||
q.cx = (q.cx * q.mass + nx * nmass) / total;
|
||||
q.cy = (q.cy * q.mass + ny * nmass) / total;
|
||||
q.mass = total;
|
||||
|
||||
if (q.body == -1 && q.children[0] == -1) {
|
||||
// Empty leaf
|
||||
q.body = node_idx;
|
||||
return;
|
||||
}
|
||||
|
||||
if (q.children[0] == -1) {
|
||||
// Leaf occupied: subdivide and push existing body down
|
||||
int old_body = q.body;
|
||||
q.body = -1;
|
||||
quad_subdivide(qi);
|
||||
|
||||
// Push old body into child
|
||||
int old_ci = quad_child_idx(quad_pool[qi], g_nodes[old_body].x, g_nodes[old_body].y);
|
||||
int old_child = quad_pool[qi].children[old_ci];
|
||||
if (old_child >= 0) {
|
||||
QuadNode& oc = quad_pool[old_child];
|
||||
oc.cx = g_nodes[old_body].x;
|
||||
oc.cy = g_nodes[old_body].y;
|
||||
oc.mass = 1.0f;
|
||||
oc.body = old_body;
|
||||
}
|
||||
}
|
||||
|
||||
int ci = quad_child_idx(quad_pool[qi], nx, ny);
|
||||
qi = quad_pool[qi].children[ci];
|
||||
}
|
||||
}
|
||||
|
||||
// Compute Barnes-Hut repulsion force on node at (nx,ny) from subtree qi.
|
||||
// Accumulates force into (fx, fy).
|
||||
static void quad_force(int qi, float nx, float ny,
|
||||
float theta, float repulsion, float min_dist,
|
||||
float& fx, float& fy) {
|
||||
// Iterative traversal using a small stack to avoid recursion depth issues.
|
||||
static int stack[MAX_QUAD_NODES]; // reuse static stack
|
||||
int top = 0;
|
||||
stack[top++] = qi;
|
||||
|
||||
while (top > 0) {
|
||||
int ci = stack[--top];
|
||||
if (ci < 0) continue;
|
||||
const QuadNode& q = quad_pool[ci];
|
||||
if (q.mass == 0) continue;
|
||||
|
||||
float dx = q.cx - nx;
|
||||
float dy = q.cy - ny;
|
||||
float dist2 = dx * dx + dy * dy;
|
||||
float dist = std::sqrt(dist2);
|
||||
if (dist < min_dist) dist = min_dist;
|
||||
|
||||
// Cell size
|
||||
float cell_size = q.x1 - q.x0;
|
||||
|
||||
// Use multipole approximation if far enough OR if leaf
|
||||
bool is_leaf = (q.children[0] == -1);
|
||||
if (is_leaf || (cell_size / dist) < theta) {
|
||||
// Coulomb repulsion: F = repulsion * mass / dist^2
|
||||
float force = repulsion * q.mass / (dist * dist);
|
||||
fx -= force * dx / dist;
|
||||
fy -= force * dy / dist;
|
||||
} else {
|
||||
// Push children
|
||||
for (int k = 0; k < 4; ++k) {
|
||||
if (q.children[k] >= 0)
|
||||
stack[top++] = q.children[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public API
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
float graph_force_layout_step(GraphData& graph, const ForceLayoutConfig& config) {
|
||||
if (graph.node_count <= 0) return 0.0f;
|
||||
|
||||
// Temporary force accumulators (stack-allocated for small graphs, static for large)
|
||||
static float* fx_buf = nullptr;
|
||||
static float* fy_buf = nullptr;
|
||||
static int buf_cap = 0;
|
||||
|
||||
if (graph.node_count > buf_cap) {
|
||||
delete[] fx_buf;
|
||||
delete[] fy_buf;
|
||||
buf_cap = graph.node_count + 64;
|
||||
fx_buf = new float[buf_cap];
|
||||
fy_buf = new float[buf_cap];
|
||||
}
|
||||
|
||||
float total_energy = 0.0f;
|
||||
|
||||
for (int iter = 0; iter < config.iterations; ++iter) {
|
||||
// Zero forces
|
||||
for (int i = 0; i < graph.node_count; ++i) {
|
||||
fx_buf[i] = 0.0f;
|
||||
fy_buf[i] = 0.0f;
|
||||
}
|
||||
|
||||
// ---- Build Barnes-Hut quadtree ----
|
||||
// Compute bounding box of current positions
|
||||
float bx0 = graph.nodes[0].x, bx1 = graph.nodes[0].x;
|
||||
float by0 = graph.nodes[0].y, by1 = graph.nodes[0].y;
|
||||
for (int i = 1; i < graph.node_count; ++i) {
|
||||
float px = graph.nodes[i].x, py = graph.nodes[i].y;
|
||||
if (px < bx0) bx0 = px; if (px > bx1) bx1 = px;
|
||||
if (py < by0) by0 = py; if (py > by1) by1 = py;
|
||||
}
|
||||
// Add margin to avoid degeneracies
|
||||
float margin = (bx1 - bx0 + by1 - by0) * 0.05f + 1.0f;
|
||||
bx0 -= margin; bx1 += margin;
|
||||
by0 -= margin; by1 += margin;
|
||||
// Make it square
|
||||
float side = std::max(bx1 - bx0, by1 - by0);
|
||||
float cx = (bx0 + bx1) * 0.5f, cy = (by0 + by1) * 0.5f;
|
||||
bx0 = cx - side * 0.5f; bx1 = cx + side * 0.5f;
|
||||
by0 = cy - side * 0.5f; by1 = cy + side * 0.5f;
|
||||
|
||||
quad_count = 0;
|
||||
g_nodes = graph.nodes;
|
||||
int root = quad_new(bx0, by0, bx1, by1);
|
||||
|
||||
for (int i = 0; i < graph.node_count; ++i) {
|
||||
quad_insert_body(root, i);
|
||||
}
|
||||
|
||||
// ---- Repulsion via Barnes-Hut ----
|
||||
for (int i = 0; i < graph.node_count; ++i) {
|
||||
if (graph.nodes[i].pinned) continue;
|
||||
quad_force(root,
|
||||
graph.nodes[i].x, graph.nodes[i].y,
|
||||
config.theta, config.repulsion, config.min_distance,
|
||||
fx_buf[i], fy_buf[i]);
|
||||
// Subtract self-interaction (the tree includes the node itself)
|
||||
// Self-force: repulsion * 1 / min_dist^2, but direction is (0,0) -> skip
|
||||
}
|
||||
|
||||
// ---- Attraction along edges (spring force) ----
|
||||
for (int e = 0; e < graph.edge_count; ++e) {
|
||||
const GraphEdge& edge = graph.edges[e];
|
||||
int s = (int)edge.source;
|
||||
int t = (int)edge.target;
|
||||
if (s < 0 || s >= graph.node_count) continue;
|
||||
if (t < 0 || t >= graph.node_count) continue;
|
||||
|
||||
float dx = graph.nodes[t].x - graph.nodes[s].x;
|
||||
float dy = graph.nodes[t].y - graph.nodes[s].y;
|
||||
float dist = std::sqrt(dx * dx + dy * dy);
|
||||
if (dist < config.min_distance) dist = config.min_distance;
|
||||
|
||||
// F = k * dist * weight (Hooke: pulls toward equilibrium at 0)
|
||||
float force = config.attraction * dist * edge.weight;
|
||||
float fx_e = force * dx / dist;
|
||||
float fy_e = force * dy / dist;
|
||||
|
||||
if (!graph.nodes[s].pinned) { fx_buf[s] += fx_e; fy_buf[s] += fy_e; }
|
||||
if (!graph.nodes[t].pinned) { fx_buf[t] -= fx_e; fy_buf[t] -= fy_e; }
|
||||
}
|
||||
|
||||
// ---- Gravity toward center (0,0) ----
|
||||
if (config.gravity != 0.0f) {
|
||||
for (int i = 0; i < graph.node_count; ++i) {
|
||||
if (graph.nodes[i].pinned) continue;
|
||||
fx_buf[i] -= config.gravity * graph.nodes[i].x;
|
||||
fy_buf[i] -= config.gravity * graph.nodes[i].y;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Integrate: v = v * damping + F; pos += v ----
|
||||
total_energy = 0.0f;
|
||||
for (int i = 0; i < graph.node_count; ++i) {
|
||||
GraphNode& n = graph.nodes[i];
|
||||
if (n.pinned) continue;
|
||||
|
||||
n.vx = n.vx * config.damping + fx_buf[i];
|
||||
n.vy = n.vy * config.damping + fy_buf[i];
|
||||
|
||||
// Clamp velocity
|
||||
n.vx = std::max(-config.max_velocity, std::min(config.max_velocity, n.vx));
|
||||
n.vy = std::max(-config.max_velocity, std::min(config.max_velocity, n.vy));
|
||||
|
||||
n.x += n.vx;
|
||||
n.y += n.vy;
|
||||
|
||||
total_energy += n.vx * n.vx + n.vy * n.vy;
|
||||
}
|
||||
}
|
||||
|
||||
graph.update_bounds();
|
||||
return total_energy;
|
||||
}
|
||||
|
||||
void graph_force_layout_reset(GraphData& graph, float spread) {
|
||||
for (int i = 0; i < graph.node_count; ++i) {
|
||||
GraphNode& n = graph.nodes[i];
|
||||
if (n.pinned) continue;
|
||||
// rand() produces [0, RAND_MAX]; map to [-spread, spread]
|
||||
n.x = spread * (2.0f * (float)rand() / (float)RAND_MAX - 1.0f);
|
||||
n.y = spread * (2.0f * (float)rand() / (float)RAND_MAX - 1.0f);
|
||||
n.vx = 0.0f;
|
||||
n.vy = 0.0f;
|
||||
}
|
||||
graph.update_bounds();
|
||||
}
|
||||
|
||||
void graph_layout_circular(GraphData& graph, float radius) {
|
||||
if (graph.node_count <= 0) return;
|
||||
const float two_pi = 6.28318530718f;
|
||||
for (int i = 0; i < graph.node_count; ++i) {
|
||||
GraphNode& n = graph.nodes[i];
|
||||
if (n.pinned) continue;
|
||||
float angle = two_pi * (float)i / (float)graph.node_count;
|
||||
n.x = radius * std::cos(angle);
|
||||
n.y = radius * std::sin(angle);
|
||||
n.vx = 0.0f;
|
||||
n.vy = 0.0f;
|
||||
}
|
||||
graph.update_bounds();
|
||||
}
|
||||
|
||||
void graph_layout_grid(GraphData& graph, float spacing) {
|
||||
if (graph.node_count <= 0) return;
|
||||
int cols = (int)std::ceil(std::sqrt((float)graph.node_count));
|
||||
int rows = (graph.node_count + cols - 1) / cols;
|
||||
float ox = -0.5f * (cols - 1) * spacing;
|
||||
float oy = -0.5f * (rows - 1) * spacing;
|
||||
for (int i = 0; i < graph.node_count; ++i) {
|
||||
GraphNode& n = graph.nodes[i];
|
||||
if (n.pinned) continue;
|
||||
int col = i % cols;
|
||||
int row = i / cols;
|
||||
n.x = ox + col * spacing;
|
||||
n.y = oy + row * spacing;
|
||||
n.vx = 0.0f;
|
||||
n.vy = 0.0f;
|
||||
}
|
||||
graph.update_bounds();
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
struct GraphData; // forward declare
|
||||
|
||||
struct ForceLayoutConfig {
|
||||
float repulsion = 500.0f; // repulsion strength between all nodes
|
||||
float attraction = 0.01f; // spring constant for edges
|
||||
float damping = 0.85f; // velocity decay per step
|
||||
float min_distance = 1.0f; // minimum distance (avoid division by zero)
|
||||
float theta = 0.5f; // Barnes-Hut threshold (0 = exact, 1 = fast)
|
||||
float gravity = 0.1f; // pull toward center (prevents drift)
|
||||
float max_velocity = 50.0f; // cap velocity per axis
|
||||
int iterations = 1; // steps per call
|
||||
};
|
||||
|
||||
// Perform one (or more) steps of force-directed layout.
|
||||
// Modifies node positions (x, y) and velocities (vx, vy) in-place.
|
||||
// Returns the total kinetic energy (sum of |v|^2). When energy < threshold,
|
||||
// layout has converged.
|
||||
float graph_force_layout_step(GraphData& graph, const ForceLayoutConfig& config = {});
|
||||
|
||||
// Reset: randomize positions within [-spread, spread], zero velocities.
|
||||
void graph_force_layout_reset(GraphData& graph, float spread = 200.0f);
|
||||
|
||||
// Preset layouts (non-iterative, instant positioning)
|
||||
void graph_layout_circular(GraphData& graph, float radius = 100.0f);
|
||||
void graph_layout_grid(GraphData& graph, float spacing = 20.0f);
|
||||
@@ -0,0 +1,79 @@
|
||||
---
|
||||
name: graph_force_layout
|
||||
kind: function
|
||||
lang: cpp
|
||||
domain: viz
|
||||
version: "1.0.0"
|
||||
purity: pure
|
||||
signature: "float graph_force_layout_step(GraphData& graph, const ForceLayoutConfig& config)"
|
||||
description: "Layout force-directed con aproximacion Barnes-Hut para grafos grandes, ejecuta un paso de simulacion por llamada"
|
||||
tags: [graph, layout, force-directed, barnes-hut, physics, gpu]
|
||||
uses_functions: []
|
||||
uses_types: ["GraphData_cpp_viz"]
|
||||
returns: []
|
||||
returns_optional: false
|
||||
error_type: ""
|
||||
imports: []
|
||||
tested: false
|
||||
tests: []
|
||||
test_file_path: ""
|
||||
file_path: "cpp/functions/viz/graph_force_layout.cpp"
|
||||
framework: imgui
|
||||
params:
|
||||
- name: graph
|
||||
desc: "Referencia al grafo (GraphData) cuyos nodos se actualizan in-place. Modifica x, y, vx, vy de cada nodo no pinned."
|
||||
- name: config
|
||||
desc: "Parametros de la simulacion: repulsion (fuerza coulombiana), attraction (spring constant), damping (decay de velocidad), theta (precision Barnes-Hut 0=exacto/1=rapido), gravity (atraccion al centro), max_velocity, iterations."
|
||||
output: "Energia cinetica total (suma de |v|^2). Cuando cae por debajo de un umbral elegido por el caller, el layout ha convergido y se puede dejar de llamar."
|
||||
---
|
||||
|
||||
# graph_force_layout
|
||||
|
||||
Implementa el algoritmo de layout force-directed clasico (Fruchterman-Reingold / Eades) con aproximacion Barnes-Hut O(n log n) para escalar a grafos de miles de nodos.
|
||||
|
||||
## Algoritmo
|
||||
|
||||
Cada llamada a `graph_force_layout_step` ejecuta `config.iterations` pasos. Un paso:
|
||||
|
||||
1. **Construccion del quadtree** (Barnes-Hut): se calcula el bounding box de las posiciones actuales, se construye un quadtree flat en `quad_pool` (sin allocaciones por nodo). Cada celda acumula centro de masa y masa total.
|
||||
2. **Repulsion**: para cada nodo se recorre el quadtree. Si el cociente `cell_size / distance < theta`, la celda se trata como una sola masa puntual (multipolo de orden 0). Si no, se desciende a los hijos. Con `theta=0` es O(n²) exacto; con `theta=0.5` es O(n log n).
|
||||
3. **Atraccion**: para cada arista `(s, t)`, fuerza de Hooke `F = k * dist * weight` en la direccion del arco.
|
||||
4. **Gravedad**: fuerza proporcional a la distancia al origen, evita que el grafo derive fuera de pantalla.
|
||||
5. **Integracion**: `v = v * damping + F`, `pos += v`, con clamping de velocidad.
|
||||
6. Nodos con `pinned = true` no se mueven en ningun paso.
|
||||
|
||||
## Funciones auxiliares
|
||||
|
||||
```cpp
|
||||
// Randomizar posiciones para empezar la simulacion
|
||||
graph_force_layout_reset(graph, 200.0f);
|
||||
|
||||
// Layout circular instantaneo (sin iteracion)
|
||||
graph_layout_circular(graph, 150.0f);
|
||||
|
||||
// Layout en grid instantaneo
|
||||
graph_layout_grid(graph, 25.0f);
|
||||
```
|
||||
|
||||
## Ejemplo de uso tipico (loop ImGui)
|
||||
|
||||
```cpp
|
||||
static ForceLayoutConfig cfg;
|
||||
static bool running = true;
|
||||
|
||||
if (running) {
|
||||
float energy = graph_force_layout_step(my_graph, cfg);
|
||||
if (energy < 0.01f) running = false; // convergido
|
||||
}
|
||||
```
|
||||
|
||||
## Notas de implementacion
|
||||
|
||||
- El quadtree usa un pool estatico de `1 << 20` (~1M) celdas. Para grafos de >500K nodos
|
||||
se recomienda reducir `MAX_QUAD_NODES` o aumentarlo segun memoria disponible.
|
||||
- La pila de traversal en `quad_force` es tambien estatica (`static int stack[]`); no es
|
||||
thread-safe si se llama desde multiples hilos simultaneamente.
|
||||
- `graph_force_layout_reset` usa `rand()`. Para reproducibilidad llama `srand(seed)` antes.
|
||||
- Los buffers de fuerza (`fx_buf`, `fy_buf`) se realocan una sola vez cuando el conteo de
|
||||
nodos supera la capacidad previa; en el uso normal (tamano fijo) no hay allocaciones
|
||||
por frame.
|
||||
@@ -0,0 +1,446 @@
|
||||
#include "viz/graph_renderer.h"
|
||||
#include "viz/graph_types.h"
|
||||
|
||||
#define GL_GLEXT_PROTOTYPES
|
||||
#include <GL/gl.h>
|
||||
#include <GL/glext.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <cstdio>
|
||||
#include <cmath>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Community palette (ABGR packed, 10 colors)
|
||||
// ---------------------------------------------------------------------------
|
||||
static const uint32_t k_palette[10] = {
|
||||
0xFF4CAF50, // green
|
||||
0xFFF44336, // red
|
||||
0xFF2196F3, // blue
|
||||
0xFFFF9800, // orange
|
||||
0xFF9C27B0, // purple
|
||||
0xFF00BCD4, // cyan
|
||||
0xFFFFEB3B, // yellow
|
||||
0xFFE91E63, // pink
|
||||
0xFF795548, // brown
|
||||
0xFF607D8B // blue-grey
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal struct
|
||||
// ---------------------------------------------------------------------------
|
||||
struct GraphRenderer {
|
||||
unsigned int fbo;
|
||||
unsigned int texture;
|
||||
unsigned int rbo; // depth/stencil renderbuffer
|
||||
int width, height;
|
||||
|
||||
// Node rendering (instanced quads)
|
||||
unsigned int node_vao, node_quad_vbo, node_instance_vbo;
|
||||
unsigned int node_shader;
|
||||
|
||||
// Edge rendering (lines)
|
||||
unsigned int edge_vao, edge_vbo;
|
||||
unsigned int edge_shader;
|
||||
|
||||
GraphRendererConfig config;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shader sources
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Node vertex shader — instanced unit quad
|
||||
static const char* k_node_vert = R"(
|
||||
#version 330 core
|
||||
// Quad corners [-0.5, 0.5]
|
||||
layout(location = 0) in vec2 a_quad;
|
||||
|
||||
// Per-instance: world position, size, RGBA color
|
||||
layout(location = 1) in vec2 a_pos;
|
||||
layout(location = 2) in float a_size;
|
||||
layout(location = 3) in vec4 a_color;
|
||||
|
||||
out vec2 v_uv;
|
||||
out vec4 v_color;
|
||||
|
||||
uniform vec2 u_viewport; // (width, height) in pixels
|
||||
uniform float u_scale; // cam_zoom
|
||||
uniform vec2 u_translate; // (tx, ty) in pixels
|
||||
|
||||
void main() {
|
||||
// World -> screen (pixels)
|
||||
vec2 screen = a_pos * u_scale + u_translate;
|
||||
// Expand quad by node radius (size = diameter)
|
||||
screen += a_quad * a_size * u_scale;
|
||||
// Screen -> NDC
|
||||
vec2 ndc = (screen / u_viewport) * 2.0 - 1.0;
|
||||
ndc.y = -ndc.y; // flip Y (screen Y grows downward)
|
||||
gl_Position = vec4(ndc, 0.0, 1.0);
|
||||
v_uv = a_quad + 0.5; // [0,1]
|
||||
v_color = a_color;
|
||||
}
|
||||
)";
|
||||
|
||||
// Node fragment shader — SDF circle with outline
|
||||
static const char* k_node_frag = R"(
|
||||
#version 330 core
|
||||
in vec2 v_uv;
|
||||
in vec4 v_color;
|
||||
|
||||
out vec4 frag_color;
|
||||
|
||||
uniform float u_outline_px; // outline width in uv units
|
||||
uniform float u_node_px; // node diameter in pixels (= size * zoom)
|
||||
|
||||
void main() {
|
||||
// SDF circle centered at (0.5, 0.5) in uv space
|
||||
float dist = length(v_uv - 0.5);
|
||||
float r = 0.5;
|
||||
|
||||
// Anti-alias edge (in uv units; 1px ~ 1/u_node_px in uv space)
|
||||
float fwidth_uv = 1.5 / max(u_node_px, 1.0);
|
||||
|
||||
float alpha = 1.0 - smoothstep(r - fwidth_uv, r, dist);
|
||||
if (alpha < 0.001) discard;
|
||||
|
||||
// Outline ring
|
||||
float outline_uv = u_outline_px / max(u_node_px, 1.0);
|
||||
float outline = smoothstep(r - outline_uv - fwidth_uv, r - outline_uv, dist);
|
||||
|
||||
vec3 fill = v_color.rgb;
|
||||
vec3 outline_col = mix(fill, vec3(1.0), 0.6); // lighter outline
|
||||
vec3 color = mix(fill, outline_col, outline);
|
||||
|
||||
frag_color = vec4(color, v_color.a * alpha);
|
||||
}
|
||||
)";
|
||||
|
||||
// Edge vertex shader
|
||||
static const char* k_edge_vert = R"(
|
||||
#version 330 core
|
||||
layout(location = 0) in vec2 a_pos;
|
||||
layout(location = 1) in vec4 a_color;
|
||||
|
||||
out vec4 v_color;
|
||||
|
||||
uniform vec2 u_viewport;
|
||||
uniform float u_scale;
|
||||
uniform vec2 u_translate;
|
||||
|
||||
void main() {
|
||||
vec2 screen = a_pos * u_scale + u_translate;
|
||||
vec2 ndc = (screen / u_viewport) * 2.0 - 1.0;
|
||||
ndc.y = -ndc.y;
|
||||
gl_Position = vec4(ndc, 0.0, 1.0);
|
||||
v_color = a_color;
|
||||
}
|
||||
)";
|
||||
|
||||
// Edge fragment shader
|
||||
static const char* k_edge_frag = R"(
|
||||
#version 330 core
|
||||
in vec4 v_color;
|
||||
out vec4 frag_color;
|
||||
|
||||
void main() {
|
||||
frag_color = v_color;
|
||||
}
|
||||
)";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shader helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
static unsigned int compile_shader(GLenum type, const char* src) {
|
||||
unsigned int s = glCreateShader(type);
|
||||
glShaderSource(s, 1, &src, nullptr);
|
||||
glCompileShader(s);
|
||||
int ok;
|
||||
glGetShaderiv(s, GL_COMPILE_STATUS, &ok);
|
||||
if (!ok) {
|
||||
char buf[512];
|
||||
glGetShaderInfoLog(s, sizeof(buf), nullptr, buf);
|
||||
fprintf(stderr, "[graph_renderer] shader compile error: %s\n", buf);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
static unsigned int link_program(const char* vert_src, const char* frag_src) {
|
||||
unsigned int vs = compile_shader(GL_VERTEX_SHADER, vert_src);
|
||||
unsigned int fs = compile_shader(GL_FRAGMENT_SHADER, frag_src);
|
||||
unsigned int prog = glCreateProgram();
|
||||
glAttachShader(prog, vs);
|
||||
glAttachShader(prog, fs);
|
||||
glLinkProgram(prog);
|
||||
int ok;
|
||||
glGetProgramiv(prog, GL_LINK_STATUS, &ok);
|
||||
if (!ok) {
|
||||
char buf[512];
|
||||
glGetProgramInfoLog(prog, sizeof(buf), nullptr, buf);
|
||||
fprintf(stderr, "[graph_renderer] program link error: %s\n", buf);
|
||||
}
|
||||
glDeleteShader(vs);
|
||||
glDeleteShader(fs);
|
||||
return prog;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FBO helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
static void create_fbo(GraphRenderer* r) {
|
||||
// Texture
|
||||
glGenTextures(1, &r->texture);
|
||||
glBindTexture(GL_TEXTURE_2D, r->texture);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, r->width, r->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
glBindTexture(GL_TEXTURE_2D, 0);
|
||||
|
||||
// Depth renderbuffer
|
||||
glGenRenderbuffers(1, &r->rbo);
|
||||
glBindRenderbuffer(GL_RENDERBUFFER, r->rbo);
|
||||
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, r->width, r->height);
|
||||
glBindRenderbuffer(GL_RENDERBUFFER, 0);
|
||||
|
||||
// FBO
|
||||
glGenFramebuffers(1, &r->fbo);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, r->fbo);
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, r->texture, 0);
|
||||
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, r->rbo);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
}
|
||||
|
||||
static void destroy_fbo(GraphRenderer* r) {
|
||||
glDeleteFramebuffers(1, &r->fbo);
|
||||
glDeleteTextures(1, &r->texture);
|
||||
glDeleteRenderbuffers(1, &r->rbo);
|
||||
r->fbo = r->texture = r->rbo = 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helper: unpack ABGR uint32 to float RGBA
|
||||
// ---------------------------------------------------------------------------
|
||||
static inline void abgr_to_rgba(uint32_t abgr, float& r, float& g, float& b, float& a) {
|
||||
// ABGR layout: bits 31-24 = A, 23-16 = B, 15-8 = G, 7-0 = R
|
||||
a = ((abgr >> 24) & 0xFF) / 255.0f;
|
||||
b = ((abgr >> 16) & 0xFF) / 255.0f;
|
||||
g = ((abgr >> 8) & 0xFF) / 255.0f;
|
||||
r = ((abgr ) & 0xFF) / 255.0f;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public API
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
GraphRenderer* graph_renderer_create(int width, int height, const GraphRendererConfig& config) {
|
||||
GraphRenderer* r = new GraphRenderer();
|
||||
r->width = width;
|
||||
r->height = height;
|
||||
r->config = config;
|
||||
|
||||
// --- FBO ---
|
||||
create_fbo(r);
|
||||
|
||||
// --- Node VAO ---
|
||||
// Unit quad: 4 vertices, each (x, y) in [-0.5, 0.5]
|
||||
static const float quad_verts[8] = {
|
||||
-0.5f, -0.5f,
|
||||
0.5f, -0.5f,
|
||||
-0.5f, 0.5f,
|
||||
0.5f, 0.5f,
|
||||
};
|
||||
|
||||
glGenVertexArrays(1, &r->node_vao);
|
||||
glBindVertexArray(r->node_vao);
|
||||
|
||||
// Quad VBO (location 0)
|
||||
glGenBuffers(1, &r->node_quad_vbo);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, r->node_quad_vbo);
|
||||
glBufferData(GL_ARRAY_BUFFER, sizeof(quad_verts), quad_verts, GL_STATIC_DRAW);
|
||||
glEnableVertexAttribArray(0);
|
||||
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
|
||||
|
||||
// Instance VBO (location 1,2,3 — position, size, color)
|
||||
glGenBuffers(1, &r->node_instance_vbo);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, r->node_instance_vbo);
|
||||
// layout: x, y, size, r, g, b, a — 7 floats per instance
|
||||
glEnableVertexAttribArray(1); // pos
|
||||
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (void*)0);
|
||||
glVertexAttribDivisor(1, 1);
|
||||
glEnableVertexAttribArray(2); // size
|
||||
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (void*)(2 * sizeof(float)));
|
||||
glVertexAttribDivisor(2, 1);
|
||||
glEnableVertexAttribArray(3); // color
|
||||
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (void*)(3 * sizeof(float)));
|
||||
glVertexAttribDivisor(3, 1);
|
||||
|
||||
glBindVertexArray(0);
|
||||
|
||||
// --- Edge VAO ---
|
||||
// Each edge: 2 vertices x (x, y, r, g, b, a) = 2 * 6 floats
|
||||
glGenVertexArrays(1, &r->edge_vao);
|
||||
glBindVertexArray(r->edge_vao);
|
||||
|
||||
glGenBuffers(1, &r->edge_vbo);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, r->edge_vbo);
|
||||
glEnableVertexAttribArray(0); // pos
|
||||
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
|
||||
glEnableVertexAttribArray(1); // color
|
||||
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(2 * sizeof(float)));
|
||||
|
||||
glBindVertexArray(0);
|
||||
|
||||
// --- Shaders ---
|
||||
r->node_shader = link_program(k_node_vert, k_node_frag);
|
||||
r->edge_shader = link_program(k_edge_vert, k_edge_frag);
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
void graph_renderer_destroy(GraphRenderer* r) {
|
||||
if (!r) return;
|
||||
destroy_fbo(r);
|
||||
glDeleteVertexArrays(1, &r->node_vao);
|
||||
glDeleteBuffers(1, &r->node_quad_vbo);
|
||||
glDeleteBuffers(1, &r->node_instance_vbo);
|
||||
glDeleteVertexArrays(1, &r->edge_vao);
|
||||
glDeleteBuffers(1, &r->edge_vbo);
|
||||
glDeleteProgram(r->node_shader);
|
||||
glDeleteProgram(r->edge_shader);
|
||||
delete r;
|
||||
}
|
||||
|
||||
void graph_renderer_resize(GraphRenderer* r, int width, int height) {
|
||||
if (!r) return;
|
||||
if (r->width == width && r->height == height) return;
|
||||
r->width = width;
|
||||
r->height = height;
|
||||
destroy_fbo(r);
|
||||
create_fbo(r);
|
||||
}
|
||||
|
||||
unsigned int graph_renderer_draw(GraphRenderer* r, const GraphData& graph,
|
||||
float cam_x, float cam_y, float cam_zoom) {
|
||||
if (!r) return 0;
|
||||
|
||||
// --- Save GL state ---
|
||||
GLint prev_fbo;
|
||||
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &prev_fbo);
|
||||
GLint prev_viewport[4];
|
||||
glGetIntegerv(GL_VIEWPORT, prev_viewport);
|
||||
|
||||
// --- Bind FBO ---
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, r->fbo);
|
||||
glViewport(0, 0, r->width, r->height);
|
||||
|
||||
// Clear with bg_color (ABGR)
|
||||
float bg_a, bg_b, bg_g, bg_cr;
|
||||
abgr_to_rgba(r->config.bg_color, bg_cr, bg_g, bg_b, bg_a);
|
||||
glClearColor(bg_cr, bg_g, bg_b, bg_a);
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
|
||||
// Enable blending for anti-aliasing and transparency
|
||||
glEnable(GL_BLEND);
|
||||
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
|
||||
|
||||
// View transform: world -> screen pixels
|
||||
// tx = -cam_x * scale + width/2
|
||||
// ty = -cam_y * scale + height/2
|
||||
float scale = cam_zoom;
|
||||
float tx = -cam_x * scale + (float)r->width * 0.5f;
|
||||
float ty = -cam_y * scale + (float)r->height * 0.5f;
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Draw edges
|
||||
// ----------------------------------------------------------------
|
||||
if (graph.edge_count > 0 && graph.edges && graph.nodes) {
|
||||
// Pack: 2 vertices per edge, each vertex = (x, y, r, g, b, a) = 6 floats
|
||||
const int floats_per_edge = 2 * 6;
|
||||
float* edge_buf = (float*)malloc((size_t)graph.edge_count * floats_per_edge * sizeof(float));
|
||||
int vi = 0;
|
||||
for (int i = 0; i < graph.edge_count; ++i) {
|
||||
const GraphEdge& e = graph.edges[i];
|
||||
uint32_t ecol = e.color != 0 ? e.color : 0xFF888888u; // default gray
|
||||
float er, eg, eb, ea;
|
||||
abgr_to_rgba(ecol, er, eg, eb, ea);
|
||||
ea *= r->config.edge_alpha;
|
||||
|
||||
if (e.source < (uint32_t)graph.node_count && e.target < (uint32_t)graph.node_count) {
|
||||
const GraphNode& ns = graph.nodes[e.source];
|
||||
const GraphNode& nt = graph.nodes[e.target];
|
||||
|
||||
// Source vertex
|
||||
edge_buf[vi++] = ns.x; edge_buf[vi++] = ns.y;
|
||||
edge_buf[vi++] = er; edge_buf[vi++] = eg;
|
||||
edge_buf[vi++] = eb; edge_buf[vi++] = ea;
|
||||
// Target vertex
|
||||
edge_buf[vi++] = nt.x; edge_buf[vi++] = nt.y;
|
||||
edge_buf[vi++] = er; edge_buf[vi++] = eg;
|
||||
edge_buf[vi++] = eb; edge_buf[vi++] = ea;
|
||||
}
|
||||
}
|
||||
|
||||
glUseProgram(r->edge_shader);
|
||||
glUniform2f(glGetUniformLocation(r->edge_shader, "u_viewport"), (float)r->width, (float)r->height);
|
||||
glUniform1f(glGetUniformLocation(r->edge_shader, "u_scale"), scale);
|
||||
glUniform2f(glGetUniformLocation(r->edge_shader, "u_translate"), tx, ty);
|
||||
|
||||
glLineWidth(r->config.edge_width);
|
||||
|
||||
glBindVertexArray(r->edge_vao);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, r->edge_vbo);
|
||||
glBufferData(GL_ARRAY_BUFFER, vi * (int)sizeof(float), edge_buf, GL_DYNAMIC_DRAW);
|
||||
glDrawArrays(GL_LINES, 0, vi / 6);
|
||||
glBindVertexArray(0);
|
||||
|
||||
free(edge_buf);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Draw nodes (instanced quads)
|
||||
// ----------------------------------------------------------------
|
||||
if (graph.node_count > 0 && graph.nodes) {
|
||||
// Pack: 7 floats per node: x, y, size, r, g, b, a
|
||||
float* node_buf = (float*)malloc((size_t)graph.node_count * 7 * sizeof(float));
|
||||
for (int i = 0; i < graph.node_count; ++i) {
|
||||
const GraphNode& n = graph.nodes[i];
|
||||
uint32_t ncol = n.color != 0 ? n.color : k_palette[n.community % 10];
|
||||
float nr, ng, nb, na;
|
||||
abgr_to_rgba(ncol, nr, ng, nb, na);
|
||||
|
||||
float sz = n.size > 0.0f ? n.size : 4.0f;
|
||||
float* p = node_buf + i * 7;
|
||||
p[0] = n.x; p[1] = n.y; p[2] = sz;
|
||||
p[3] = nr; p[4] = ng; p[5] = nb; p[6] = na;
|
||||
}
|
||||
|
||||
glUseProgram(r->node_shader);
|
||||
glUniform2f(glGetUniformLocation(r->node_shader, "u_viewport"), (float)r->width, (float)r->height);
|
||||
glUniform1f(glGetUniformLocation(r->node_shader, "u_scale"), scale);
|
||||
glUniform2f(glGetUniformLocation(r->node_shader, "u_translate"), tx, ty);
|
||||
glUniform1f(glGetUniformLocation(r->node_shader, "u_outline_px"), r->config.node_outline);
|
||||
|
||||
glBindVertexArray(r->node_vao);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, r->node_instance_vbo);
|
||||
glBufferData(GL_ARRAY_BUFFER, graph.node_count * 7 * (int)sizeof(float), node_buf, GL_DYNAMIC_DRAW);
|
||||
|
||||
// Draw 4 vertices (triangle strip quad) x node_count instances
|
||||
// Pass per-instance node_px uniform via the average size (approximation)
|
||||
// For exact per-node pixel size we'd need a texture or another approach;
|
||||
// use a uniform average for AA quality — good enough for most graphs.
|
||||
float avg_px = 8.0f * scale; // rough estimate
|
||||
glUniform1f(glGetUniformLocation(r->node_shader, "u_node_px"), avg_px);
|
||||
|
||||
glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, graph.node_count);
|
||||
glBindVertexArray(0);
|
||||
|
||||
free(node_buf);
|
||||
}
|
||||
|
||||
// --- Restore GL state ---
|
||||
glDisable(GL_BLEND);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, (GLuint)prev_fbo);
|
||||
glViewport(prev_viewport[0], prev_viewport[1], prev_viewport[2], prev_viewport[3]);
|
||||
|
||||
return r->texture;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
struct GraphData; // forward declare
|
||||
|
||||
struct GraphRendererConfig {
|
||||
float node_outline = 1.5f; // outline width in pixels
|
||||
float edge_width = 1.0f; // edge line width
|
||||
float edge_alpha = 0.4f; // edge transparency
|
||||
uint32_t bg_color = 0xFF1A1A1E; // ABGR background
|
||||
bool edge_fade_alpha = true; // fade edge alpha by distance to camera
|
||||
// Default palette for communities (when node.color == 0)
|
||||
// 10 distinct colors, ABGR packed
|
||||
};
|
||||
|
||||
struct GraphRenderer;
|
||||
|
||||
// Lifecycle
|
||||
GraphRenderer* graph_renderer_create(int width, int height, const GraphRendererConfig& config = {});
|
||||
void graph_renderer_destroy(GraphRenderer* r);
|
||||
void graph_renderer_resize(GraphRenderer* r, int width, int height);
|
||||
|
||||
// Render graph to internal FBO.
|
||||
// cam_x, cam_y: camera center in graph space
|
||||
// cam_zoom: zoom level (1.0 = 1:1 pixel mapping)
|
||||
// Returns OpenGL texture ID suitable for ImGui::Image().
|
||||
unsigned int graph_renderer_draw(GraphRenderer* r, const GraphData& graph,
|
||||
float cam_x, float cam_y, float cam_zoom);
|
||||
@@ -0,0 +1,87 @@
|
||||
---
|
||||
name: graph_renderer
|
||||
kind: function
|
||||
lang: cpp
|
||||
domain: viz
|
||||
version: "1.0.0"
|
||||
purity: impure
|
||||
signature: "GraphRenderer* graph_renderer_create(int width, int height, const GraphRendererConfig& config)"
|
||||
description: "Renderer GPU de grafos con instanced rendering a FBO, compatible con ImGui::Image para visualizacion de grafos grandes"
|
||||
tags: [graph, renderer, opengl, gpu, instanced, fbo, visualization]
|
||||
uses_functions: []
|
||||
uses_types: ["GraphData_cpp_viz"]
|
||||
returns: []
|
||||
returns_optional: false
|
||||
error_type: "error_go_core"
|
||||
imports: [imgui]
|
||||
tested: false
|
||||
tests: []
|
||||
test_file_path: ""
|
||||
file_path: "cpp/functions/viz/graph_renderer.cpp"
|
||||
framework: imgui
|
||||
params:
|
||||
- name: width
|
||||
desc: "Ancho del framebuffer en pixels"
|
||||
- name: height
|
||||
desc: "Alto del framebuffer en pixels"
|
||||
- name: config
|
||||
desc: "Configuracion visual: outline width, edge width, edge alpha, color de fondo, fade de aristas por distancia a camara"
|
||||
output: "Handle opaco al renderer. Usar graph_renderer_draw() para obtener texture ID de OpenGL, pasable directamente a ImGui::Image()"
|
||||
---
|
||||
|
||||
# graph_renderer
|
||||
|
||||
Renderer GPU de grafos basado en OpenGL 3.3 core profile con instanced rendering. Renderiza nodos y aristas de un `GraphData` a un FBO interno y retorna el texture ID para integracion directa con `ImGui::Image()`.
|
||||
|
||||
## Funciones del API
|
||||
|
||||
```cpp
|
||||
// Ciclo de vida
|
||||
GraphRenderer* graph_renderer_create(int width, int height, const GraphRendererConfig& config = {});
|
||||
void graph_renderer_destroy(GraphRenderer* r);
|
||||
void graph_renderer_resize(GraphRenderer* r, int width, int height);
|
||||
|
||||
// Renderizado
|
||||
unsigned int graph_renderer_draw(GraphRenderer* r, const GraphData& graph,
|
||||
float cam_x, float cam_y, float cam_zoom);
|
||||
```
|
||||
|
||||
## Ejemplo de uso con ImGui
|
||||
|
||||
```cpp
|
||||
// Inicializacion (una vez)
|
||||
GraphRenderer* renderer = graph_renderer_create(800, 600);
|
||||
|
||||
// En el render loop
|
||||
ImVec2 panel_size = ImGui::GetContentRegionAvail();
|
||||
graph_renderer_resize(renderer, (int)panel_size.x, (int)panel_size.y);
|
||||
|
||||
unsigned int tex = graph_renderer_draw(renderer, graph_data,
|
||||
cam_x, cam_y, cam_zoom);
|
||||
|
||||
ImGui::Image((ImTextureID)(uintptr_t)tex,
|
||||
panel_size,
|
||||
ImVec2(0, 1), ImVec2(1, 0)); // flip Y para OpenGL
|
||||
|
||||
// Destruccion
|
||||
graph_renderer_destroy(renderer);
|
||||
```
|
||||
|
||||
## Notas de implementacion
|
||||
|
||||
**Renderizado de nodos:** Instanced rendering con un quad unitario [-0.5, 0.5] expandido por el tamano del nodo. El fragment shader aplica un SDF circular con anti-aliasing via `smoothstep` y un anillo de outline.
|
||||
|
||||
**Renderizado de aristas:** `GL_LINES` con datos de posicion y color empaquetados por arista. El ancho se controla con `GraphRendererConfig::edge_width`.
|
||||
|
||||
**Transformacion de camara:**
|
||||
```
|
||||
tx = -cam_x * zoom + width/2
|
||||
ty = -cam_y * zoom + height/2
|
||||
ndc = (screen / viewport) * 2 - 1
|
||||
```
|
||||
|
||||
**Paleta de comunidades:** 10 colores ABGR usados cuando `node.color == 0`, seleccionados por `node.community % 10`.
|
||||
|
||||
**Estado GL:** Guarda y restaura `GL_FRAMEBUFFER_BINDING` y `GL_VIEWPORT` para ser compatible con el render loop de ImGui sin efectos secundarios.
|
||||
|
||||
**Includes GL:** Usa `#define GL_GLEXT_PROTOTYPES` + `<GL/gl.h>` + `<GL/glext.h>`. Si el proyecto carga funciones GL via glad/gl3w, reemplazar estos includes por el loader correspondiente.
|
||||
@@ -0,0 +1,24 @@
|
||||
#include "graph_types.h"
|
||||
#include <cfloat>
|
||||
|
||||
void GraphData::update_bounds() {
|
||||
if (node_count == 0) {
|
||||
min_x = min_y = max_x = max_y = 0.0f;
|
||||
return;
|
||||
}
|
||||
min_x = max_x = nodes[0].x;
|
||||
min_y = max_y = nodes[0].y;
|
||||
for (int i = 1; i < node_count; ++i) {
|
||||
if (nodes[i].x < min_x) min_x = nodes[i].x;
|
||||
if (nodes[i].x > max_x) max_x = nodes[i].x;
|
||||
if (nodes[i].y < min_y) min_y = nodes[i].y;
|
||||
if (nodes[i].y > max_y) max_y = nodes[i].y;
|
||||
}
|
||||
}
|
||||
|
||||
int GraphData::find_node(uint32_t id) const {
|
||||
for (int i = 0; i < node_count; ++i) {
|
||||
if (nodes[i].id == id) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
// --- Graph node ---
|
||||
struct GraphNode {
|
||||
uint32_t id;
|
||||
float x, y; // position in layout space
|
||||
float vx, vy; // velocity (used by force layout)
|
||||
float size; // visual radius (default 4.0)
|
||||
uint32_t color; // ABGR packed (0 = use default palette)
|
||||
const char* label; // optional display label (nullptr = none)
|
||||
uint32_t community; // group/cluster ID (for auto-coloring)
|
||||
float value; // arbitrary metric (for sizing)
|
||||
bool pinned; // if true, force layout won't move this node
|
||||
};
|
||||
|
||||
// --- Graph edge ---
|
||||
struct GraphEdge {
|
||||
uint32_t source; // index into GraphData::nodes
|
||||
uint32_t target; // index into GraphData::nodes
|
||||
float weight; // edge weight (affects attraction force)
|
||||
uint32_t color; // ABGR packed (0 = default gray)
|
||||
};
|
||||
|
||||
// --- Graph container ---
|
||||
struct GraphData {
|
||||
GraphNode* nodes;
|
||||
int node_count;
|
||||
GraphEdge* edges;
|
||||
int edge_count;
|
||||
|
||||
// Bounding box (updated by layout)
|
||||
float min_x, min_y, max_x, max_y;
|
||||
|
||||
// Recompute bounding box from node positions
|
||||
void update_bounds();
|
||||
|
||||
// Find node index by id. Returns -1 if not found.
|
||||
int find_node(uint32_t id) const;
|
||||
};
|
||||
|
||||
// --- Helper: create a default node ---
|
||||
inline GraphNode graph_node(uint32_t id, float x = 0, float y = 0) {
|
||||
return {id, x, y, 0, 0, 4.0f, 0, nullptr, 0, 0, false};
|
||||
}
|
||||
|
||||
// --- Helper: create an edge ---
|
||||
inline GraphEdge graph_edge(uint32_t source, uint32_t target, float weight = 1.0f) {
|
||||
return {source, target, weight, 0};
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
#include "viz/graph_viewport.h"
|
||||
#include "viz/graph_types.h"
|
||||
#include "viz/graph_renderer.h"
|
||||
#include "viz/graph_force_layout.h"
|
||||
#include "core/graph_spatial_hash.h"
|
||||
#include "imgui.h"
|
||||
|
||||
#include <cstdio> // snprintf
|
||||
#include <cstring> // memset
|
||||
#include <vector>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static void viewport_to_graph(float vx, float vy,
|
||||
float widget_x, float widget_y,
|
||||
float widget_w, float widget_h,
|
||||
float cam_x, float cam_y, float zoom,
|
||||
float& gx, float& gy)
|
||||
{
|
||||
gx = (vx - widget_x - widget_w * 0.5f) / zoom + cam_x;
|
||||
gy = (vy - widget_y - widget_h * 0.5f) / zoom + cam_y;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// graph_viewport_fit
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
void graph_viewport_fit(GraphData& graph, GraphViewportState& state)
|
||||
{
|
||||
graph.update_bounds();
|
||||
if (graph.node_count == 0) {
|
||||
state.cam_x = 0.0f;
|
||||
state.cam_y = 0.0f;
|
||||
state.zoom = 1.0f;
|
||||
return;
|
||||
}
|
||||
|
||||
float cx = (graph.min_x + graph.max_x) * 0.5f;
|
||||
float cy = (graph.min_y + graph.max_y) * 0.5f;
|
||||
state.cam_x = cx;
|
||||
state.cam_y = cy;
|
||||
|
||||
float span_x = graph.max_x - graph.min_x;
|
||||
float span_y = graph.max_y - graph.min_y;
|
||||
float span = (span_x > span_y ? span_x : span_y);
|
||||
|
||||
// Use render dimensions if available; fall back to a safe default.
|
||||
float view_px = (state.render_w > 0 ? (float)state.render_w : 600.0f);
|
||||
float view_py = (state.render_h > 0 ? (float)state.render_h : 400.0f);
|
||||
float view_min = (view_px < view_py ? view_px : view_py);
|
||||
|
||||
if (span > 0.0f) {
|
||||
state.zoom = (view_min * 0.9f) / span;
|
||||
} else {
|
||||
state.zoom = 1.0f;
|
||||
}
|
||||
|
||||
// Clamp to allowed range
|
||||
if (state.zoom < state.zoom_min) state.zoom = state.zoom_min;
|
||||
if (state.zoom > state.zoom_max) state.zoom = state.zoom_max;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// graph_viewport_destroy
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
void graph_viewport_destroy(GraphViewportState& state)
|
||||
{
|
||||
if (state.renderer) {
|
||||
graph_renderer_destroy(state.renderer);
|
||||
state.renderer = nullptr;
|
||||
}
|
||||
if (state.spatial) {
|
||||
delete state.spatial;
|
||||
state.spatial = nullptr;
|
||||
}
|
||||
state.initialized = false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// graph_viewport — main widget
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
bool graph_viewport(const char* id, GraphData& graph, GraphViewportState& state,
|
||||
ImVec2 size)
|
||||
{
|
||||
bool interacted = false;
|
||||
|
||||
// Resolve size
|
||||
ImVec2 avail = ImGui::GetContentRegionAvail();
|
||||
float w = (size.x > 0.0f) ? size.x : avail.x;
|
||||
float h = (size.y > 0.0f) ? size.y : avail.y;
|
||||
if (w < 1.0f) w = 1.0f;
|
||||
if (h < 1.0f) h = 1.0f;
|
||||
|
||||
int iw = (int)w, ih = (int)h;
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// 1. Lazy init
|
||||
// -------------------------------------------------------------------
|
||||
if (!state.initialized) {
|
||||
state.renderer = graph_renderer_create(iw, ih);
|
||||
state.spatial = new SpatialHash(20.0f, 4096);
|
||||
state.render_w = iw;
|
||||
state.render_h = ih;
|
||||
state.initialized = true;
|
||||
graph_viewport_fit(graph, state);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// 2. Resize
|
||||
// -------------------------------------------------------------------
|
||||
if (iw != state.render_w || ih != state.render_h) {
|
||||
graph_renderer_resize(state.renderer, iw, ih);
|
||||
state.render_w = iw;
|
||||
state.render_h = ih;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// 3. Force layout step
|
||||
// -------------------------------------------------------------------
|
||||
if (state.layout_running && graph.node_count > 0) {
|
||||
state.layout_energy = graph_force_layout_step(graph);
|
||||
if (state.layout_energy < 0.01f) {
|
||||
state.layout_running = false;
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// 4. Build spatial hash
|
||||
// -------------------------------------------------------------------
|
||||
if (graph.node_count > 0) {
|
||||
static std::vector<float> xs_buf, ys_buf, sz_buf;
|
||||
xs_buf.resize(graph.node_count);
|
||||
ys_buf.resize(graph.node_count);
|
||||
sz_buf.resize(graph.node_count);
|
||||
for (int i = 0; i < graph.node_count; ++i) {
|
||||
xs_buf[i] = graph.nodes[i].x;
|
||||
ys_buf[i] = graph.nodes[i].y;
|
||||
sz_buf[i] = graph.nodes[i].size;
|
||||
}
|
||||
state.spatial->build(xs_buf.data(), ys_buf.data(), sz_buf.data(), graph.node_count);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// 5. Invisible button to capture input
|
||||
// -------------------------------------------------------------------
|
||||
ImGui::PushID(id);
|
||||
|
||||
ImVec2 widget_pos = ImGui::GetCursorScreenPos();
|
||||
ImGui::InvisibleButton("canvas", ImVec2(w, h),
|
||||
ImGuiButtonFlags_MouseButtonLeft |
|
||||
ImGuiButtonFlags_MouseButtonMiddle|
|
||||
ImGuiButtonFlags_MouseButtonRight);
|
||||
|
||||
bool hovered = ImGui::IsItemHovered();
|
||||
bool lm_down = ImGui::IsMouseDown(ImGuiMouseButton_Left);
|
||||
bool lm_click = ImGui::IsMouseClicked(ImGuiMouseButton_Left);
|
||||
bool mm_down = ImGui::IsMouseDown(ImGuiMouseButton_Middle);
|
||||
bool rm_down = ImGui::IsMouseDown(ImGuiMouseButton_Right);
|
||||
|
||||
ImVec2 mouse_pos = ImGui::GetMousePos();
|
||||
float mx = mouse_pos.x, my = mouse_pos.y;
|
||||
|
||||
// Convert mouse to graph space
|
||||
float gx_mouse, gy_mouse;
|
||||
viewport_to_graph(mx, my,
|
||||
widget_pos.x, widget_pos.y, w, h,
|
||||
state.cam_x, state.cam_y, state.zoom,
|
||||
gx_mouse, gy_mouse);
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// 5a. Pan (middle or right mouse drag)
|
||||
// -------------------------------------------------------------------
|
||||
if (hovered && (mm_down || rm_down)) {
|
||||
ImVec2 delta = ImGui::GetIO().MouseDelta;
|
||||
if (delta.x != 0.0f || delta.y != 0.0f) {
|
||||
state.cam_x -= delta.x / state.zoom;
|
||||
state.cam_y -= delta.y / state.zoom;
|
||||
interacted = true;
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// 5b. Zoom (scroll wheel)
|
||||
// -------------------------------------------------------------------
|
||||
if (hovered) {
|
||||
float wheel = ImGui::GetIO().MouseWheel;
|
||||
if (wheel != 0.0f) {
|
||||
float old_zoom = state.zoom;
|
||||
float new_zoom = old_zoom * (1.0f + wheel * 0.1f);
|
||||
if (new_zoom < state.zoom_min) new_zoom = state.zoom_min;
|
||||
if (new_zoom > state.zoom_max) new_zoom = state.zoom_max;
|
||||
|
||||
// Zoom toward cursor: keep gx_mouse/gy_mouse fixed in graph space
|
||||
float rel_x = (mx - widget_pos.x - w * 0.5f);
|
||||
float rel_y = (my - widget_pos.y - h * 0.5f);
|
||||
state.cam_x += rel_x / old_zoom - rel_x / new_zoom;
|
||||
state.cam_y += rel_y / old_zoom - rel_y / new_zoom;
|
||||
state.zoom = new_zoom;
|
||||
interacted = true;
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// 5c. Hover — query nearest node
|
||||
// -------------------------------------------------------------------
|
||||
state.hovered_node = -1;
|
||||
if (hovered && graph.node_count > 0) {
|
||||
float hit_radius = 10.0f / state.zoom;
|
||||
int nearest = state.spatial->query_nearest(gx_mouse, gy_mouse, hit_radius);
|
||||
if (nearest >= 0) {
|
||||
state.hovered_node = nearest;
|
||||
interacted = true;
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// 5d. Node drag (left mouse down on a node)
|
||||
// -------------------------------------------------------------------
|
||||
if (hovered && lm_down) {
|
||||
if (state.drag_node == -1 && state.hovered_node >= 0) {
|
||||
state.drag_node = state.hovered_node;
|
||||
state.is_dragging = true;
|
||||
}
|
||||
} else {
|
||||
// Release drag
|
||||
if (state.drag_node >= 0 && state.drag_node < graph.node_count) {
|
||||
graph.nodes[state.drag_node].pinned = false;
|
||||
}
|
||||
state.drag_node = -1;
|
||||
state.is_dragging = false;
|
||||
}
|
||||
|
||||
if (state.drag_node >= 0 && state.drag_node < graph.node_count) {
|
||||
GraphNode& n = graph.nodes[state.drag_node];
|
||||
n.x = gx_mouse;
|
||||
n.y = gy_mouse;
|
||||
n.vx = 0.0f;
|
||||
n.vy = 0.0f;
|
||||
n.pinned = true;
|
||||
interacted = true;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// 5e. Click — select node
|
||||
// -------------------------------------------------------------------
|
||||
if (hovered && lm_click && state.drag_node == -1) {
|
||||
state.selected_node = state.hovered_node;
|
||||
interacted = true;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// 5f. Keyboard shortcuts (only when widget is active/hovered)
|
||||
// -------------------------------------------------------------------
|
||||
if (hovered) {
|
||||
if (ImGui::IsKeyPressed(ImGuiKey_Space)) {
|
||||
state.layout_running = !state.layout_running;
|
||||
}
|
||||
if (ImGui::IsKeyPressed(ImGuiKey_F)) {
|
||||
graph_viewport_fit(graph, state);
|
||||
interacted = true;
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// 6. Render to GPU texture
|
||||
// -------------------------------------------------------------------
|
||||
unsigned int tex_id = graph_renderer_draw(state.renderer, graph,
|
||||
state.cam_x, state.cam_y,
|
||||
state.zoom);
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// 7. Display texture (flip UV for OpenGL FBO convention)
|
||||
// -------------------------------------------------------------------
|
||||
ImDrawList* draw_list = ImGui::GetWindowDrawList();
|
||||
draw_list->AddImage(
|
||||
(ImTextureID)(intptr_t)tex_id,
|
||||
widget_pos,
|
||||
ImVec2(widget_pos.x + w, widget_pos.y + h),
|
||||
ImVec2(0.0f, 1.0f), // UV top-left (flipped Y)
|
||||
ImVec2(1.0f, 0.0f) // UV bottom-right
|
||||
);
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// 8. Tooltip on hovered node
|
||||
// -------------------------------------------------------------------
|
||||
if (state.hovered_node >= 0 && state.hovered_node < graph.node_count) {
|
||||
const GraphNode& n = graph.nodes[state.hovered_node];
|
||||
|
||||
// Count degree
|
||||
int degree = 0;
|
||||
for (int i = 0; i < graph.edge_count; ++i) {
|
||||
if ((int)graph.edges[i].source == state.hovered_node ||
|
||||
(int)graph.edges[i].target == state.hovered_node) {
|
||||
++degree;
|
||||
}
|
||||
}
|
||||
|
||||
ImGui::BeginTooltip();
|
||||
if (n.label) ImGui::TextUnformatted(n.label);
|
||||
ImGui::Text("ID: %u", n.id);
|
||||
ImGui::Text("Community: %u", n.community);
|
||||
ImGui::Text("Degree: %d", degree);
|
||||
ImGui::Text("Value: %.3f", n.value);
|
||||
ImGui::EndTooltip();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// 9. Status bar overlay
|
||||
// -------------------------------------------------------------------
|
||||
{
|
||||
char status[128];
|
||||
snprintf(status, sizeof(status),
|
||||
"Nodes: %d | Edges: %d | Zoom: %.2fx | Energy: %.4f | [Space] layout [F] fit",
|
||||
graph.node_count, graph.edge_count,
|
||||
state.zoom, state.layout_energy);
|
||||
|
||||
ImVec2 text_pos = ImVec2(widget_pos.x + 6.0f, widget_pos.y + h - 18.0f);
|
||||
draw_list->AddText(text_pos, IM_COL32(180, 180, 180, 200), status);
|
||||
}
|
||||
|
||||
ImGui::PopID();
|
||||
return interacted;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
#pragma once
|
||||
#include "imgui.h"
|
||||
|
||||
struct GraphData;
|
||||
struct GraphRenderer;
|
||||
struct SpatialHash;
|
||||
|
||||
// Persistent state for graph_viewport widget. Create one per viewport and keep
|
||||
// alive across frames.
|
||||
struct GraphViewportState {
|
||||
// Camera
|
||||
float cam_x = 0.0f, cam_y = 0.0f;
|
||||
float zoom = 1.0f;
|
||||
float zoom_min = 0.01f, zoom_max = 50.0f;
|
||||
|
||||
// Interaction result (read after calling graph_viewport each frame)
|
||||
int hovered_node = -1; // node index under cursor, -1 if none
|
||||
int selected_node = -1; // last clicked node index, -1 if none
|
||||
bool is_dragging = false;
|
||||
|
||||
// Layout
|
||||
bool layout_running = true; // animate force layout each frame
|
||||
float layout_energy = 0.0f; // kinetic energy from last step
|
||||
|
||||
// Internal — managed by graph_viewport / graph_viewport_destroy
|
||||
GraphRenderer* renderer = nullptr;
|
||||
SpatialHash* spatial = nullptr;
|
||||
bool initialized = false;
|
||||
|
||||
// Widget pixel dimensions tracked for resize detection
|
||||
int render_w = 0, render_h = 0;
|
||||
|
||||
// Node being dragged (-1 = none)
|
||||
int drag_node = -1;
|
||||
};
|
||||
|
||||
// Main viewport widget. Call every ImGui frame.
|
||||
// id: unique ImGui widget identifier
|
||||
// graph: mutable graph data (node positions updated on drag)
|
||||
// state: persistent state (camera, selection, GPU renderer); must outlive frames
|
||||
// size: widget size in pixels — ImVec2(0,0) uses all available space
|
||||
// Returns true if any user interaction occurred (hover, click, drag, zoom).
|
||||
bool graph_viewport(const char* id, GraphData& graph, GraphViewportState& state,
|
||||
ImVec2 size = ImVec2(0.0f, 0.0f));
|
||||
|
||||
// Release GPU resources. Call once when done with the viewport.
|
||||
void graph_viewport_destroy(GraphViewportState& state);
|
||||
|
||||
// Fit camera to current graph bounds with 10% padding.
|
||||
void graph_viewport_fit(GraphData& graph, GraphViewportState& state);
|
||||
@@ -0,0 +1,119 @@
|
||||
---
|
||||
name: graph_viewport
|
||||
kind: component
|
||||
lang: cpp
|
||||
domain: viz
|
||||
version: "1.0.0"
|
||||
purity: impure
|
||||
signature: "bool graph_viewport(const char* id, GraphData& graph, GraphViewportState& state, ImVec2 size)"
|
||||
description: "Widget ImGui completo para visualizacion interactiva de grafos con pan, zoom, hover, seleccion y layout en vivo"
|
||||
tags: [graph, viewport, imgui, interactive, pan, zoom, dashboard]
|
||||
uses_functions: ["graph_renderer_cpp_viz", "graph_force_layout_cpp_viz", "graph_spatial_hash_cpp_core"]
|
||||
uses_types: ["GraphData_cpp_viz"]
|
||||
returns: []
|
||||
returns_optional: false
|
||||
error_type: "error_go_core"
|
||||
imports: [imgui]
|
||||
tested: false
|
||||
tests: []
|
||||
test_file_path: ""
|
||||
file_path: "cpp/functions/viz/graph_viewport.cpp"
|
||||
framework: imgui
|
||||
props:
|
||||
- name: id
|
||||
type: "const char*"
|
||||
required: true
|
||||
description: "Identificador unico del widget ImGui"
|
||||
- name: graph
|
||||
type: "GraphData&"
|
||||
required: true
|
||||
description: "Referencia al grafo (lectura de datos, escritura de posiciones al drag)"
|
||||
- name: state
|
||||
type: "GraphViewportState&"
|
||||
required: true
|
||||
description: "Estado persistente del viewport (camera, seleccion, renderer). Debe vivir mas que los frames."
|
||||
- name: size
|
||||
type: "ImVec2"
|
||||
required: false
|
||||
description: "Tamanio del widget en pixeles. ImVec2(0,0) usa todo el espacio disponible."
|
||||
emits: []
|
||||
has_state: true
|
||||
params:
|
||||
- name: id
|
||||
desc: "Identificador unico del widget ImGui. Debe ser estable entre frames."
|
||||
- name: graph
|
||||
desc: "Grafo a visualizar. Las posiciones de nodos se modifican al arrastrar."
|
||||
- name: state
|
||||
desc: "Estado persistente: camara (cam_x, cam_y, zoom), nodo seleccionado/hovereado, renderer GPU, spatial hash. Alojado por el caller."
|
||||
- name: size
|
||||
desc: "Tamanio del widget en pixeles. (0,0) ocupa todo el espacio disponible en la ventana ImGui."
|
||||
output: "true si hubo alguna interaccion del usuario en el frame actual (hover, click, drag, zoom, teclado)"
|
||||
---
|
||||
|
||||
# graph_viewport
|
||||
|
||||
Widget ImGui self-contained para visualizar grafos interactivos. Integra rendering GPU, force-directed layout y hit-testing espacial en una sola llamada por frame.
|
||||
|
||||
## Uso basico
|
||||
|
||||
```cpp
|
||||
// Declarar estado persistente (fuera del loop de render)
|
||||
GraphViewportState vp_state;
|
||||
|
||||
// En el loop de render (dentro de una ventana ImGui):
|
||||
if (graph_viewport("mi_grafo", my_graph, vp_state)) {
|
||||
// hubo interaccion este frame
|
||||
if (vp_state.selected_node >= 0) {
|
||||
auto& n = my_graph.nodes[vp_state.selected_node];
|
||||
// mostrar panel de detalle de n
|
||||
}
|
||||
}
|
||||
|
||||
// Al terminar:
|
||||
graph_viewport_destroy(vp_state);
|
||||
```
|
||||
|
||||
## Estado de camara
|
||||
|
||||
La camara usa coordenadas del espacio del grafo:
|
||||
|
||||
- `cam_x`, `cam_y`: centro de la camara en espacio del grafo
|
||||
- `zoom`: pixeles por unidad de grafo
|
||||
|
||||
`graph_viewport_fit()` centra y ajusta el zoom para que el grafo quepa con 10% de padding.
|
||||
|
||||
## Controles
|
||||
|
||||
| Accion | Control |
|
||||
|--------|---------|
|
||||
| Pan | Boton medio o derecho + arrastrar |
|
||||
| Zoom | Rueda del raton (hacia el cursor) |
|
||||
| Seleccionar nodo | Click izquierdo |
|
||||
| Arrastrar nodo | Click izquierdo sobre nodo |
|
||||
| Toggle layout | Barra espaciadora |
|
||||
| Fit camara | F |
|
||||
|
||||
## Force layout
|
||||
|
||||
El layout se ejecuta automaticamente cada frame mientras `state.layout_running == true`. Se detiene solo cuando la energia cinetica cae por debajo de `0.01`. Se puede pausar/reanudar con la barra espaciadora.
|
||||
|
||||
Los nodos arrastrados se marcan como `pinned = true` durante el drag, impidiendo que el force layout los mueva. Al soltar, `pinned` vuelve a `false`.
|
||||
|
||||
## Tooltip
|
||||
|
||||
Al hacer hover sobre un nodo se muestra un tooltip con: label, id numerico, community, degree (aristas conectadas) y value.
|
||||
|
||||
## Status bar
|
||||
|
||||
En la parte inferior del widget aparece: numero de nodos, aristas, zoom actual, energia del layout y recordatorio de atajos de teclado.
|
||||
|
||||
## Inicializacion lazy
|
||||
|
||||
El renderer OpenGL y el spatial hash se crean en el primer frame. La camara se ajusta automaticamente con `graph_viewport_fit` en la inicializacion.
|
||||
|
||||
## Notas de implementacion
|
||||
|
||||
- Usa `ImGui::InvisibleButton` con flags para los tres botones del raton, capturando input sin dibujar ningun boton visible.
|
||||
- La textura del renderer se muestra con UV volteado en Y (`ImVec2(0,1)` a `ImVec2(1,0)`) para corregir la convencion de coordenadas de OpenGL vs ImGui.
|
||||
- El spatial hash se reconstruye cada frame desde las posiciones actuales de los nodos, garantizando hit-testing correcto despues de drag o layout.
|
||||
- El zoom hacia el cursor mantiene el punto del grafo bajo el cursor fijo en pantalla ajustando `cam_x`/`cam_y`.
|
||||
@@ -0,0 +1,18 @@
|
||||
#include "viz/histogram.h"
|
||||
#include "implot.h"
|
||||
|
||||
void histogram(const char* title, const float* values, int count, int bins) {
|
||||
if (ImPlot::BeginPlot(title, ImVec2(-1, 0))) {
|
||||
int b = (bins > 0) ? bins : ImPlotBin_Sturges;
|
||||
ImPlot::PlotHistogram("##data", values, count, b);
|
||||
ImPlot::EndPlot();
|
||||
}
|
||||
}
|
||||
|
||||
void histogram(const char* title, const double* values, int count, int bins) {
|
||||
if (ImPlot::BeginPlot(title, ImVec2(-1, 0))) {
|
||||
int b = (bins > 0) ? bins : ImPlotBin_Sturges;
|
||||
ImPlot::PlotHistogram("##data", values, count, b);
|
||||
ImPlot::EndPlot();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
// Renders a histogram using ImPlot::PlotHistogram.
|
||||
// Call within an ImGui frame.
|
||||
// bins == -1: automatic bin count via Sturges' rule.
|
||||
void histogram(const char* title, const float* values, int count, int bins = -1);
|
||||
void histogram(const char* title, const double* values, int count, int bins = -1);
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
name: histogram
|
||||
kind: component
|
||||
lang: cpp
|
||||
domain: viz
|
||||
version: "1.0.0"
|
||||
purity: pure
|
||||
signature: "void histogram(const char* title, const float* values, int count, int bins = -1)"
|
||||
description: "Renderiza un histograma con bins automaticos o manuales usando ImPlot PlotHistogram dentro de un frame ImGui"
|
||||
tags: [implot, chart, visualization, gpu, histogram, distribution]
|
||||
uses_functions: []
|
||||
uses_types: []
|
||||
returns: []
|
||||
returns_optional: false
|
||||
error_type: ""
|
||||
imports: [implot]
|
||||
tested: false
|
||||
tests: []
|
||||
test_file_path: ""
|
||||
file_path: "cpp/functions/viz/histogram.cpp"
|
||||
framework: imgui
|
||||
params:
|
||||
- name: title
|
||||
desc: "Titulo del histograma mostrado como cabecera del plot"
|
||||
- name: values
|
||||
desc: "Array de valores numericos a distribuir en bins"
|
||||
- name: count
|
||||
desc: "Numero de valores en el array"
|
||||
- name: bins
|
||||
desc: "Numero de bins. -1 = automatico via regla de Sturges (ImPlotBin_Sturges). Positivo = numero explicito de bins"
|
||||
output: "Renderiza el histograma en el frame ImGui actual"
|
||||
---
|
||||
|
||||
# histogram
|
||||
|
||||
Wrapper atomico sobre `ImPlot::PlotHistogram` con seleccion automatica del numero de bins.
|
||||
|
||||
Cuando `bins == -1` usa `ImPlotBin_Sturges`, que calcula el numero de bins como `ceil(log2(n)) + 1`. Para distribuciones con muchos valores o alta varianza puede preferirse pasar un valor explicito.
|
||||
|
||||
El plot usa `ImVec2(-1, 0)` para ocupar el ancho disponible con altura automatica.
|
||||
|
||||
Debe llamarse dentro del render callback de `fn::run_app`.
|
||||
@@ -0,0 +1,44 @@
|
||||
#include "kpi_card.h"
|
||||
#include "sparkline.h"
|
||||
#include <imgui.h>
|
||||
#include <cstdio>
|
||||
|
||||
void kpi_card(const char* label, float value, float delta_percent,
|
||||
const float* history, int history_count,
|
||||
const char* format) {
|
||||
ImGui::BeginGroup();
|
||||
|
||||
// Label — small, muted
|
||||
ImGui::TextDisabled("%s", label);
|
||||
|
||||
// Value — scaled up font
|
||||
ImGui::SetWindowFontScale(1.8f);
|
||||
char value_buf[64];
|
||||
snprintf(value_buf, sizeof(value_buf), format, value);
|
||||
ImGui::Text("%s", value_buf);
|
||||
ImGui::SetWindowFontScale(1.0f);
|
||||
|
||||
// Delta badge — green up arrow / red down arrow
|
||||
const bool positive = delta_percent >= 0.0f;
|
||||
const ImVec4 delta_color = positive
|
||||
? ImVec4(0.20f, 0.80f, 0.35f, 1.0f) // green
|
||||
: ImVec4(0.90f, 0.25f, 0.25f, 1.0f); // red
|
||||
|
||||
char delta_buf[32];
|
||||
if (positive) {
|
||||
snprintf(delta_buf, sizeof(delta_buf), "\xe2\x96\xb2 +%.1f%%", delta_percent);
|
||||
} else {
|
||||
snprintf(delta_buf, sizeof(delta_buf), "\xe2\x96\xbc %.1f%%", delta_percent);
|
||||
}
|
||||
|
||||
ImGui::PushStyleColor(ImGuiCol_Text, delta_color);
|
||||
ImGui::Text("%s", delta_buf);
|
||||
ImGui::PopStyleColor();
|
||||
|
||||
// Sparkline — matches delta color
|
||||
if (history != nullptr && history_count > 0) {
|
||||
sparkline(label, history, history_count, delta_color, 120.0f, 24.0f);
|
||||
}
|
||||
|
||||
ImGui::EndGroup();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
|
||||
// KPI card — displays a key metric with trend.
|
||||
// Usage:
|
||||
// float history[] = {10, 12, 11, 15, 18, 17, 20};
|
||||
// kpi_card("Revenue", 20000.0f, 12.5f, history, 7, "$%.0f");
|
||||
//
|
||||
// Shows:
|
||||
// - Label (small, muted)
|
||||
// - Value (large font)
|
||||
// - Delta badge (green up / red down)
|
||||
// - Sparkline of history
|
||||
|
||||
void kpi_card(const char* label, float value, float delta_percent,
|
||||
const float* history = nullptr, int history_count = 0,
|
||||
const char* format = "%.1f");
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
name: kpi_card
|
||||
kind: component
|
||||
lang: cpp
|
||||
domain: viz
|
||||
version: "1.0.0"
|
||||
purity: pure
|
||||
signature: "void kpi_card(const char* label, float value, float delta_percent, const float* history = nullptr, int history_count = 0, const char* format = \"%.1f\")"
|
||||
description: "Card de KPI con valor grande, delta porcentual, y sparkline historico para dashboards"
|
||||
tags: [imgui, kpi, card, dashboard, metrics, sparkline]
|
||||
uses_functions: ["sparkline_cpp_viz"]
|
||||
uses_types: []
|
||||
returns: []
|
||||
returns_optional: false
|
||||
error_type: ""
|
||||
imports: [imgui]
|
||||
tested: false
|
||||
tests: []
|
||||
test_file_path: ""
|
||||
file_path: "cpp/functions/viz/kpi_card.cpp"
|
||||
framework: imgui
|
||||
params:
|
||||
- name: label
|
||||
desc: "Nombre del KPI mostrado como header muted (ej: \"Revenue\", \"Users\")"
|
||||
- name: value
|
||||
desc: "Valor numerico actual del KPI"
|
||||
- name: delta_percent
|
||||
desc: "Cambio porcentual respecto al periodo anterior (positivo = mejora, negativo = deterioro)"
|
||||
- name: history
|
||||
desc: "Array de valores historicos para el sparkline. Nullable — si es nullptr no se renderiza sparkline"
|
||||
- name: history_count
|
||||
desc: "Numero de valores en el array history"
|
||||
- name: format
|
||||
desc: "Formato printf para el valor principal (ej: \"$%.0f\", \"%.1f%%\", \"%.2f\")"
|
||||
output: "Renderiza la card KPI completa en el frame ImGui actual: label muted, valor grande, badge delta verde/rojo con triangulo, y sparkline de 120x24px"
|
||||
---
|
||||
|
||||
# kpi_card
|
||||
|
||||
Card compacta para dashboards ImGui que muestra un KPI con contexto de tendencia. Combina label, valor escalado, badge de delta colorizado y sparkline historico en un grupo coherente de ~150px de ancho.
|
||||
|
||||
Usa `sparkline` del registry para el historico, con el mismo color que el badge (verde si delta >= 0, rojo si delta < 0).
|
||||
|
||||
Debe llamarse dentro del render callback de `fn::run_app` (o cualquier contexto con un frame ImGui activo).
|
||||
|
||||
## Ejemplo
|
||||
|
||||
```cpp
|
||||
float history[] = {10.0f, 12.0f, 11.0f, 15.0f, 18.0f, 17.0f, 20.0f};
|
||||
kpi_card("Revenue", 20000.0f, 12.5f, history, 7, "$%.0f");
|
||||
|
||||
// Sin sparkline
|
||||
kpi_card("Error Rate", 0.3f, -15.2f, nullptr, 0, "%.2f%%");
|
||||
|
||||
// Grid de KPIs
|
||||
ImGui::Columns(3, "kpis", false);
|
||||
kpi_card("MAU", 1250000.0f, 3.4f, mau_history, 30);
|
||||
ImGui::NextColumn();
|
||||
kpi_card("Revenue", 89400.0f, -1.2f, rev_history, 30, "$%.0f");
|
||||
ImGui::NextColumn();
|
||||
kpi_card("Churn", 2.1f, -0.3f, churn_history, 30, "%.1f%%");
|
||||
ImGui::Columns(1);
|
||||
```
|
||||
|
||||
## Notas
|
||||
|
||||
- El ancho total del grupo es aproximadamente 150px, apto para grids de 2-4 columnas.
|
||||
- El escalado de fuente usa `SetWindowFontScale(1.8f)` — compatible con cualquier fuente cargada; no requiere fonts adicionales.
|
||||
- Los caracteres UTF-8 del triangulo (`▲` U+25B2 y `▼` U+25BC) requieren que la fuente ImGui tenga el rango de simbolos geometricos cargado, o bien sustituir por ASCII (`^` y `v`).
|
||||
- El color verde del delta es `ImVec4(0.20, 0.80, 0.35, 1.0)` y el rojo `ImVec4(0.90, 0.25, 0.25, 1.0)`, coherentes con los colores del sparkline subyacente.
|
||||
- `BeginGroup`/`EndGroup` permite usar `SameLine()` despues de `kpi_card` y que el cursor avance correctamente.
|
||||
@@ -0,0 +1,31 @@
|
||||
#include "viz/pie_chart.h"
|
||||
#include "implot.h"
|
||||
|
||||
void pie_chart(const char* title, const char* const* labels, const float* values, int count, float radius) {
|
||||
if (ImPlot::BeginPlot(title, ImVec2(-1, 0), ImPlotFlags_Equal | ImPlotFlags_NoLegend)) {
|
||||
ImPlot::SetupAxes(nullptr, nullptr, ImPlotAxisFlags_NoDecorations, ImPlotAxisFlags_NoDecorations);
|
||||
ImPlot::SetupAxesLimits(0, 1, 0, 1);
|
||||
if (radius < 0.0f) {
|
||||
// Donut mode: outer = |radius|, inner = 0.2
|
||||
ImPlot::PlotPieChart(labels, values, count, 0.5, 0.5, -radius, "%.1f", 90.0, ImPlotPieChartFlags_None);
|
||||
} else {
|
||||
float r = (radius > 0.0f) ? radius : 0.4f;
|
||||
ImPlot::PlotPieChart(labels, values, count, 0.5, 0.5, r, "%.1f", 90.0, ImPlotPieChartFlags_None);
|
||||
}
|
||||
ImPlot::EndPlot();
|
||||
}
|
||||
}
|
||||
|
||||
void pie_chart(const char* title, const char* const* labels, const double* values, int count, double radius) {
|
||||
if (ImPlot::BeginPlot(title, ImVec2(-1, 0), ImPlotFlags_Equal | ImPlotFlags_NoLegend)) {
|
||||
ImPlot::SetupAxes(nullptr, nullptr, ImPlotAxisFlags_NoDecorations, ImPlotAxisFlags_NoDecorations);
|
||||
ImPlot::SetupAxesLimits(0, 1, 0, 1);
|
||||
if (radius < 0.0) {
|
||||
ImPlot::PlotPieChart(labels, values, count, 0.5, 0.5, -radius, "%.1f", 90.0, ImPlotPieChartFlags_None);
|
||||
} else {
|
||||
double r = (radius > 0.0) ? radius : 0.4;
|
||||
ImPlot::PlotPieChart(labels, values, count, 0.5, 0.5, r, "%.1f", 90.0, ImPlotPieChartFlags_None);
|
||||
}
|
||||
ImPlot::EndPlot();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
// Renders a pie or donut chart using ImPlot::PlotPieChart.
|
||||
// Call within an ImGui frame.
|
||||
// radius == 0: auto (0.4). radius > 0: explicit radius. radius < 0: donut mode (|radius| as outer, 0.2 as inner).
|
||||
void pie_chart(const char* title, const char* const* labels, const float* values, int count, float radius = 0.0f);
|
||||
void pie_chart(const char* title, const char* const* labels, const double* values, int count, double radius = 0.0);
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
name: pie_chart
|
||||
kind: component
|
||||
lang: cpp
|
||||
domain: viz
|
||||
version: "1.0.0"
|
||||
purity: pure
|
||||
signature: "void pie_chart(const char* title, const char* const* labels, const float* values, int count, float radius = 0.0f)"
|
||||
description: "Renderiza un grafico circular (pie/donut) usando ImPlot PlotPieChart dentro de un frame ImGui"
|
||||
tags: [implot, chart, visualization, gpu, pie, donut]
|
||||
uses_functions: []
|
||||
uses_types: []
|
||||
returns: []
|
||||
returns_optional: false
|
||||
error_type: ""
|
||||
imports: [implot]
|
||||
tested: false
|
||||
tests: []
|
||||
test_file_path: ""
|
||||
file_path: "cpp/functions/viz/pie_chart.cpp"
|
||||
framework: imgui
|
||||
params:
|
||||
- name: title
|
||||
desc: "Titulo del grafico"
|
||||
- name: labels
|
||||
desc: "Array de etiquetas para cada segmento del pie"
|
||||
- name: values
|
||||
desc: "Array de valores numericos para cada segmento"
|
||||
- name: count
|
||||
desc: "Numero de segmentos (longitud de labels y values)"
|
||||
- name: radius
|
||||
desc: "Radio del pie (0 = auto 0.4). Positivo = radio explicito. Negativo = modo donut con outer radius = |radius| e inner = 0.2"
|
||||
output: "Renderiza el grafico circular en el frame ImGui actual"
|
||||
---
|
||||
|
||||
# pie_chart
|
||||
|
||||
Wrapper atomico sobre `ImPlot::PlotPieChart` con soporte para modo pie y modo donut.
|
||||
|
||||
El eje del plot se configura con `ImPlotAxisFlags_NoDecorations` para ocultar los ejes y mostrar solo el grafico circular. El aspecto se fuerza a cuadrado con `ImPlotFlags_Equal`.
|
||||
|
||||
**Modo pie** (`radius >= 0`): dibuja un pie chart solido. Si `radius == 0`, usa radio automatico de 0.4.
|
||||
|
||||
**Modo donut** (`radius < 0`): usa `|radius|` como radio exterior. El agujero interior es fijo en 0.2, suficiente para texto central.
|
||||
|
||||
Debe llamarse dentro del render callback de `fn::run_app`.
|
||||
@@ -0,0 +1,76 @@
|
||||
#include "viz/sparkline.h"
|
||||
#include "imgui.h"
|
||||
|
||||
void sparkline(const char* id, const float* values, int count, ImVec4 color,
|
||||
float width, float height) {
|
||||
if (count <= 0) return;
|
||||
|
||||
ImGui::PushID(id);
|
||||
|
||||
ImVec2 pos = ImGui::GetCursorScreenPos();
|
||||
ImDrawList* draw_list = ImGui::GetWindowDrawList();
|
||||
|
||||
// Reserve inline space
|
||||
ImGui::Dummy(ImVec2(width, height));
|
||||
|
||||
// Find min/max for Y auto-scale
|
||||
float min_val = values[0];
|
||||
float max_val = values[0];
|
||||
for (int i = 1; i < count; i++) {
|
||||
if (values[i] < min_val) min_val = values[i];
|
||||
if (values[i] > max_val) max_val = values[i];
|
||||
}
|
||||
float range = max_val - min_val;
|
||||
if (range < 1e-6f) range = 1.0f; // avoid division by zero for flat lines
|
||||
|
||||
// Fill area under curve (low alpha)
|
||||
if (count >= 2) {
|
||||
ImU32 fill_color = IM_COL32(
|
||||
(int)(color.x * 255),
|
||||
(int)(color.y * 255),
|
||||
(int)(color.z * 255),
|
||||
40);
|
||||
|
||||
// Build fill polygon: baseline bottom-left -> points -> baseline bottom-right
|
||||
// We use AddConvexPolyFilled workaround: draw as a series of triangles from baseline
|
||||
float x0 = pos.x;
|
||||
float y_base = pos.y + height;
|
||||
|
||||
for (int i = 0; i + 1 < count; i++) {
|
||||
float xa = x0 + ((float)i / (count - 1)) * width;
|
||||
float xb = x0 + ((float)(i + 1) / (count - 1)) * width;
|
||||
float ya = pos.y + height - ((values[i] - min_val) / range) * height;
|
||||
float yb = pos.y + height - ((values[i + 1] - min_val) / range) * height;
|
||||
|
||||
draw_list->AddQuadFilled(
|
||||
ImVec2(xa, y_base),
|
||||
ImVec2(xa, ya),
|
||||
ImVec2(xb, yb),
|
||||
ImVec2(xb, y_base),
|
||||
fill_color);
|
||||
}
|
||||
}
|
||||
|
||||
// Draw polyline
|
||||
ImU32 line_color = IM_COL32(
|
||||
(int)(color.x * 255),
|
||||
(int)(color.y * 255),
|
||||
(int)(color.z * 255),
|
||||
(int)(color.w * 255));
|
||||
|
||||
for (int i = 0; i + 1 < count; i++) {
|
||||
float xa = pos.x + ((float)i / (count - 1)) * width;
|
||||
float xb = pos.x + ((float)(i + 1) / (count - 1)) * width;
|
||||
float ya = pos.y + height - ((values[i] - min_val) / range) * height;
|
||||
float yb = pos.y + height - ((values[i + 1] - min_val) / range) * height;
|
||||
draw_list->AddLine(ImVec2(xa, ya), ImVec2(xb, yb), line_color, 1.5f);
|
||||
}
|
||||
|
||||
ImGui::PopID();
|
||||
}
|
||||
|
||||
void sparkline(const char* id, const float* values, int count,
|
||||
float width, float height) {
|
||||
// Default color: soft green
|
||||
sparkline(id, values, count, ImVec4(0.35f, 0.85f, 0.45f, 1.0f), width, height);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include "imgui.h"
|
||||
|
||||
// Renders a mini inline line chart for use in tables, headers and KPI cards.
|
||||
// Auto-scales Y to the min/max of values.
|
||||
// Uses PushID/PopID with id for uniqueness inside tables.
|
||||
void sparkline(const char* id, const float* values, int count,
|
||||
float width = 100.0f, float height = 20.0f);
|
||||
|
||||
void sparkline(const char* id, const float* values, int count, ImVec4 color,
|
||||
float width = 100.0f, float height = 20.0f);
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
name: sparkline
|
||||
kind: component
|
||||
lang: cpp
|
||||
domain: viz
|
||||
version: "1.0.0"
|
||||
purity: pure
|
||||
signature: "void sparkline(const char* id, const float* values, int count, float width = 100.0f, float height = 20.0f)"
|
||||
description: "Renderiza un mini grafico de lineas inline para uso en tablas, headers y KPI cards"
|
||||
tags: [imgui, visualization, sparkline, inline, dashboard]
|
||||
uses_functions: []
|
||||
uses_types: []
|
||||
returns: []
|
||||
returns_optional: false
|
||||
error_type: ""
|
||||
imports: [imgui]
|
||||
tested: false
|
||||
tests: []
|
||||
test_file_path: ""
|
||||
file_path: "cpp/functions/viz/sparkline.cpp"
|
||||
framework: imgui
|
||||
params:
|
||||
- name: id
|
||||
desc: "Identificador unico del widget, usado con PushID/PopID para garantizar unicidad en tablas"
|
||||
- name: values
|
||||
desc: "Array de valores float del sparkline (serie temporal)"
|
||||
- name: count
|
||||
desc: "Numero de valores en el array"
|
||||
- name: width
|
||||
desc: "Ancho en pixels del sparkline (default 100.0)"
|
||||
- name: height
|
||||
desc: "Alto en pixels del sparkline (default 20.0)"
|
||||
output: "Renderiza el sparkline inline en el frame ImGui actual, reservando espacio con ImGui::Dummy"
|
||||
---
|
||||
|
||||
# sparkline
|
||||
|
||||
Mini grafico de lineas inline construido sobre ImGui draw primitives. No requiere ImPlot.
|
||||
|
||||
Auto-escala el eje Y al rango minimo/maximo de los valores. Dibuja una polyline con relleno semitransparente bajo la curva. Disenado para encajar en celdas de tablas, headers y tarjetas KPI.
|
||||
|
||||
Ofrece dos overloads:
|
||||
- Sin color: usa verde suave por defecto (`ImVec4(0.35, 0.85, 0.45, 1.0)`)
|
||||
- Con color: acepta cualquier `ImVec4` para personalizar la linea y el relleno
|
||||
|
||||
Debe llamarse dentro del render callback de `fn::run_app` (o cualquier contexto con un frame ImGui activo).
|
||||
|
||||
## Ejemplo
|
||||
|
||||
```cpp
|
||||
// En una celda de tabla
|
||||
ImGui::TableNextColumn();
|
||||
sparkline("##revenue_spark", revenue.data(), (int)revenue.size(), 80.0f, 18.0f);
|
||||
|
||||
// Con color personalizado (rojo para valores negativos)
|
||||
sparkline("##pnl", pnl.data(), (int)pnl.size(),
|
||||
ImVec4(0.9f, 0.3f, 0.3f, 1.0f), 100.0f, 20.0f);
|
||||
|
||||
// KPI card inline con label
|
||||
ImGui::Text("Revenue"); ImGui::SameLine();
|
||||
sparkline("kpi_rev", data, count);
|
||||
```
|
||||
|
||||
## Notas
|
||||
|
||||
- El relleno bajo la curva usa alpha 40/255 del mismo color de la linea.
|
||||
- Si todos los valores son iguales (rango < 1e-6), la linea se dibuja en el centro verticalmente.
|
||||
- El grosor de linea es 1.5px para que sea legible a alturas de 16-24px.
|
||||
- `id` no se muestra visualmente; solo se pasa a `PushID` para que ImGui diferencie widgets con los mismos datos en la misma tabla.
|
||||
@@ -0,0 +1,12 @@
|
||||
#include "viz/surface_plot_3d.h"
|
||||
#include "imgui.h"
|
||||
|
||||
void surface_plot_3d(const char* title, const float* values, int rows, int cols,
|
||||
float z_min, float z_max) {
|
||||
ImGui::BeginGroup();
|
||||
ImGui::TextDisabled("[STUB] %s", title);
|
||||
ImGui::TextWrapped("surface_plot_3d requires ImPlot3D. "
|
||||
"Add it to cpp/vendor/implot3d/ and rebuild.");
|
||||
ImGui::Text("Data: %dx%d, range [%.2f, %.2f]", rows, cols, z_min, z_max);
|
||||
ImGui::EndGroup();
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
// [STUB] Renders a 3D surface plot using ImPlot3D.
|
||||
// Requires ImPlot3D to be vendored in cpp/vendor/implot3d/.
|
||||
// Until then, displays a placeholder message inside an ImGui group.
|
||||
// Call within an ImGui frame (inside fn::run_app render callback).
|
||||
void surface_plot_3d(const char* title, const float* values, int rows, int cols,
|
||||
float z_min, float z_max);
|
||||
@@ -0,0 +1,61 @@
|
||||
---
|
||||
name: surface_plot_3d
|
||||
kind: component
|
||||
lang: cpp
|
||||
domain: viz
|
||||
version: "1.0.0"
|
||||
purity: pure
|
||||
signature: "void surface_plot_3d(const char* title, const float* values, int rows, int cols, float z_min, float z_max)"
|
||||
description: "[STUB] Renderiza una superficie 3D — requiere ImPlot3D (no vendoreado aun)"
|
||||
tags: [implot3d, chart, visualization, gpu, surface, 3d, stub]
|
||||
uses_functions: []
|
||||
uses_types: []
|
||||
returns: []
|
||||
returns_optional: false
|
||||
error_type: ""
|
||||
imports: [imgui]
|
||||
tested: false
|
||||
tests: []
|
||||
test_file_path: ""
|
||||
file_path: "cpp/functions/viz/surface_plot_3d.cpp"
|
||||
framework: imgui
|
||||
params:
|
||||
- name: title
|
||||
desc: "Titulo de la superficie, se muestra como header del plot"
|
||||
- name: values
|
||||
desc: "Array row-major de alturas Z con dimension rows*cols"
|
||||
- name: rows
|
||||
desc: "Numero de filas de la grilla de la superficie"
|
||||
- name: cols
|
||||
desc: "Numero de columnas de la grilla de la superficie"
|
||||
- name: z_min
|
||||
desc: "Valor minimo del eje Z para escalar el colormap"
|
||||
- name: z_max
|
||||
desc: "Valor maximo del eje Z para escalar el colormap"
|
||||
output: "Renderiza un placeholder informativo en el frame ImGui actual; cuando ImPlot3D este disponible, renderizara la superficie 3D"
|
||||
---
|
||||
|
||||
# surface_plot_3d
|
||||
|
||||
**STUB** — la implementacion real requiere [ImPlot3D](https://github.com/brenocq/implot3d), que todavia no esta vendoreado en `cpp/vendor/implot3d/`.
|
||||
|
||||
Mientras tanto la funcion renderiza un grupo ImGui con un mensaje informativo que muestra el titulo, las dimensiones de la grilla y el rango Z. La firma es definitiva y no cambiara cuando se integre ImPlot3D.
|
||||
|
||||
## Dependencia pendiente
|
||||
|
||||
Para activar la implementacion real:
|
||||
|
||||
1. Clonar o copiar ImPlot3D en `cpp/vendor/implot3d/`
|
||||
2. Anadir `implot3d.cpp` al build system (CMake / Makefile)
|
||||
3. Reemplazar el cuerpo de `surface_plot_3d` por la llamada a `ImPlot3D::BeginPlot3D` / `ImPlot3D::PlotSurface` / `ImPlot3D::EndPlot3D`
|
||||
4. Actualizar `imports` del .md a `[imgui, implot3d]` y quitar el tag `stub`
|
||||
|
||||
## Uso
|
||||
|
||||
```cpp
|
||||
// values es un array row-major de rows*cols floats
|
||||
float grid[4 * 4] = { ... };
|
||||
surface_plot_3d("Mi Superficie", grid, 4, 4, -1.0f, 1.0f);
|
||||
```
|
||||
|
||||
Debe llamarse dentro del render callback de `fn::run_app` (o cualquier contexto con un frame ImGui activo).
|
||||
@@ -0,0 +1,32 @@
|
||||
#include "viz/table_view.h"
|
||||
#include "imgui.h"
|
||||
|
||||
bool table_view(const char* id, const char* const* headers, int col_count, const char* const* cells, int row_count) {
|
||||
ImGuiTableFlags flags =
|
||||
ImGuiTableFlags_Borders |
|
||||
ImGuiTableFlags_Sortable |
|
||||
ImGuiTableFlags_RowBg |
|
||||
ImGuiTableFlags_Resizable |
|
||||
ImGuiTableFlags_ScrollY |
|
||||
ImGuiTableFlags_Reorderable;
|
||||
|
||||
if (!ImGui::BeginTable(id, col_count, flags, ImVec2(0, 300))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int col = 0; col < col_count; col++) {
|
||||
ImGui::TableSetupColumn(headers[col]);
|
||||
}
|
||||
ImGui::TableHeadersRow();
|
||||
|
||||
for (int row = 0; row < row_count; row++) {
|
||||
ImGui::TableNextRow();
|
||||
for (int col = 0; col < col_count; col++) {
|
||||
ImGui::TableSetColumnIndex(col);
|
||||
ImGui::TextUnformatted(cells[row * col_count + col]);
|
||||
}
|
||||
}
|
||||
|
||||
ImGui::EndTable();
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
// Renders an interactive table with sorting indicators and scroll using the ImGui Tables API.
|
||||
// Call within an ImGui frame.
|
||||
// Returns true if the table was rendered visible, false if clipped/skipped.
|
||||
bool table_view(const char* id, const char* const* headers, int col_count, const char* const* cells, int row_count);
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
name: table_view
|
||||
kind: component
|
||||
lang: cpp
|
||||
domain: viz
|
||||
version: "1.0.0"
|
||||
purity: pure
|
||||
signature: "bool table_view(const char* id, const char* const* headers, int col_count, const char* const* cells, int row_count)"
|
||||
description: "Renderiza una tabla interactiva con sorting y scroll usando ImGui Tables API"
|
||||
tags: [imgui, table, visualization, dashboard, data]
|
||||
uses_functions: []
|
||||
uses_types: []
|
||||
returns: []
|
||||
returns_optional: false
|
||||
error_type: ""
|
||||
imports: [imgui]
|
||||
tested: false
|
||||
tests: []
|
||||
test_file_path: ""
|
||||
file_path: "cpp/functions/viz/table_view.cpp"
|
||||
framework: imgui
|
||||
params:
|
||||
- name: id
|
||||
desc: "Identificador unico de la tabla para ImGui (debe ser unico en el frame)"
|
||||
- name: headers
|
||||
desc: "Array de strings con los nombres de las columnas"
|
||||
- name: col_count
|
||||
desc: "Numero de columnas"
|
||||
- name: cells
|
||||
desc: "Array flat row-major de strings; acceso a celda (row, col) via cells[row * col_count + col]"
|
||||
- name: row_count
|
||||
desc: "Numero de filas de datos, sin contar el header"
|
||||
output: "true si la tabla se renderizo visible, false si fue clipped o skipped por ImGui"
|
||||
---
|
||||
|
||||
# table_view
|
||||
|
||||
Wrapper atomico sobre `ImGui::BeginTable` / `ImGui::EndTable`. Renderiza una tabla con las siguientes capacidades:
|
||||
|
||||
- **Borders**: bordes entre celdas y columnas
|
||||
- **Sortable**: muestra indicadores de orden en los headers (el caller es responsable de ordenar `cells` antes de llamar)
|
||||
- **RowBg**: filas alternadas con color de fondo
|
||||
- **Resizable**: el usuario puede arrastrar los separadores de columna
|
||||
- **ScrollY**: scroll vertical con altura fija de 300px
|
||||
- **Reorderable**: el usuario puede reordenar columnas arrastrando los headers
|
||||
|
||||
El caller controla el orden de los datos — `table_view` solo habilita el flag `Sortable` para que ImGui muestre los indicadores visuales, pero no reordena `cells` internamente.
|
||||
|
||||
Debe llamarse dentro del render callback de `fn::run_app` (o cualquier contexto con un frame ImGui activo).
|
||||
|
||||
## Ejemplo
|
||||
|
||||
```cpp
|
||||
const char* headers[] = {"Nombre", "Valor", "Estado"};
|
||||
const char* cells[] = {
|
||||
"Alpha", "1.23", "OK",
|
||||
"Beta", "4.56", "WARN",
|
||||
"Gamma", "7.89", "ERROR",
|
||||
};
|
||||
table_view("##mi_tabla", headers, 3, cells, 3);
|
||||
```
|
||||
|
||||
## Notas
|
||||
|
||||
- `id` debe comenzar con `##` si no se quiere mostrar como titulo de ventana en el contexto ImGui.
|
||||
- El outer size fijo de `ImVec2(0, 300)` puede parametrizarse en una version futura.
|
||||
- El sorting real de datos queda fuera del scope de esta funcion para mantenerla pura y componible.
|
||||
Reference in New Issue
Block a user