commit 0fcda5aa093dc3c8e2c3a597d6f425ce75c779c8 Author: 4DBug <115124145+4DBug@users.noreply.github.com> Date: Sat Oct 17 04:25:43 2026 -0500 Scaffold: upstream @ 7913cf1, core submodule, test runner, example diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..30e1d28 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +.gitattributes export-ignore +tools/upstream/** linguist-vendored=true diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..f73a6ab --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "tools/core"] + path = tools/core + url = https://git.bug.tools/bug/imgui-luau.git diff --git a/ImPlot3D.lua b/ImPlot3D.lua new file mode 100644 index 0000000..85d49c8 --- /dev/null +++ b/ImPlot3D.lua @@ -0,0 +1,8 @@ +-- ImPlot3D for imgui-luau. Port of https://github.com/brenocq/implot3d (7913cf11684730119bd284fd8e7052d140e72f61). +-- Usage: local ImPlot3D = require(path.to.ImPlot3D)(require(path.to.ImGui)) +return function(G) + local ImGui, ImVec2, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4 + local ImPlot3D = {} + -- [Port] TODO: port from tools/upstream + return ImPlot3D +end diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..624a823 --- /dev/null +++ b/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Copyright (c) 2024-2026 Breno Cunha Queiroz + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +Luau port: Copyright (c) 2026 4DBug, same MIT terms. diff --git a/README.md b/README.md new file mode 100644 index 0000000..81c9079 --- /dev/null +++ b/README.md @@ -0,0 +1,26 @@ +# implot3d-luau + +Immediate-mode 3D plotting (ImPlot3D) for imgui-luau (Roblox / LÖVE). + +Luau port of [ImPlot3D](https://github.com/brenocq/implot3d) for [imgui-luau](https://git.bug.tools/bug/imgui-luau) ([GitHub](https://github.com/4DBug/imgui-luau)). +Mirrors: [git.bug.tools](https://git.bug.tools/bug/implot3d-luau) / [GitHub](https://github.com/4DBug/implot3d-luau). + +**Status: work in progress.** + +```lua +local G = require(ReplicatedStorage.ImGui) +local ImPlot3D = require(ReplicatedStorage.ImPlot3D)(G) +``` + +## Development + +```sh +git clone --recursive https://git.bug.tools/bug/implot3d-luau.git +bash tools/test.sh # tests/t_*.luau in the core's Roblox mock +``` + +Upstream source (pinned) is in `tools/upstream/`; port-specific comments are tagged `[Port]`. + +## License + +MIT, see LICENSE (upstream copyright kept). diff --git a/default.project.json b/default.project.json new file mode 100644 index 0000000..d6dcb37 --- /dev/null +++ b/default.project.json @@ -0,0 +1,11 @@ +{ + "name": "implot3d-luau", + "tree": { + "$className": "DataModel", + "ReplicatedStorage": { + "ImGui": { "$path": "tools/core/build/ImGuiTyped.luau", "Impl": { "$path": "tools/core/build/ImGui.luau" } }, + "ImPlot3D": { "$path": "ImPlot3D.lua" } + }, + "StarterPlayer": { "StarterPlayerScripts": { "ImPlot3DExample": { "$path": "examples/roblox/main.client.luau" } } } + } +} diff --git a/examples/roblox/main.client.luau b/examples/roblox/main.client.luau new file mode 100644 index 0000000..a7a5424 --- /dev/null +++ b/examples/roblox/main.client.luau @@ -0,0 +1,15 @@ +local RS = game:GetService("ReplicatedStorage") +local RunService = game:GetService("RunService") +local G = require(RS:WaitForChild("ImGui")) +local ImPlot3D = require(RS:WaitForChild("ImPlot3D"))(G) +local ImGui = G.ImGui + +ImGui.CreateContext() +G.ImGui_ImplRoblox.Init(game:GetService("Players").LocalPlayer:WaitForChild("PlayerGui")) +RunService.RenderStepped:Connect(function() + G.ImGui_ImplRoblox.NewFrame() + ImGui.NewFrame() + -- ImPlot3D example goes here + ImGui.Render() + G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData()) +end) diff --git a/tests/t_load.luau b/tests/t_load.luau new file mode 100644 index 0000000..dda6fa5 --- /dev/null +++ b/tests/t_load.luau @@ -0,0 +1,5 @@ +local RS = game:GetService("ReplicatedStorage") +local G = require(RS:WaitForChild("ImGui")) +local ImPlot3D = require(RS:WaitForChild("ImPlot3D"))(G) +assert(type(ImPlot3D) == "table", "module did not return a table") +print("OK") diff --git a/tools/core b/tools/core new file mode 160000 index 0000000..b0e4f10 --- /dev/null +++ b/tools/core @@ -0,0 +1 @@ +Subproject commit b0e4f105f5820f4165ca990d966924f5b582925c diff --git a/tools/test.sh b/tools/test.sh new file mode 100755 index 0000000..60cda9c --- /dev/null +++ b/tools/test.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Runs every tests/t_*.luau against the core (tools/core submodule) in the Roblox mock. +cd "$(dirname "$0")/.." +fail=0 +for t in tests/t_*.luau; do + out=$(python3 tools/core/tools/test/run.py --module ImPlot3D=ImPlot3D.lua --main "$t" --quiet --roblox 2>&1) + if echo "$out" | grep -q "^OK"; then echo "PASS $t"; else echo "FAIL $t"; echo "$out" | tail -20; fail=1; fi +done +exit $fail diff --git a/tools/upstream/LICENSE b/tools/upstream/LICENSE new file mode 100644 index 0000000..2eab42e --- /dev/null +++ b/tools/upstream/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024-2026 Breno Cunha Queiroz + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/upstream/UPSTREAM.txt b/tools/upstream/UPSTREAM.txt new file mode 100644 index 0000000..8ed349a --- /dev/null +++ b/tools/upstream/UPSTREAM.txt @@ -0,0 +1 @@ +https://github.com/brenocq/implot3d @ 7913cf11684730119bd284fd8e7052d140e72f61 diff --git a/tools/upstream/implot3d.cpp b/tools/upstream/implot3d.cpp new file mode 100644 index 0000000..7472594 --- /dev/null +++ b/tools/upstream/implot3d.cpp @@ -0,0 +1,4440 @@ +// SPDX-License-Identifier: MIT +// SPDX-FileCopyrightText: 2024-2026 Breno Cunha Queiroz + +// ImPlot3D v0.5 WIP + +// Acknowledgments: +// ImPlot3D is heavily inspired by ImPlot +// (https://github.com/epezent/implot) by Evan Pezent, +// and follows a similar code style and structure to +// maintain consistency with ImPlot's API. + +// Table of Contents: +// [SECTION] Includes +// [SECTION] Macros +// [SECTION] Context +// [SECTION] Text Utils +// [SECTION] Legend Utils +// [SECTION] Mouse Position Utils +// [SECTION] Plot Box Utils +// [SECTION] Formatter +// [SECTION] Locator +// [SECTION] Context Menus +// [SECTION] Begin/End Plot +// [SECTION] Setup +// [SECTION] Plot Utils +// [SECTION] Setup Utils +// [SECTION] Miscellaneous +// [SECTION] Styles +// [SECTION] Colormaps +// [SECTION] Context Utils +// [SECTION] Style Utils +// [SECTION] ImPlot3DPoint +// [SECTION] ImPlot3DBox +// [SECTION] ImPlot3DRange +// [SECTION] ImPlot3DQuat +// [SECTION] ImDrawList3D +// [SECTION] ImPlot3DAxis +// [SECTION] ImPlot3DPlot +// [SECTION] ImPlot3DStyle +// [SECTION] Metrics +// [SECTION] Obsolete API + +/* +API BREAKING CHANGES +==================== +Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix. +Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code. +When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all +implot3d files. You can read releases logs https://github.com/brenocq/implot3d/releases for more details. + +- 2026/04/04 (0.4) - PlotMesh signature changed: the ImPlot3DPoint* overload is deprecated and will be removed in v1.0. + A new overload accepting separate coordinate arrays (vtx_xs, vtx_ys, vtx_zs) was added, matching + the pattern of PlotLine/PlotScatter/PlotTriangle and supporting Spec.Offset and Spec.Stride. + ```cpp + // Before + ImPlot3D::PlotMesh("Mesh", vtx, idxs, vtx_count, idx_count); + + // After + ImPlot3D::PlotMesh("Mesh", vtx_xs, vtx_ys, vtx_zs, idxs, vtx_count, idx_count); + ``` +- 2026/02/03 (0.4) - ImPlotSpec was made the default and _only_ way of styling plot items. The SetNextXXXStyle functions have been removed. + - SetNextLineStyle has been removed, styling should be set via ImPlot3DSpec. + ```cpp + // Before + ImPlot3D::SetNextLineStyle(line_color, line_weight); + ImPlot3D::PlotLine("Line", xs, ys, zs, count); + + // After + ImPlot3DSpec spec; + spec.LineColor = line_color; + spec.LineWeight = line_weight; + ImPlot3D::PlotLine("Line", xs, ys, zs, count, spec); + ``` + - SetNextFillStyle has been removed, styling should be set via ImPlot3DSpec. + ```cpp + // Before + ImPlot3D::SetNextFillStyle(fill_color, fill_alpha); + ImPlot3D::PlotTriangle("Triangle", xs, ys, zs, count); + + // After + ImPlot3DSpec spec; + spec.FillColor = fill_color; + spec.FillAlpha = fill_alpha; + ImPlot3D::PlotTriangle("Triangle", xs, ys, zs, count, spec); + ``` + - SetNextMarkerStyle has been removed, styling should be set via ImPlot3DSpec. + ```cpp + // Before: + ImPlot3D::SetNextMarkerStyle(marker, marker_size, fill_color, line_weight, marker_outline_color); + ImPlot3D::PlotScatter("Scatter", xs, ys, zs, count); + + // After + ImPlot3DSpec spec; + spec.LineWeight = line_weight; + spec.Marker = marker; + spec.MarkerSize = marker_size; + spec.MarkerLineColor = marker_outline_color; + spec.MarkerFillColor = fill_color; + ImPlot3D::PlotScatter("Scatter", xs, ys, zs, count, spec); + ``` + - Flags, Offset and Stride should also be set via ImPlot3DSpec now. +- 2026/02/02 (0.4) - Item colors removed from ImPlot3DCol_, it's no longer possible to push/pop individual item colors. +- 2026/02/02 (0.4) - ImPlot3DStyle::MarkerWeight was removed. The marker line weight is now controlled by ImPlot3DStyle::LineWeight. + +- 2025/11/15 (0.3) - Renamed GetPlotPos() -> GetPlotRectPos() and GetPlotSize() -> GetPlotRectSize() for clarity in 3D context. + Old functions are marked as deprecated and will be removed in v1.0. +- 2025/10/22 (0.3) - **IMPORTANT** All plot coordinate types migrated from float to double precision to fix sorting issues with large values: + - ImPlot3DPoint members (x, y, z): float -> double + - ImPlot3DPoint operators: float parameters -> double parameters + - ImPlot3DRange members (Min, Max): float -> double + - ImPlot3DQuat members (x, y, z, w): float -> double + - ImPlot3DQuat methods: float parameters -> double parameters + - ImPlot3DTick::PlotPos: float -> double + - ImPlot3DAxis::NDCScale: float -> double + - ImDrawList3D::ZBuffer: ImVector -> ImVector + - ImDrawList3D::_ZWritePtr: float* -> double* + - ImPlot3DFormatter callback: float value -> double value + - SetupBoxRotation(): float elevation, float azimuth -> double elevation, double azimuth + - SetupBoxInitialRotation(): float elevation, float azimuth -> double elevation, double azimuth + - SetupBoxScale(): float x, float y, float z -> double x, double y, double z + - PlotText(): float x, float y, float z, float angle -> double x, double y, double z, double angle + No code changes required for most users. Advanced users directly using these classes with float precision assumption may need to + update their code. +- 2025/07/21 (0.3) - Renamed ImPlot3DPlot::GetBoxZoom() -> ImPlot3DPlot::GetViewScale() (internal API only). +*/ + +//----------------------------------------------------------------------------- +// [SECTION] Includes +//----------------------------------------------------------------------------- + +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif + +// We define this to avoid accidentally using the deprecated API +#ifndef IMPLOT3D_DISABLE_OBSOLETE_FUNCTIONS +#define IMPLOT3D_DISABLE_OBSOLETE_FUNCTIONS +#endif + +#include "implot3d.h" +#include "implot3d_internal.h" + +#ifndef IMGUI_DISABLE + +//----------------------------------------------------------------------------- +// [SECTION] Macros +//----------------------------------------------------------------------------- + +#define IMPLOT3D_CHECK_CTX() \ + IM_ASSERT_USER_ERROR(GImPlot3D != nullptr, "No current context. Did you call ImPlot3D::CreateContext() or ImPlot3D::SetCurrentContext()?") +#define IMPLOT3D_CHECK_PLOT() IM_ASSERT_USER_ERROR(GImPlot3D->CurrentPlot != nullptr, "No active plot. Did you call ImPlot3D::BeginPlot()?") + +//----------------------------------------------------------------------------- +// [SECTION] Context +//----------------------------------------------------------------------------- + +namespace ImPlot3D { + +// Global ImPlot3D context +#ifndef GImPlot3D +ImPlot3DContext* GImPlot3D = nullptr; +#endif + +ImPlot3DContext* CreateContext() { + ImPlot3DContext* ctx = IM_NEW(ImPlot3DContext)(); + if (GImPlot3D == nullptr) + SetCurrentContext(ctx); + InitializeContext(ctx); + return ctx; +} + +void DestroyContext(ImPlot3DContext* ctx) { + if (ctx == nullptr) + ctx = GImPlot3D; + if (GImPlot3D == ctx) + SetCurrentContext(nullptr); + IM_DELETE(ctx); +} + +ImPlot3DContext* GetCurrentContext() { return GImPlot3D; } + +void SetCurrentContext(ImPlot3DContext* ctx) { GImPlot3D = ctx; } + +//----------------------------------------------------------------------------- +// [SECTION] Text Utils +//----------------------------------------------------------------------------- + +void AddTextRotated(ImDrawList* draw_list, ImVec2 pos, float angle, ImU32 col, const char* text_begin, const char* text_end) { + if (!text_end) + text_end = text_begin + strlen(text_begin); + + ImGuiContext& g = *GImGui; + ImFont* font = g.Font; + +#ifdef IMGUI_HAS_TEXTURES + ImFontBaked* fontBaked = g.Font->GetFontBaked(g.FontSize); + const float scale = g.FontSize / fontBaked->Size; +#else + const float scale = g.FontSize / font->FontSize; +#endif + + // Align to be pixel perfect + pos = ImFloor(pos); + + // Measure the size of the text in unrotated coordinates + ImVec2 text_size = font->CalcTextSizeA(g.FontSize, FLT_MAX, 0.0f, text_begin, text_end, nullptr); + + // Precompute sine and cosine of the angle (note: angle should be positive for rotation in ImGui) + float cos_a = cosf(-angle); + float sin_a = sinf(-angle); + + const char* s = text_begin; + int chars_total = (int)(text_end - s); + int chars_rendered = 0; + const int vtx_count_max = chars_total * 4; + const int idx_count_max = chars_total * 6; + draw_list->PrimReserve(idx_count_max, vtx_count_max); + + // Adjust pen position to center the text + ImVec2 pen = ImVec2(-text_size.x * 0.5f, -text_size.y * 0.5f); + + while (s < text_end) { + unsigned int c = (unsigned int)*s; + if (c < 0x80) { + s += 1; + } else { + s += ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) // Malformed UTF-8? + break; + } + +#ifdef IMGUI_HAS_TEXTURES + const ImFontGlyph* glyph = fontBaked->FindGlyph((ImWchar)c); +#else + const ImFontGlyph* glyph = font->FindGlyph((ImWchar)c); +#endif + if (glyph == nullptr) { + continue; + } + + // Glyph dimensions and positions + ImVec2 glyph_offset = ImVec2(glyph->X0, glyph->Y0) * scale; + ImVec2 glyph_size = ImVec2(glyph->X1 - glyph->X0, glyph->Y1 - glyph->Y0) * scale; + + // Corners of the glyph quad in unrotated space + ImVec2 corners[4]; + corners[0] = pen + glyph_offset; + corners[1] = pen + glyph_offset + ImVec2(glyph_size.x, 0); + corners[2] = pen + glyph_offset + glyph_size; + corners[3] = pen + glyph_offset + ImVec2(0, glyph_size.y); + + // Rotate and translate the corners + for (int i = 0; i < 4; i++) { + float x = corners[i].x; + float y = corners[i].y; + corners[i].x = x * cos_a - y * sin_a + pos.x; + corners[i].y = x * sin_a + y * cos_a + pos.y; + } + + // Texture coordinates + ImVec2 uv0 = ImVec2(glyph->U0, glyph->V0); + ImVec2 uv1 = ImVec2(glyph->U1, glyph->V1); + + // Render the glyph quad + draw_list->PrimQuadUV(corners[0], corners[1], corners[2], corners[3], uv0, ImVec2(glyph->U1, glyph->V0), uv1, ImVec2(glyph->U0, glyph->V1), + col); + + // Advance the pen position + pen.x += glyph->AdvanceX * scale; + + chars_rendered++; + } + + // Return unused vertices + int chars_skipped = chars_total - chars_rendered; + draw_list->PrimUnreserve(chars_skipped * 6, chars_skipped * 4); +} + +void AddTextCentered(ImDrawList* draw_list, ImVec2 top_center, ImU32 col, const char* text_begin) { + const char* text_end = ImGui::FindRenderedTextEnd(text_begin); + ImVec2 text_size = ImGui::CalcTextSize(text_begin, text_end, true); + draw_list->AddText(ImVec2(top_center.x - text_size.x * 0.5f, top_center.y), col, text_begin, text_end); +} + +//----------------------------------------------------------------------------- +// [SECTION] Legend Utils +//----------------------------------------------------------------------------- + +static const char* short_legend_location[9] = {"C", "N", "S", "W", "E", "NW", "NE", "SW", "SE"}; + +static const char* GetShortLegendLocationName(ImPlot3DLocation loc) { + if (loc == ImPlot3DLocation_Center) + return short_legend_location[0]; + if (loc == ImPlot3DLocation_North) + return short_legend_location[1]; + if (loc == ImPlot3DLocation_South) + return short_legend_location[2]; + if (loc == ImPlot3DLocation_West) + return short_legend_location[3]; + if (loc == ImPlot3DLocation_East) + return short_legend_location[4]; + if (loc == ImPlot3DLocation_NorthWest) + return short_legend_location[5]; + if (loc == ImPlot3DLocation_NorthEast) + return short_legend_location[6]; + if (loc == ImPlot3DLocation_SouthWest) + return short_legend_location[7]; + if (loc == ImPlot3DLocation_SouthEast) + return short_legend_location[8]; + return nullptr; +} + +ImVec2 GetLocationPos(const ImRect& outer_rect, const ImVec2& inner_size, ImPlot3DLocation loc, const ImVec2& pad) { + ImVec2 pos; + // Legend x coordinate + if (ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_West) && !ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_East)) + pos.x = outer_rect.Min.x + pad.x; + else if (!ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_West) && ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_East)) + pos.x = outer_rect.Max.x - pad.x - inner_size.x; + else + pos.x = outer_rect.GetCenter().x - inner_size.x * 0.5f; + // Legend y coordinate + if (ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_North) && !ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_South)) + pos.y = outer_rect.Min.y + pad.y; + else if (!ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_North) && ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_South)) + pos.y = outer_rect.Max.y - pad.y - inner_size.y; + else + pos.y = outer_rect.GetCenter().y - inner_size.y * 0.5f; + pos.x = IM_ROUND(pos.x); + pos.y = IM_ROUND(pos.y); + return pos; +} + +ImVec2 CalcLegendSize(ImPlot3DItemGroup& items, const ImVec2& pad, const ImVec2& spacing, bool vertical) { + const int nItems = items.GetLegendCount(); + const float txt_ht = ImGui::GetTextLineHeight(); + const float icon_size = txt_ht; + // Get label max width + float max_label_width = 0; + float sum_label_width = 0; + for (int i = 0; i < nItems; i++) { + const char* label = items.GetLegendLabel(i); + const float label_width = ImGui::CalcTextSize(label, nullptr, true).x; + max_label_width = label_width > max_label_width ? label_width : max_label_width; + sum_label_width += label_width; + } + // Compute legend size + const ImVec2 legend_size = vertical ? ImVec2(pad.x * 2 + icon_size + max_label_width, pad.y * 2 + nItems * txt_ht + (nItems - 1) * spacing.y) + : ImVec2(pad.x * 2 + icon_size * nItems + sum_label_width + (nItems - 1) * spacing.x, pad.y * 2 + txt_ht); + return legend_size; +} + +bool ClampLegendRect(ImRect& legend_rect, const ImRect& outer_rect, const ImVec2& pad) { + bool clamped = false; + ImRect outer_rect_pad(outer_rect.Min + pad, outer_rect.Max - pad); + if (legend_rect.Min.x < outer_rect_pad.Min.x) { + legend_rect.Min.x = outer_rect_pad.Min.x; + clamped = true; + } + if (legend_rect.Min.y < outer_rect_pad.Min.y) { + legend_rect.Min.y = outer_rect_pad.Min.y; + clamped = true; + } + if (legend_rect.Max.x > outer_rect_pad.Max.x) { + legend_rect.Max.x = outer_rect_pad.Max.x; + clamped = true; + } + if (legend_rect.Max.y > outer_rect_pad.Max.y) { + legend_rect.Max.y = outer_rect_pad.Max.y; + clamped = true; + } + return clamped; +} + +void ShowLegendEntries(ImPlot3DItemGroup& items, const ImRect& legend_bb, const ImVec2& pad, const ImVec2& spacing, bool vertical, + ImDrawList& draw_list) { + const float txt_ht = ImGui::GetTextLineHeight(); + const float icon_size = txt_ht; + const float icon_shrink = 2; + ImU32 col_txt = GetStyleColorU32(ImPlot3DCol_LegendText); + ImU32 col_txt_dis = ImAlphaU32(col_txt, 0.25f); + float sum_label_width = 0; + + const int num_items = items.GetLegendCount(); + if (num_items == 0) + return; + + // Render legend items + for (int i = 0; i < num_items; i++) { + const int idx = i; + ImPlot3DItem* item = items.GetLegendItem(idx); + const char* label = items.GetLegendLabel(idx); + const float label_width = ImGui::CalcTextSize(label, nullptr, true).x; + const ImVec2 top_left = vertical ? legend_bb.Min + pad + ImVec2(0, i * (txt_ht + spacing.y)) + : legend_bb.Min + pad + ImVec2(i * (icon_size + spacing.x) + sum_label_width, 0); + sum_label_width += label_width; + ImRect icon_bb; + icon_bb.Min = top_left + ImVec2(icon_shrink, icon_shrink); + icon_bb.Max = top_left + ImVec2(icon_size - icon_shrink, icon_size - icon_shrink); + ImRect label_bb; + label_bb.Min = top_left; + label_bb.Max = top_left + ImVec2(label_width + icon_size, icon_size); + ImU32 col_txt_hl; + ImU32 col_item = ImAlphaU32(item->Color, 1); + + ImRect button_bb(icon_bb.Min, label_bb.Max); + + ImGui::KeepAliveID(item->ID); + + bool item_hov = false; + bool item_hld = false; + bool item_clk = ImPlot3D::ImHasFlag(items.Legend.Flags, ImPlot3DLegendFlags_NoButtons) + ? false + : ImGui::ButtonBehavior(button_bb, item->ID, &item_hov, &item_hld); + + if (item_clk) + item->Show = !item->Show; + + const bool hovering = item_hov && !ImPlot3D::ImHasFlag(items.Legend.Flags, ImPlot3DLegendFlags_NoHighlightItem); + + if (hovering) { + item->LegendHovered = true; + col_txt_hl = ImPlot3D::ImMixU32(col_txt, col_item, 64); + } else { + item->LegendHovered = false; + col_txt_hl = ImGui::GetColorU32(col_txt); + } + + ImU32 col_icon; + if (item_hld) + col_icon = item->Show ? ImAlphaU32(col_item, 0.5f) : ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.5f); + else if (item_hov) + col_icon = item->Show ? ImAlphaU32(col_item, 0.75f) : ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.75f); + else + col_icon = item->Show ? col_item : col_txt_dis; + + draw_list.AddRectFilled(icon_bb.Min, icon_bb.Max, col_icon); + const char* text_display_end = ImGui::FindRenderedTextEnd(label, nullptr); + if (label != text_display_end) + draw_list.AddText(top_left + ImVec2(icon_size, 0), item->Show ? col_txt_hl : col_txt_dis, label, text_display_end); + } +} + +void RenderLegend() { + ImPlot3DContext& gp = *GImPlot3D; + ImPlot3DPlot& plot = *gp.CurrentPlot; + if (ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_NoLegend) || plot.Items.GetLegendCount() == 0) + return; + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImDrawList* draw_list = window->DrawList; + const ImGuiIO& IO = ImGui::GetIO(); + + ImPlot3DLegend& legend = plot.Items.Legend; + const bool legend_horz = ImPlot3D::ImHasFlag(legend.Flags, ImPlot3DLegendFlags_Horizontal); + const ImVec2 legend_size = CalcLegendSize(plot.Items, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !legend_horz); + const ImVec2 legend_pos = GetLocationPos(plot.PlotRect, legend_size, legend.Location, gp.Style.LegendPadding); + legend.Rect = ImRect(legend_pos, legend_pos + legend_size); + legend.RectClamped = legend.Rect; + const bool legend_scrollable = ClampLegendRect(legend.RectClamped, plot.PlotRect, gp.Style.LegendPadding); + + // Test hover (using the clamped rect so off-screen overflow does not register) + // clang-format off + const ImGuiButtonFlags legend_button_flags = ImGuiButtonFlags_AllowOverlap + | ImGuiButtonFlags_PressedOnClick + | ImGuiButtonFlags_PressedOnDoubleClick + | ImGuiButtonFlags_MouseButtonLeft + | ImGuiButtonFlags_MouseButtonRight + | ImGuiButtonFlags_MouseButtonMiddle + | ImGuiButtonFlags_FlattenChildren; + // clang-format on + ImGui::KeepAliveID(plot.Items.ID); + ImGui::ButtonBehavior(legend.RectClamped, plot.Items.ID, &legend.Hovered, &legend.Held, legend_button_flags); + legend.Hovered = legend.Hovered || legend.RectClamped.Contains(IO.MousePos); + + // Handle legend scrolling + if (legend_scrollable) { + if (legend.Hovered) { + ImGui::SetKeyOwner(ImGuiKey_MouseWheelY, plot.Items.ID); + if (IO.MouseWheel != 0.0f) { + ImVec2 max_step = legend.Rect.GetSize() * 0.67f; + float font_size = ImGui::GetFontSize(); + float scroll_step = ImFloor(ImMin(2 * font_size, max_step.x)); + legend.Scroll.x += scroll_step * IO.MouseWheel; + legend.Scroll.y += scroll_step * IO.MouseWheel; + } + } + const ImVec2 min_scroll_offset = legend.RectClamped.GetSize() - legend.Rect.GetSize(); + legend.Scroll.x = ImClamp(legend.Scroll.x, min_scroll_offset.x, 0.0f); + legend.Scroll.y = ImClamp(legend.Scroll.y, min_scroll_offset.y, 0.0f); + const ImVec2 scroll_offset = legend_horz ? ImVec2(legend.Scroll.x, 0) : ImVec2(0, legend.Scroll.y); + ImVec2 legend_offset = legend.RectClamped.Min - legend.Rect.Min + scroll_offset; + legend.Rect.Min += legend_offset; + legend.Rect.Max += legend_offset; + } else { + legend.Scroll = ImVec2(0, 0); + } + + // Render background and entries (clipped to the clamped rect to hide scrolled-off overflow) + ImU32 col_bg = GetStyleColorU32(ImPlot3DCol_LegendBg); + ImU32 col_bd = GetStyleColorU32(ImPlot3DCol_LegendBorder); + ImGui::PushClipRect(legend.RectClamped.Min, legend.RectClamped.Max, true); + draw_list->AddRectFilled(legend.RectClamped.Min, legend.RectClamped.Max, col_bg); + ShowLegendEntries(plot.Items, legend.Rect, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !legend_horz, *draw_list); + draw_list->AddRect(legend.RectClamped.Min, legend.RectClamped.Max, col_bd); + ImGui::PopClipRect(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Mouse Position Utils +//----------------------------------------------------------------------------- + +void RenderMousePos() { + ImPlot3DContext& gp = *GImPlot3D; + ImPlot3DPlot& plot = *gp.CurrentPlot; + if (ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_NoMouseText)) + return; + + ImVec2 mouse_pos = ImGui::GetMousePos(); + ImPlot3DPoint mouse_plot_pos = PixelsToPlotPlane(mouse_pos, ImPlane3D_YZ, true); + if (mouse_plot_pos.IsNaN()) + mouse_plot_pos = PixelsToPlotPlane(mouse_pos, ImPlane3D_XZ, true); + if (mouse_plot_pos.IsNaN()) + mouse_plot_pos = PixelsToPlotPlane(mouse_pos, ImPlane3D_XY, true); + + char buff[IMPLOT3D_LABEL_MAX_SIZE]; + if (!mouse_plot_pos.IsNaN()) { + ImGuiTextBuffer builder; + builder.append("("); + for (int i = 0; i < 3; i++) { + ImPlot3DAxis& axis = plot.Axes[i]; + if (i > 0) + builder.append(", "); + axis.Formatter(mouse_plot_pos[i], buff, IMPLOT3D_LABEL_MAX_SIZE, axis.FormatterData); + builder.append(buff); + } + builder.append(")"); + + const ImVec2 size = ImGui::CalcTextSize(builder.c_str()); + // TODO custom location/padding + const ImVec2 pos = GetLocationPos(plot.PlotRect, size, ImPlot3DLocation_SouthEast, ImVec2(10, 10)); + ImDrawList& draw_list = *ImGui::GetWindowDrawList(); + draw_list.AddText(pos, GetStyleColorU32(ImPlot3DCol_InlayText), builder.c_str()); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Plot Box Utils +//----------------------------------------------------------------------------- + +// Faces of the box (defined by 4 corner indices) +static const int faces[6][4] = { + {0, 3, 7, 4}, // X-min face + {0, 4, 5, 1}, // Y-min face + {0, 1, 2, 3}, // Z-min face + {1, 2, 6, 5}, // X-max face + {3, 7, 6, 2}, // Y-max face + {4, 5, 6, 7}, // Z-max face +}; + +// Edges of the box (defined by 2 corner indices) +static const int edges[12][2] = { + // Bottom face edges + {0, 1}, + {1, 2}, + {2, 3}, + {3, 0}, + // Top face edges + {4, 5}, + {5, 6}, + {6, 7}, + {7, 4}, + // Vertical edges + {0, 4}, + {1, 5}, + {2, 6}, + {3, 7}, +}; + +// Face edges (4 edge indices for each face) +static const int face_edges[6][4] = { + {3, 11, 8, 7}, // X-min face + {0, 8, 4, 9}, // Y-min face + {0, 1, 2, 3}, // Z-min face + {1, 9, 5, 10}, // X-max face + {2, 10, 6, 11}, // Y-max face + {4, 5, 6, 7}, // Z-max face +}; + +// Lookup table for axis_corners based on active_faces (3D plot) +static const int axis_corners_lookup_3d[8][3][2] = { + // Index 0: active_faces = {0, 0, 0} + {{3, 2}, {1, 2}, {1, 5}}, + // Index 1: active_faces = {0, 0, 1} + {{7, 6}, {5, 6}, {1, 5}}, + // Index 2: active_faces = {0, 1, 0} + {{0, 1}, {1, 2}, {2, 6}}, + // Index 3: active_faces = {0, 1, 1} + {{4, 5}, {5, 6}, {2, 6}}, + // Index 4: active_faces = {1, 0, 0} + {{3, 2}, {0, 3}, {0, 4}}, + // Index 5: active_faces = {1, 0, 1} + {{7, 6}, {4, 7}, {0, 4}}, + // Index 6: active_faces = {1, 1, 0} + {{0, 1}, {0, 3}, {3, 7}}, + // Index 7: active_faces = {1, 1, 1} + {{4, 5}, {4, 7}, {3, 7}}, +}; + +// Lookup table for axis_edges based on active_faces (3D plot) +static const int axis_edges_lookup_3d[8][3] = { + // Index 0: active_faces = {0, 0, 0} + {2, 1, 9}, + // Index 1: active_faces = {0, 0, 1} + {6, 5, 9}, + // Index 2: active_faces = {0, 1, 0} + {0, 1, 10}, + // Index 3: active_faces = {0, 1, 1} + {4, 5, 10}, + // Index 4: active_faces = {1, 0, 0} + {2, 3, 8}, + // Index 5: active_faces = {1, 0, 1} + {6, 7, 8}, + // Index 6: active_faces = {1, 1, 0} + {0, 3, 11}, + // Index 7: active_faces = {1, 1, 1} + {4, 7, 11}, +}; + +// Convert the X, Y and Z active_faces array to a integer value representation that can be looked up in axis_corners_lookup_3d +int Active3DFacesToAxisLookupIndex(const bool* active_faces) { + return ((int)active_faces[0] << 2) | ((int)active_faces[1] << 1) | ((int)active_faces[2]); +} + +int GetMouseOverPlane(const bool* active_faces, const ImVec2* corners_pix, int* plane_out = nullptr) { + ImGuiIO& io = ImGui::GetIO(); + ImVec2 mouse_pos = io.MousePos; + if (plane_out) + *plane_out = -1; + + // Check each active face + for (int a = 0; a < 3; a++) { + int face_idx = a + 3 * active_faces[a]; + ImVec2 p0 = corners_pix[faces[face_idx][0]]; + ImVec2 p1 = corners_pix[faces[face_idx][1]]; + ImVec2 p2 = corners_pix[faces[face_idx][2]]; + ImVec2 p3 = corners_pix[faces[face_idx][3]]; + + // Check if the mouse is inside the face's quad (using a triangle check) + if (ImTriangleContainsPoint(p0, p1, p2, mouse_pos) || ImTriangleContainsPoint(p2, p3, p0, mouse_pos)) { + if (plane_out) + *plane_out = a; + return a; // Return the plane index: 0 -> YZ, 1 -> XZ, 2 -> XY + } + } + + return -1; // Not over any active plane +} + +// Check if a point is inside an edge's hover region (a rectangle extending outward from the edge) +bool IsPointInEdgeHoverRegion(const ImVec2& point, const ImVec2& p0, const ImVec2& p1, const ImVec2& outward_dir, float width) { + ImVec2 dir = p1 - p0; + float len = ImSqrt(ImLengthSqr(dir)); + if (len < 0.001f) + return false; + dir = dir / len; + + // Transform point to edge's local coordinate system + ImVec2 local = point - p0; + float along = local.x * dir.x + local.y * dir.y; + float across = local.x * outward_dir.x + local.y * outward_dir.y; + + // Check if within bounds (rectangle extends from edge outward) + return along >= 0 && along <= len && across >= 0 && across <= width; +} + +// Compute the outward direction for an edge (perpendicular, pointing away from box center) +ImVec2 ComputeEdgeOutwardDir(const ImVec2& p0, const ImVec2& p1, const ImVec2& box_center) { + ImVec2 dir = p1 - p0; + float len = ImSqrt(ImLengthSqr(dir)); + if (len < 0.001f) + return ImVec2(0, 0); + dir = dir / len; + + // Perpendicular direction + ImVec2 perp(-dir.y, dir.x); + + // Make sure it points away from box center + ImVec2 edge_center = (p0 + p1) * 0.5f; + ImVec2 to_edge = edge_center - box_center; + if (ImDot(perp, to_edge) < 0) + perp = ImVec2(-perp.x, -perp.y); + + return perp; +} + +// Forward declaration +float ComputeMaxTickLabelExtent(const ImPlot3DAxis& axis); + +// Spacing constants for axis tick labels and axis labels +static const float AXIS_TICK_INNER_PAD = 5.0f; // gap between axis edge and inner edge of tick labels +static const float AXIS_LABEL_PAD = 10.0f; // gap between tick label outer edge and axis label center +static const float AXIS_RECT_MIN_WIDTH = 40.0f; // minimum hover rect width when labels are absent + +// Computes the total outward width of the hover rect for an axis +float ComputeAxisHoverWidth(const ImPlot3DAxis& axis) { + float max_tick_extent = ComputeMaxTickLabelExtent(axis); + float w = 2.0f * max_tick_extent + AXIS_TICK_INNER_PAD; + if (axis.HasLabel()) { + ImVec2 label_size = ImGui::CalcTextSize(axis.GetLabel()); + w += AXIS_LABEL_PAD + label_size.y * 0.5f; + } + return ImMax(w, AXIS_RECT_MIN_WIDTH); +} + +int GetMouseOverAxis(const ImPlot3DPlot& plot, const ImVec2* corners_pix, const int plane_2d, const int axis_corners[3][2], int* edge_out = nullptr) { + ImGuiIO& io = ImGui::GetIO(); + ImVec2 mouse_pos = io.MousePos; + if (edge_out) + *edge_out = -1; + + // Compute box center in screen space (average of all corners) + ImVec2 box_center(0, 0); + for (int i = 0; i < 8; i++) + box_center = box_center + corners_pix[i]; + box_center = box_center * (1.0f / 8.0f); + + // Check each axis for mouse containment in hover rectangle + for (int axis_idx = 0; axis_idx < 3; axis_idx++) { + // In 2D mode, skip the perpendicular axis + if (plane_2d != -1 && axis_idx == plane_2d) + continue; + + int idx0 = axis_corners[axis_idx][0]; + int idx1 = axis_corners[axis_idx][1]; + + // Skip if axis corners are not defined + if (idx0 == -1 || idx1 == -1) + continue; + + // Find the edge index for these two corners + int edge = -1; + for (int e = 0; e < 12; e++) { + if ((edges[e][0] == idx0 && edges[e][1] == idx1) || (edges[e][0] == idx1 && edges[e][1] == idx0)) { + edge = e; + break; + } + } + + if (edge == -1) + continue; + + ImVec2 p0 = corners_pix[idx0]; + ImVec2 p1 = corners_pix[idx1]; + ImVec2 outward_dir = ComputeEdgeOutwardDir(p0, p1, box_center); + float hover_width = ComputeAxisHoverWidth(plot.Axes[axis_idx]); + + // Check if mouse is within the edge's hover region + if (IsPointInEdgeHoverRegion(mouse_pos, p0, p1, outward_dir, hover_width)) { + if (edge_out) + *edge_out = edge; + return axis_idx; + } + } + + return -1; // Not over any axis +} + +void RenderPlotBackground(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImVec2* corners_pix, const bool* active_faces, const int plane_2d, + const int axis_corners[3][2]) { + const ImVec4 col_bg = GetStyleColorVec4(ImPlot3DCol_PlotBg); + const ImVec4 col_bg_hov = col_bg + ImVec4(0.03f, 0.03f, 0.03f, 0.0f); + + int hovered_plane = -1; + if (!plot.Held) { + // If the mouse is not held, highlight plane hovering when mouse over it + hovered_plane = GetMouseOverPlane(active_faces, corners_pix); + if (GetMouseOverAxis(plot, corners_pix, plane_2d, axis_corners) != -1) + hovered_plane = -1; + } else { + // If the mouse is held, highlight the held plane + hovered_plane = plot.HeldPlaneIdx; + } + + for (int a = 0; a < 3; a++) { + int idx[4]; // Corner indices + for (int i = 0; i < 4; i++) + idx[i] = faces[a + 3 * active_faces[a]][i]; + const ImU32 col = ImGui::ColorConvertFloat4ToU32((hovered_plane == a) ? col_bg_hov : col_bg); + draw_list->AddQuadFilled(corners_pix[idx[0]], corners_pix[idx[1]], corners_pix[idx[2]], corners_pix[idx[3]], col); + } +} + +void RenderAxisRects(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImVec2* corners_pix, const bool*, const int plane_2d, + const int axis_corners[3][2]) { + int hovered_axis = GetMouseOverAxis(plot, corners_pix, plane_2d, axis_corners); + + // Compute box center in screen space + ImVec2 box_center(0, 0); + for (int i = 0; i < 8; i++) + box_center = box_center + corners_pix[i]; + box_center = box_center * (1.0f / 8.0f); + + // Render axis hover rectangles + for (int axis_idx = 0; axis_idx < 3; axis_idx++) { + // In 2D mode, skip the perpendicular axis + if (plane_2d != -1 && axis_idx == plane_2d) + continue; + + int idx0 = axis_corners[axis_idx][0]; + int idx1 = axis_corners[axis_idx][1]; + + if (idx0 == -1 || idx1 == -1) + continue; + + const ImPlot3DAxis& axis = plot.Axes[axis_idx]; + ImVec2 p0 = corners_pix[idx0]; + ImVec2 p1 = corners_pix[idx1]; + ImVec2 outward_dir = ComputeEdgeOutwardDir(p0, p1, box_center); + float hover_width = ComputeAxisHoverWidth(axis); + + // Determine color based on state: + // Active only when the drag started on this axis rect (HeldEdgeIdx set), not on a plane or outside. + ImU32 col; + if (axis.Held && plot.HeldEdgeIdx != -1) + col = axis.ColorAct; + else if (axis_idx == hovered_axis && !plot.Held) + col = axis.ColorHov; + else + col = axis.ColorBg; + + // Draw hover rectangle if color is not transparent + if (col != IM_COL32_BLACK_TRANS) { + ImVec2 c0 = p0; + ImVec2 c1 = p0 + outward_dir * hover_width; + ImVec2 c2 = p1 + outward_dir * hover_width; + ImVec2 c3 = p1; + draw_list->AddQuadFilled(c0, c1, c2, c3, col); + } + } +} + +void RenderPlotBorder(ImDrawList* draw_list, const ImPlot3DPlot&, const ImVec2* corners_pix, const bool* active_faces, const int plane_2d) { + // Determine which edges to render (all visible edges) + bool render_edge[12]; + for (int i = 0; i < 12; i++) + render_edge[i] = false; + for (int a = 0; a < 3; a++) { + int face_idx = a + 3 * active_faces[a]; + if (plane_2d != -1 && a != plane_2d) + continue; + for (size_t i = 0; i < 4; i++) + render_edge[face_edges[face_idx][i]] = true; + } + + // Render edge lines (all visible edges) + ImU32 col_bd = GetStyleColorU32(ImPlot3DCol_PlotBorder); + for (int i = 0; i < 12; i++) { + if (render_edge[i]) { + int idx0 = edges[i][0]; + int idx1 = edges[i][1]; + draw_list->AddLine(corners_pix[idx0], corners_pix[idx1], col_bd, 1.0f); + } + } +} + +void RenderGrid(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint* corners, const bool* active_faces, const int plane_2d) { + ImVec4 col_grid = GetStyleColorVec4(ImPlot3DCol_AxisGrid); + ImU32 col_grid_minor = ImGui::GetColorU32(col_grid * ImVec4(1, 1, 1, 0.3f)); + ImU32 col_grid_major = ImGui::GetColorU32(col_grid * ImVec4(1, 1, 1, 0.6f)); + for (int face = 0; face < 3; face++) { + if (plane_2d != -1 && face != plane_2d) + continue; + int face_idx = face + 3 * active_faces[face]; + const ImPlot3DAxis& axis_u = plot.Axes[(face + 1) % 3]; + const ImPlot3DAxis& axis_v = plot.Axes[(face + 2) % 3]; + + // Get the two axes (u and v) that define the face plane + int idx0 = faces[face_idx][0]; + int idx1 = faces[face_idx][1]; + int idx3 = faces[face_idx][3]; + + // Corners of the face in plot space + ImPlot3DPoint p0 = corners[idx0]; + ImPlot3DPoint p1 = corners[idx1]; + ImPlot3DPoint p3 = corners[idx3]; + + // Vectors along the edges + ImPlot3DPoint u_vec = p1 - p0; + ImPlot3DPoint v_vec = p3 - p0; + + // Render grid lines along u axis (axis_u) + if (!ImPlot3D::ImHasFlag(axis_u.Flags, ImPlot3DAxisFlags_NoGridLines)) + for (int t = 0; t < axis_u.Ticker.TickCount(); ++t) { + const ImPlot3DTick& tick = axis_u.Ticker.Ticks[t]; + + // Compute position along u + double t_u = (tick.PlotPos - axis_u.Range.Min) / (axis_u.Range.Max - axis_u.Range.Min); + + // Skip ticks that are out of range + if (t_u < 0.0 || t_u > 1.0) + continue; + + ImPlot3DPoint p_start = p0 + u_vec * t_u; + ImPlot3DPoint p_end = p3 + u_vec * t_u; + + // Convert to pixel coordinates + ImVec2 p_start_pix = PlotToPixels(p_start); + ImVec2 p_end_pix = PlotToPixels(p_end); + + // Get color + ImU32 col_line = tick.Major ? col_grid_major : col_grid_minor; + + // Draw the grid line + draw_list->AddLine(p_start_pix, p_end_pix, col_line); + } + + // Render grid lines along v axis (axis_v) + if (!ImPlot3D::ImHasFlag(axis_v.Flags, ImPlot3DAxisFlags_NoGridLines)) + for (int t = 0; t < axis_v.Ticker.TickCount(); ++t) { + const ImPlot3DTick& tick = axis_v.Ticker.Ticks[t]; + + // Compute position along v + double t_v = (tick.PlotPos - axis_v.Range.Min) / (axis_v.Range.Max - axis_v.Range.Min); + + // Skip ticks that are out of range + if (t_v < 0.0 || t_v > 1.0) + continue; + + ImPlot3DPoint p_start = p0 + v_vec * t_v; + ImPlot3DPoint p_end = p1 + v_vec * t_v; + + // Convert to pixel coordinates + ImVec2 p_start_pix = PlotToPixels(p_start); + ImVec2 p_end_pix = PlotToPixels(p_end); + + // Get color + ImU32 col_line = tick.Major ? col_grid_major : col_grid_minor; + + // Draw the grid line + draw_list->AddLine(p_start_pix, p_end_pix, col_line); + } + } +} + +void RenderTickMarks(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint* corners, const ImVec2* corners_pix, + const int axis_corners[3][2], const int plane_2d) { + ImU32 col_tick = GetStyleColorU32(ImPlot3DCol_AxisTick); + + auto DeterminePlaneForAxis = [&](int axis_idx) { + if (plane_2d != -1) + return plane_2d; + // If no plane chosen (-1), use: + // X or Y axis -> XY plane (2) + // Z axis -> YZ plane (0) + if (axis_idx == 2) + return 1; // Z-axis use XZ plane + else + return 2; // X or Y-axis use XY plane + }; + + for (int a = 0; a < 3; a++) { + const ImPlot3DAxis& axis = plot.Axes[a]; + if (ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_NoTickMarks)) + continue; + + int idx0 = axis_corners[a][0]; + int idx1 = axis_corners[a][1]; + if (idx0 == idx1) // axis not visible or invalid + continue; + + ImPlot3DPoint axis_start = corners[idx0]; + ImPlot3DPoint axis_end = corners[idx1]; + ImPlot3DPoint axis_dir = axis_end - axis_start; + double axis_len = axis_dir.Length(); + if (axis_len < 1e-12) + continue; + axis_dir /= axis_len; + + // Draw axis line + ImVec2 axis_start_pix = corners_pix[idx0]; + ImVec2 axis_end_pix = corners_pix[idx1]; + draw_list->AddLine(axis_start_pix, axis_end_pix, col_tick); + + // Choose plane + int chosen_plane = DeterminePlaneForAxis(a); + + // Project axis_dir onto chosen plane + ImPlot3DPoint proj_dir = axis_dir; + if (chosen_plane == 0) { + // YZ plane: zero out x + proj_dir.x = 0.0f; + } else if (chosen_plane == 1) { + // XZ plane: zero out y + proj_dir.y = 0.0f; + } else if (chosen_plane == 2) { + // XY plane: zero out z + proj_dir.z = 0.0f; + } + + double proj_len = proj_dir.Length(); + if (proj_len < 1e-12) { + // Axis is parallel to plane normal or something degenerate, skip ticks + continue; + } + proj_dir /= proj_len; + + // Rotate 90 degrees in chosen plane + ImPlot3DPoint tick_dir; + if (chosen_plane == 0) { + // YZ plane + // proj_dir=(0,py,pz), rotate 90°: (py,pz) -> (-pz,py) + tick_dir = ImPlot3DPoint(0, -proj_dir.z, proj_dir.y); + } else if (chosen_plane == 1) { + // XZ plane (plane=1) + // proj_dir=(px,0,pz), rotate 90°: (px,pz) -> (-pz,px) + tick_dir = ImPlot3DPoint(-proj_dir.z, 0, proj_dir.x); + } else { + // XY plane + // proj_dir=(px,py,0), rotate by 90°: (px,py) -> (-py,px) + tick_dir = ImPlot3DPoint(-proj_dir.y, proj_dir.x, 0); + } + tick_dir.Normalize(); + + // Tick lengths in NDC units + const double major_size_ndc = 0.06; + const double minor_size_ndc = 0.03; + + for (int t = 0; t < axis.Ticker.TickCount(); ++t) { + const ImPlot3DTick& tick = axis.Ticker.Ticks[t]; + double v = (tick.PlotPos - axis.Range.Min) / (axis.Range.Max - axis.Range.Min); + + // Skip ticks that are out of range + if (v < 0.0 || v > 1.0) + continue; + ImPlot3DPoint tick_pos_ndc = PlotToNDC(axis_start + axis_dir * (v * axis_len)); + + // Half tick on each side of the axis line + double size_tick_ndc = tick.Major ? major_size_ndc : minor_size_ndc; + ImPlot3DPoint half_tick_ndc = tick_dir * (size_tick_ndc * 0.5); + + ImPlot3DPoint T1_ndc = tick_pos_ndc - half_tick_ndc; + ImPlot3DPoint T2_ndc = tick_pos_ndc + half_tick_ndc; + + ImVec2 T1_screen = NDCToPixels(T1_ndc); + ImVec2 T2_screen = NDCToPixels(T2_ndc); + + draw_list->AddLine(T1_screen, T2_screen, col_tick); + } + } +} + +// Computes the maximum extent of tick labels perpendicular to the axis in screen space +float ComputeMaxTickLabelExtent(const ImPlot3DAxis& axis) { + if (ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_NoTickLabels)) + return 0.0f; + + // Tick labels are always rendered perpendicular to the axis (in the outward direction), + // so LabelSize.x (the text advance width) fully contributes to the outward extent. + float max_extent = 0.0f; + for (int t = 0; t < axis.Ticker.TickCount(); ++t) { + const ImPlot3DTick& tick = axis.Ticker.Ticks[t]; + if (!tick.ShowLabel) + continue; + max_extent = ImMax(max_extent, tick.LabelSize.x * 0.5f); + } + + return max_extent; +} + +void RenderTickLabels(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint* corners, const ImVec2* corners_pix, + const int axis_corners[3][2]) { + ImU32 col_tick_txt = GetStyleColorU32(ImPlot3DCol_AxisText); + + for (int a = 0; a < 3; a++) { + const ImPlot3DAxis& axis = plot.Axes[a]; + if (ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_NoTickLabels)) + continue; + + // Corner indices for this axis + int idx0 = axis_corners[a][0]; + int idx1 = axis_corners[a][1]; + + // If normal to the 2D plot, ignore the ticks + if (idx0 == idx1) + continue; + + // Start and end points of the axis in plot and screen space + ImPlot3DPoint axis_start = corners[idx0]; + ImPlot3DPoint axis_dir = corners[idx1] - axis_start; + ImVec2 axis_start_pix = corners_pix[idx0]; + ImVec2 axis_end_pix = corners_pix[idx1]; + + // Screen space axis direction (normalized), needed for text angle + ImVec2 axis_screen_dir = axis_end_pix - axis_start_pix; + float axis_length = ImSqrt(ImLengthSqr(axis_screen_dir)); + axis_screen_dir = (axis_length > 0.0f) ? axis_screen_dir / axis_length : ImVec2(1.0f, 0.0f); + + // Outward perpendicular direction and label offset + ImVec2 outward_dir = ComputeEdgeOutwardDir(axis_start_pix, axis_end_pix, PlotToPixels(plot.RangeCenter())); + float max_tick_extent = ComputeMaxTickLabelExtent(axis); + ImVec2 offset_pix = outward_dir * (max_tick_extent + AXIS_TICK_INNER_PAD); + + // Compute angle perpendicular to axis in screen space + float angle = atan2f(-axis_screen_dir.y, axis_screen_dir.x) + IM_PI * 0.5f; + + // Normalize angle to be between -π and π + if (angle > IM_PI) + angle -= 2 * IM_PI; + if (angle < -IM_PI) + angle += 2 * IM_PI; + + // Adjust angle to keep labels upright + if (angle > IM_PI * 0.5f) + angle -= IM_PI; + if (angle < -IM_PI * 0.5f) + angle += IM_PI; + + // Loop over ticks + for (int t = 0; t < axis.Ticker.TickCount(); ++t) { + const ImPlot3DTick& tick = axis.Ticker.Ticks[t]; + if (!tick.ShowLabel) + continue; + + // Compute position along the axis + double t_axis = (tick.PlotPos - axis.Range.Min) / (axis.Range.Max - axis.Range.Min); + + // Skip ticks that are out of range + if (t_axis < 0.0 || t_axis > 1.0) + continue; + ImPlot3DPoint tick_pos = axis_start + axis_dir * t_axis; + + // Convert to pixel coordinates + ImVec2 tick_pos_pix = PlotToPixels(tick_pos); + + // Get the tick label text + const char* label = axis.Ticker.GetText(tick); + + // Adjust label position by offset + ImVec2 label_pos_pix = tick_pos_pix + offset_pix; + + // Render the tick label + AddTextRotated(draw_list, label_pos_pix, angle, col_tick_txt, label); + } + } +} + +void RenderAxisLabels(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint*, const ImVec2* corners_pix, + const int axis_corners[3][2]) { + ImU32 col_ax_txt = GetStyleColorU32(ImPlot3DCol_AxisText); + + for (int a = 0; a < 3; a++) { + const ImPlot3DAxis& axis = plot.Axes[a]; + if (!axis.HasLabel()) + continue; + + const char* label = axis.GetLabel(); + + // Corner indices + int idx0 = axis_corners[a][0]; + int idx1 = axis_corners[a][1]; + + // If normal to the 2D plot, ignore axis label + if (idx0 == idx1) + continue; + + ImVec2 axis_start_pix = corners_pix[idx0]; + ImVec2 axis_end_pix = corners_pix[idx1]; + + // Screen space axis direction (normalized), needed for text angle + ImVec2 axis_screen_dir = axis_end_pix - axis_start_pix; + float axis_length = ImSqrt(ImLengthSqr(axis_screen_dir)); + axis_screen_dir = (axis_length > 0.0f) ? axis_screen_dir / axis_length : ImVec2(1.0f, 0.0f); + + // Outward perpendicular and total offset: + // tick labels are centered at (max_tick_extent + AXIS_TICK_INNER_PAD) from the axis edge, + // so the axis label sits one more max_tick_extent + AXIS_LABEL_PAD beyond that. + ImVec2 outward_dir = ComputeEdgeOutwardDir(axis_start_pix, axis_end_pix, PlotToPixels(plot.RangeCenter())); + float max_tick_extent = ComputeMaxTickLabelExtent(axis); + float tick_label_center = max_tick_extent + AXIS_TICK_INNER_PAD; + float total_offset = tick_label_center + max_tick_extent + AXIS_LABEL_PAD; + + ImVec2 axis_center_pix = (axis_start_pix + axis_end_pix) * 0.5f; + ImVec2 label_pos_pix = axis_center_pix + outward_dir * total_offset; + + // Compute text angle + float angle = atan2f(-axis_screen_dir.y, axis_screen_dir.x); + if (angle > IM_PI * 0.5f) + angle -= IM_PI; + if (angle < -IM_PI * 0.5f) + angle += IM_PI; + + AddTextRotated(draw_list, label_pos_pix, angle, col_ax_txt, label); + } +} + +// Function to compute active faces based on the rotation +// If the plot is close to 2D, plane_2d is set to the plane index (0 -> YZ, 1 -> XZ, 2 -> XY) +// plane_2d is set to -1 otherwise +void ComputeActiveFaces(bool* active_faces, const ImPlot3DQuat& rotation, const ImPlot3DAxis* axes, int* plane_2d = nullptr) { + if (plane_2d) + *plane_2d = -1; + + ImPlot3DPoint rot_face_n[3] = { + rotation * ImPlot3DPoint(1.0f, 0.0f, 0.0f), + rotation * ImPlot3DPoint(0.0f, 1.0f, 0.0f), + rotation * ImPlot3DPoint(0.0f, 0.0f, 1.0f), + }; + + int num_deg = 0; // Check number of planes that are degenerate (seen as a line) + for (int i = 0; i < 3; i++) { + // Determine the active face based on the Z component + if (fabs(rot_face_n[i].z) < 0.025) { + // If aligned with the plane, choose the min face for bottom/left + active_faces[i] = rot_face_n[i].x + rot_face_n[i].y < 0.0f; + num_deg++; + } else { + // Otherwise, determine based on the Z component + bool is_inverted = ImHasFlag(axes[i].Flags, ImPlot3DAxisFlags_Invert); + active_faces[i] = is_inverted ? (rot_face_n[i].z > 0.0f) : (rot_face_n[i].z < 0.0f); + // Set this plane as possible 2d plane + if (plane_2d) + *plane_2d = i; + } + } + // Only return 2d plane if there are exactly 2 degenerate planes + if (num_deg != 2 && plane_2d) + *plane_2d = -1; +} + +// Function to compute the box corners in plot space +void ComputeBoxCorners(ImPlot3DPoint* corners, const ImPlot3DPoint& range_min, const ImPlot3DPoint& range_max) { + corners[0] = ImPlot3DPoint(range_min.x, range_min.y, range_min.z); // 0 + corners[1] = ImPlot3DPoint(range_max.x, range_min.y, range_min.z); // 1 + corners[2] = ImPlot3DPoint(range_max.x, range_max.y, range_min.z); // 2 + corners[3] = ImPlot3DPoint(range_min.x, range_max.y, range_min.z); // 3 + corners[4] = ImPlot3DPoint(range_min.x, range_min.y, range_max.z); // 4 + corners[5] = ImPlot3DPoint(range_max.x, range_min.y, range_max.z); // 5 + corners[6] = ImPlot3DPoint(range_max.x, range_max.y, range_max.z); // 6 + corners[7] = ImPlot3DPoint(range_min.x, range_max.y, range_max.z); // 7 +} + +// Convert a position in the plot's NDC to pixels +ImVec2 NDCToPixels(const ImPlot3DPlot& plot, const ImPlot3DPoint& point) { + ImVec2 center = plot.PlotRect.GetCenter(); + ImPlot3DPoint point_pix = plot.GetViewScale() * (plot.Rotation * point); + point_pix.y *= -1.0f; // Invert y-axis + point_pix.x += center.x; + point_pix.y += center.y; + + return ImVec2((float)point_pix.x, (float)point_pix.y); +} + +// Convert a position in the plot's coordinate system to the plot's normalized device coordinate system (NDC) +ImPlot3DPoint PlotToNDC(const ImPlot3DPlot& plot, const ImPlot3DPoint& point) { + ImPlot3DPoint ndc_point; + for (int i = 0; i < 3; i++) { + const ImPlot3DAxis& axis = plot.Axes[i]; + // Apply forward transform if needed, then normalize to [0, 1] + double plt = point[i]; + double t; + if (axis.TransformForward != nullptr) { + double s = axis.TransformForward(plt, axis.TransformData); + t = (s - axis.ScaledRange.Min) / (axis.ScaledRange.Max - axis.ScaledRange.Min); + } else { + t = (plt - axis.Range.Min) / (axis.Range.Max - axis.Range.Min); + } + // Convert point to NDC range [-0.5*NDCScale, 0.5*NDCScale] + const double ndc_range = 0.5; + ndc_point[i] = (ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_Invert) ? (ndc_range - t) : (t - ndc_range)) * axis.NDCScale; + } + return ndc_point; +} + +// Convert a position in the plot's coordinate system to pixels +ImVec2 PlotToPixels(const ImPlot3DPlot& plot, const ImPlot3DPoint& point) { return NDCToPixels(plot, PlotToNDC(plot, point)); } + +// Function to compute the box corners in pixel space +void ComputeBoxCornersPix(const ImPlot3DPlot& plot, ImVec2* corners_pix, const ImPlot3DPoint* corners) { + for (int i = 0; i < 8; i++) { + corners_pix[i] = PlotToPixels(plot, corners[i]); + } +} + +// Function to get axes parameters which can then be used later down the line +void GetAxesParameters(const ImPlot3DPlot& plot, bool* active_faces, ImVec2* corners_pix, ImPlot3DPoint* corners, int& plane_2d, + int axis_corners[3][2]) { + // Get plot parameters + const ImPlot3DQuat& rotation = plot.Rotation; + ImPlot3DPoint range_min = plot.RangeMin(); + ImPlot3DPoint range_max = plot.RangeMax(); + + // Compute active faces + ComputeActiveFaces(active_faces, rotation, plot.Axes, &plane_2d); + bool is_2d = plane_2d != -1; + + // Compute box corners in plot space + ComputeBoxCorners(corners, range_min, range_max); + + // Compute box corners in pixel space + ComputeBoxCornersPix(plot, corners_pix, corners); + + // Compute axes start and end corners (given current rotation) + if (is_2d) { + int face = plane_2d + 3 * active_faces[plane_2d]; // Face of the 2D plot + int common_edges[2] = {-1, -1}; // Edges shared by the 3 faces + + // Find the common edges between the 3 faces + for (int i = 0; i < 4; i++) { + int edge = face_edges[face][i]; + for (int j = 0; j < 2; j++) { + int axis = (plane_2d + 1 + j) % 3; + int face_idx = axis + active_faces[axis] * 3; + for (int k = 0; k < 4; k++) { + if (face_edges[face_idx][k] == edge) { + common_edges[j] = edge; + break; + } + } + } + } + + // Get corners from 2 edges (origin is the corner in common) + int origin_corner = -1; + int x_corner = -1; + int y_corner = -1; + for (int i = 0; i < 2; i++) + for (int j = 0; j < 2; j++) + if (edges[common_edges[0]][i] == edges[common_edges[1]][j]) { + origin_corner = edges[common_edges[0]][i]; + x_corner = edges[common_edges[0]][!i]; + y_corner = edges[common_edges[1]][!j]; + } + + // Swap x and y if they are flipped + ImVec2 x_vec = corners_pix[x_corner] - corners_pix[origin_corner]; + ImVec2 y_vec = corners_pix[y_corner] - corners_pix[origin_corner]; + if (y_vec.x > x_vec.x) + ImSwap(x_corner, y_corner); + + // Check which 3d axis the 2d axis refers to + ImPlot3DPoint origin_3d = corners[origin_corner]; + ImPlot3DPoint x_3d = (corners[x_corner] - origin_3d).Normalized(); + ImPlot3DPoint y_3d = (corners[y_corner] - origin_3d).Normalized(); + int x_axis = -1; + bool x_inverted = false; + int y_axis = -1; + bool y_inverted = false; + for (int i = 0; i < 2; i++) { + int axis_i = (plane_2d + 1 + i) % 3; + if (y_axis != -1 || (ImAbs(x_3d[axis_i]) > 1e-8f && x_axis == -1)) { + x_axis = axis_i; + x_inverted = x_3d[axis_i] < 0.0f; + } else { + y_axis = axis_i; + y_inverted = y_3d[axis_i] < 0.0f; + } + } + + // Set the 3d axis corners based on the 2d axis corners + axis_corners[plane_2d][0] = -1; + axis_corners[plane_2d][1] = -1; + if (x_inverted) { + axis_corners[x_axis][0] = x_corner; + axis_corners[x_axis][1] = origin_corner; + } else { + axis_corners[x_axis][0] = origin_corner; + axis_corners[x_axis][1] = x_corner; + } + if (y_inverted) { + axis_corners[y_axis][0] = y_corner; + axis_corners[y_axis][1] = origin_corner; + } else { + axis_corners[y_axis][0] = origin_corner; + axis_corners[y_axis][1] = y_corner; + } + } else { + int index = Active3DFacesToAxisLookupIndex(active_faces); + for (int a = 0; a < 3; a++) { + axis_corners[a][0] = axis_corners_lookup_3d[index][a][0]; + axis_corners[a][1] = axis_corners_lookup_3d[index][a][1]; + } + } +} + +void RenderPlotBox(ImDrawList* draw_list, const ImPlot3DPlot& plot) { + bool active_faces[3]; + ImVec2 corners_pix[8]; + ImPlot3DPoint corners[8]; + int plane_2d; + int axis_corners[3][2]; + + GetAxesParameters(plot, active_faces, corners_pix, corners, plane_2d, axis_corners); + + // Render components + RenderPlotBackground(draw_list, plot, corners_pix, active_faces, plane_2d, axis_corners); + RenderAxisRects(draw_list, plot, corners_pix, active_faces, plane_2d, axis_corners); + RenderPlotBorder(draw_list, plot, corners_pix, active_faces, plane_2d); + RenderGrid(draw_list, plot, corners, active_faces, plane_2d); + RenderTickMarks(draw_list, plot, corners, corners_pix, axis_corners, plane_2d); + RenderTickLabels(draw_list, plot, corners, corners_pix, axis_corners); + RenderAxisLabels(draw_list, plot, corners, corners_pix, axis_corners); +} + +//----------------------------------------------------------------------------- +// [SECTION] Formatter +//----------------------------------------------------------------------------- + +int Formatter_Default(double value, char* buff, int size, void* data) { + char* fmt = (char*)data; + return ImFormatString(buff, size, fmt, value); +} + +//------------------------------------------------------------------------------ +// [SECTION] Locator +//------------------------------------------------------------------------------ + +double NiceNum(double x, bool round) { + double f; + double nf; + int expv = (int)floor(ImLog10(x)); + f = x / ImPow(10.0, (double)expv); + if (round) + if (f < 1.5) + nf = 1; + else if (f < 3) + nf = 2; + else if (f < 7) + nf = 5; + else + nf = 10; + else if (f <= 1) + nf = 1; + else if (f <= 2) + nf = 2; + else if (f <= 5) + nf = 5; + else + nf = 10; + return nf * ImPow(10.0, expv); +} + +void Locator_Default(ImPlot3DTicker& ticker, const ImPlot3DRange& range, float pixels, ImPlot3DFormatter formatter, void* formatter_data) { + if (range.Min == range.Max) + return; + const int nMinor = ImMin(ImMax(1, (int)IM_ROUND(pixels / 30.0f)), 5); + const int nMajor = ImMax(2, (int)IM_ROUND(pixels / 80.0f)); + const int max_ticks_labels = 7; + const double nice_range = NiceNum(range.Size() * 0.99, false); + const double interval = NiceNum(nice_range / (nMajor - 1), true); + const double graphmin = floor(range.Min / interval) * interval; + const double graphmax = ceil(range.Max / interval) * interval; + bool first_major_set = false; + int first_major_idx = 0; + const int idx0 = ticker.TickCount(); // Ticker may have user custom ticks + for (double major = graphmin; major < graphmax + 0.5 * interval; major += interval) { + // Is this zero? combat zero formatting issues + if (major - interval < 0 && major + interval > 0) + major = 0; + if (range.Contains(major)) { + if (!first_major_set) { + first_major_idx = ticker.TickCount(); + first_major_set = true; + } + ticker.AddTick(major, true, true, formatter, formatter_data); + } + for (int i = 1; i < nMinor; i++) { + double minor = major + i * interval / nMinor; + if (range.Contains(minor)) { + ticker.AddTick(minor, false, true, formatter, formatter_data); + } + } + } + + // Prune tick labels + if (ticker.TickCount() > max_ticks_labels) { + for (int i = first_major_idx - 1; i >= idx0; i -= 2) + ticker.Ticks[i].ShowLabel = false; + for (int i = first_major_idx + 1; i < ticker.TickCount(); i += 2) + ticker.Ticks[i].ShowLabel = false; + } +} + +bool CalcLogarithmicExponents(const ImPlot3DRange& range, float pix, int& exp_min, int& exp_max, int& exp_step) { + if (range.Min * range.Max > 0) { + const int nMajor = ImMax(2, (int)IM_ROUND(pix * 0.01f)); // TODO: magic numbers + double log_min = ImLog10(ImAbs(range.Min)); + double log_max = ImLog10(ImAbs(range.Max)); + double log_a = ImMin(log_min, log_max); + double log_b = ImMax(log_min, log_max); + exp_step = ImMax(1, (int)(log_b - log_a) / nMajor); + exp_min = (int)log_a; + exp_max = (int)log_b; + if (exp_step != 1) { + while (exp_step % 3 != 0) + exp_step++; // make step size multiple of three + while (exp_min % exp_step != 0) + exp_min--; // decrease exp_min until exp_min + N * exp_step will be 0 + } + return true; + } + return false; +} + +void AddTicksLogarithmic(const ImPlot3DRange& range, int exp_min, int exp_max, int exp_step, ImPlot3DTicker& ticker, ImPlot3DFormatter formatter, + void* data) { + const double sign = ImSign(range.Max); + for (int e = exp_min - exp_step; e < (exp_max + exp_step); e += exp_step) { + double major1 = sign * ImPow(10, (double)(e)); + double major2 = sign * ImPow(10, (double)(e + 1)); + double interval = (major2 - major1) / 9; + if (major1 >= (range.Min - DBL_EPSILON) && major1 <= (range.Max + DBL_EPSILON)) + ticker.AddTick(major1, true, true, formatter, data); + for (int j = 0; j < exp_step; ++j) { + major1 = sign * ImPow(10, (double)(e + j)); + major2 = sign * ImPow(10, (double)(e + j + 1)); + interval = (major2 - major1) / 9; + for (int i = 1; i < (9 + (int)(j < (exp_step - 1))); ++i) { + double minor = major1 + i * interval; + if (minor >= (range.Min - DBL_EPSILON) && minor <= (range.Max + DBL_EPSILON)) + ticker.AddTick(minor, false, false, formatter, data); + } + } + } +} + +void Locator_Log10(ImPlot3DTicker& ticker, const ImPlot3DRange& range, float pixels, ImPlot3DFormatter formatter, void* formatter_data) { + int exp_min, exp_max, exp_step; + if (CalcLogarithmicExponents(range, pixels, exp_min, exp_max, exp_step)) + AddTicksLogarithmic(range, exp_min, exp_max, exp_step, ticker, formatter, formatter_data); +} + +float CalcSymLogPixel(double plt, const ImPlot3DRange& range, float pixels) { + double scaleToPixels = pixels / range.Size(); + double scaleMin = TransformForward_SymLog(range.Min, nullptr); + double scaleMax = TransformForward_SymLog(range.Max, nullptr); + double s = TransformForward_SymLog(plt, nullptr); + double t = (s - scaleMin) / (scaleMax - scaleMin); + plt = range.Min + range.Size() * t; + + return (float)(0 + scaleToPixels * (plt - range.Min)); +} + +void Locator_SymLog(ImPlot3DTicker& ticker, const ImPlot3DRange& range, float pixels, ImPlot3DFormatter formatter, void* formatter_data) { + if (range.Min >= -1 && range.Max <= 1) + Locator_Default(ticker, range, pixels, formatter, formatter_data); + else if (range.Min * range.Max < 0) { // cross zero + const float pix_min = 0; + const float pix_max = pixels; + const float pix_p1 = CalcSymLogPixel(1, range, pixels); + const float pix_n1 = CalcSymLogPixel(-1, range, pixels); + int exp_min_p, exp_max_p, exp_step_p; + int exp_min_n, exp_max_n, exp_step_n; + CalcLogarithmicExponents(ImPlot3DRange(1, range.Max), ImAbs(pix_max - pix_p1), exp_min_p, exp_max_p, exp_step_p); + CalcLogarithmicExponents(ImPlot3DRange(range.Min, -1), ImAbs(pix_n1 - pix_min), exp_min_n, exp_max_n, exp_step_n); + int exp_step = ImMax(exp_step_n, exp_step_p); + ticker.AddTick(0, true, true, formatter, formatter_data); + AddTicksLogarithmic(ImPlot3DRange(1, range.Max), exp_min_p, exp_max_p, exp_step, ticker, formatter, formatter_data); + AddTicksLogarithmic(ImPlot3DRange(range.Min, -1), exp_min_n, exp_max_n, exp_step, ticker, formatter, formatter_data); + } else { + Locator_Log10(ticker, range, pixels, formatter, formatter_data); + } +} + +void AddTicksCustom(const double* values, const char* const labels[], int n, ImPlot3DTicker& ticker, ImPlot3DFormatter formatter, void* data) { + for (int i = 0; i < n; i++) { + if (labels != nullptr) + ticker.AddTick(values[i], false, true, labels[i]); + else + ticker.AddTick(values[i], false, true, formatter, data); + } +} + +//------------------------------------------------------------------------------ +// [SECTION] Context Menus +//------------------------------------------------------------------------------ + +static const char* axis_contexts[3] = {"##XAxisContext", "##YAxisContext", "##ZAxisContext"}; +static const char* axis_labels[3] = {"X-Axis", "Y-Axis", "Z-Axis"}; +static const char* plane_contexts[3] = {"##YZPlaneContext", "##XZPlaneContext", "##XYPlaneContext"}; +static const char* plane_labels[3] = {"YZ-Plane", "XZ-Plane", "XY-Plane"}; + +bool ShowLegendContextMenu(ImPlot3DLegend& legend, bool visible) { + const float s = ImGui::GetFrameHeight(); + bool ret = false; + if (ImGui::Checkbox("Show", &visible)) + ret = true; + if (ImGui::RadioButton("H", ImPlot3D::ImHasFlag(legend.Flags, ImPlot3DLegendFlags_Horizontal))) + legend.Flags |= ImPlot3DLegendFlags_Horizontal; + ImGui::SameLine(); + if (ImGui::RadioButton("V", !ImPlot3D::ImHasFlag(legend.Flags, ImPlot3DLegendFlags_Horizontal))) + legend.Flags &= ~ImPlot3DLegendFlags_Horizontal; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 2)); + // clang-format off + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_NorthWest),ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_NorthWest; } ImGui::SameLine(); + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_North) , ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_North; } ImGui::SameLine(); + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_NorthEast), ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_NorthEast; } + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_West), ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_West; } ImGui::SameLine(); + if (ImGui::InvisibleButton(GetShortLegendLocationName(ImPlot3DLocation_Center), ImVec2(1.5f*s,s))) { } ImGui::SameLine(); + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_East), ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_East; } + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_SouthWest),ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_SouthWest; } ImGui::SameLine(); + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_South), ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_South; } ImGui::SameLine(); + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_SouthEast),ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_SouthEast; } + // clang-format on + ImGui::PopStyleVar(); + return ret; +} + +void ShowAxisContextMenu(ImPlot3DPlot& plot, ImAxis3D axis_id) { + ImGui::PushItemWidth(75); + ImPlot3DAxis& axis = plot.Axes[axis_id]; + bool always_locked = axis.IsRangeLocked() || axis.IsAutoFitting(); + bool label = axis.HasLabel(); + bool grid = axis.HasGridLines(); + bool ticks = axis.HasTickMarks(); + bool labels = axis.HasTickLabels(); + double drag_speed = + (axis.Range.Size() <= DBL_EPSILON) ? DBL_EPSILON * 1.0e+13 : 0.01 * axis.Range.Size(); // Recover from almost equal axis limits + const bool equal_aspect = ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_Equal); + + ImGui::BeginDisabled(always_locked); + ImGui::CheckboxFlags("##LockMin", (unsigned int*)&axis.Flags, ImPlot3DAxisFlags_LockMin); + ImGui::EndDisabled(); + ImGui::SameLine(); + + ImGui::BeginDisabled(axis.IsLockedMin() || always_locked); + double temp_min = axis.Range.Min; + if (ImGui::DragScalar("Min", ImGuiDataType_Double, &temp_min, (float)drag_speed, &axis.ConstraintRange.Min, &axis.Range.Max)) { + axis.SetMin(temp_min, true); + // Apply equal aspect if needed + if (equal_aspect) + plot.ApplyEqualAspect(axis_id); + } + ImGui::EndDisabled(); + + ImGui::BeginDisabled(always_locked); + ImGui::CheckboxFlags("##LockMax", (unsigned int*)&axis.Flags, ImPlot3DAxisFlags_LockMax); + ImGui::EndDisabled(); + ImGui::SameLine(); + ImGui::BeginDisabled(axis.IsLockedMax() || always_locked); + double temp_max = axis.Range.Max; + if (ImGui::DragScalar("Max", ImGuiDataType_Double, &temp_max, (float)drag_speed, &axis.Range.Min, &axis.ConstraintRange.Max)) { + axis.SetMax(temp_max, true); + // Apply equal aspect if needed + if (equal_aspect) + plot.ApplyEqualAspect(axis_id); + } + ImGui::EndDisabled(); + + ImGui::Separator(); + + // Flags + ImGui::CheckboxFlags("Auto-Fit", (unsigned int*)&axis.Flags, ImPlot3DAxisFlags_AutoFit); + ImGui::Separator(); + + bool inverted = ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_Invert); + if (ImGui::Checkbox("Invert", &inverted)) + ImFlipFlag(axis.Flags, ImPlot3DAxisFlags_Invert); + + ImGui::Separator(); + + ImGui::BeginDisabled(axis.Label.empty()); + if (ImGui::Checkbox("Label", &label)) + ImFlipFlag(axis.Flags, ImPlot3DAxisFlags_NoLabel); + ImGui::EndDisabled(); + + if (ImGui::Checkbox("Grid Lines", &grid)) + ImFlipFlag(axis.Flags, ImPlot3DAxisFlags_NoGridLines); + if (ImGui::Checkbox("Tick Marks", &ticks)) + ImFlipFlag(axis.Flags, ImPlot3DAxisFlags_NoTickMarks); + if (ImGui::Checkbox("Tick Labels", &labels)) + ImFlipFlag(axis.Flags, ImPlot3DAxisFlags_NoTickLabels); +} + +void ShowPlaneContextMenu(ImPlot3DPlot& plot, int plane_idx) { + for (int i = 0; i < 3; i++) { + if (i == plane_idx) + continue; + ImPlot3DAxis& axis = plot.Axes[i]; + ImGui::PushID(i); + if (ImGui::BeginMenu(axis.HasLabel() ? axis.GetLabel() : axis_labels[i])) { + ShowAxisContextMenu(plot, i); + ImGui::EndMenu(); + } + ImGui::PopID(); + } +} + +void ShowPlotContextMenu(ImPlot3DPlot& plot) { + char buf[16] = {}; + for (int i = 0; i < 3; i++) { + ImPlot3DAxis& axis = plot.Axes[i]; + ImGui::PushID(i); + ImFormatString(buf, sizeof(buf) - 1, i == 0 ? "X-Axis" : "X-Axis %d", i + 1); + if (ImGui::BeginMenu(axis.HasLabel() ? axis.GetLabel() : axis_labels[i])) { + ShowAxisContextMenu(plot, i); + ImGui::EndMenu(); + } + ImGui::PopID(); + } + + ImGui::Separator(); + + if ((ImGui::BeginMenu("Box"))) { + ImGui::PushItemWidth(75); + float temp_scale[3] = {(float)plot.Axes[0].NDCScale, (float)plot.Axes[1].NDCScale, (float)plot.Axes[2].NDCScale}; + if (ImGui::DragFloat("Scale X", &temp_scale[0], 0.01f, 0.1f, 3.0f)) + plot.Axes[0].NDCScale = ImMax(temp_scale[0], 0.01f); + if (ImGui::DragFloat("Scale Y", &temp_scale[1], 0.01f, 0.1f, 3.0f)) + plot.Axes[1].NDCScale = ImMax(temp_scale[1], 0.01f); + if (ImGui::DragFloat("Scale Z", &temp_scale[2], 0.01f, 0.1f, 3.0f)) + plot.Axes[2].NDCScale = ImMax(temp_scale[2], 0.01f); + ImGui::PopItemWidth(); + ImGui::EndMenu(); + } + + ImGui::Separator(); + + if ((ImGui::BeginMenu("Legend"))) { + if (ShowLegendContextMenu(plot.Items.Legend, !ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_NoLegend))) + ImFlipFlag(plot.Flags, ImPlot3DFlags_NoLegend); + ImGui::EndMenu(); + } + + if ((ImGui::BeginMenu("Settings"))) { + if (ImGui::MenuItem("Equal", nullptr, ImHasFlag(plot.Flags, ImPlot3DFlags_Equal))) + ImFlipFlag(plot.Flags, ImPlot3DFlags_Equal); + ImGui::BeginDisabled(plot.Title.empty()); + if (ImGui::MenuItem("Title", nullptr, plot.HasTitle())) + ImFlipFlag(plot.Flags, ImPlot3DFlags_NoTitle); + ImGui::EndDisabled(); + if (ImGui::MenuItem("Clip", nullptr, !ImHasFlag(plot.Flags, ImPlot3DFlags_NoClip))) + ImFlipFlag(plot.Flags, ImPlot3DFlags_NoClip); + if (ImGui::MenuItem("Mouse Position", nullptr, !ImHasFlag(plot.Flags, ImPlot3DFlags_NoMouseText))) + ImFlipFlag(plot.Flags, ImPlot3DFlags_NoMouseText); + ImGui::EndMenu(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Begin/End Plot +//----------------------------------------------------------------------------- + +bool BeginPlot(const char* title_id, const ImVec2& size, ImPlot3DFlags flags) { + IMPLOT3D_CHECK_CTX(); + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot == nullptr, "Mismatched BeginPlot()/EndPlot()!"); + + // Get window + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + // Skip if needed + if (window->SkipItems) + return false; + + // Get or create plot + const ImGuiID ID = window->GetID(title_id); + const bool just_created = gp.Plots.GetByKey(ID) == nullptr; + gp.CurrentPlot = gp.Plots.GetOrAddByKey(ID); + gp.CurrentItems = &gp.CurrentPlot->Items; + ImPlot3DPlot& plot = *gp.CurrentPlot; + + // Populate plot + plot.ID = ID; + plot.Items.ID = ID - 1; + plot.JustCreated = just_created; + if (just_created) { + plot.Rotation = plot.InitialRotation; + plot.FitThisFrame = true; + for (int i = 0; i < 3; i++) { + plot.Axes[i] = ImPlot3DAxis(); + plot.Axes[i].FitThisFrame = true; + } + } + if (plot.PreviousFlags != flags) + plot.Flags = flags; + plot.PreviousFlags = flags; + plot.SetupLocked = false; + plot.OpenContextThisFrame = false; + plot.RotationCond = ImPlot3DCond_None; + + // Populate title + plot.SetTitle(title_id); + + // Calculate frame size + ImVec2 frame_size = ImGui::CalcItemSize(size, gp.Style.PlotDefaultSize.x, gp.Style.PlotDefaultSize.y); + if (frame_size.x < gp.Style.PlotMinSize.x && size.x < 0.0f) + frame_size.x = gp.Style.PlotMinSize.x; + if (frame_size.y < gp.Style.PlotMinSize.y && size.y < 0.0f) + frame_size.y = gp.Style.PlotMinSize.y; + + // Create plot ImGui item + plot.FrameRect = ImRect(window->DC.CursorPos, window->DC.CursorPos + frame_size); + ImGui::ItemSize(plot.FrameRect); + if (!ImGui::ItemAdd(plot.FrameRect, plot.ID, &plot.FrameRect)) { + gp.CurrentPlot = nullptr; + gp.CurrentItems = nullptr; + gp.CurrentItem = nullptr; + return false; + } + + // Reset legend + plot.Items.Legend.Reset(); + + // Reset axes + for (int i = 0; i < ImAxis3D_COUNT; i++) + plot.Axes[i].Reset(); + + // Push frame rect clipping + ImGui::PushClipRect(plot.FrameRect.Min, plot.FrameRect.Max, true); + plot.DrawList._Flags = window->DrawList->Flags; + plot.DrawList._SharedData = ImGui::GetDrawListSharedData(); + + return true; +} + +void EndPlot() { + IMPLOT3D_CHECK_CTX(); + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "Mismatched BeginPlot()/EndPlot()!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + + // Move triangles from 3D draw list to ImGui draw list + plot.DrawList.SortedMoveToImGuiDrawList(); + + // Handle data fitting + if (plot.FitThisFrame) { + plot.FitThisFrame = false; + + const bool axis_equal = ImHasFlag(plot.Flags, ImPlot3DFlags_Equal); + if (!axis_equal) { + // Apply fit to all axes independently + for (int i = 0; i < 3; i++) { + if (plot.Axes[i].FitThisFrame) { + plot.Axes[i].FitThisFrame = false; + plot.Axes[i].ApplyFit(); + } + } + } else { + // Find the fitted axis with the highest aspect ratio (units per NDC unit) after fit + // This axis will require the most space and should be used as reference + ImAxis3D ref_axis = ImAxis3D_X; + double max_aspect = 0.0; + + // First, apply fit to all axes + for (int i = 0; i < 3; i++) { + if (plot.Axes[i].FitThisFrame) { + plot.Axes[i].FitThisFrame = false; + plot.Axes[i].ApplyFit(); + + // Get aspect ratio for this axis + double aspect = plot.Axes[i].GetAspect(); + if (aspect > max_aspect) { + max_aspect = aspect; + ref_axis = (ImAxis3D)i; + } + } + } + + // Then, apply equal aspect constraint if enabled + // This ensures data remains centered and visible + plot.ApplyEqualAspect(ref_axis); + } + } + + // Lock setup if not already done + SetupLock(); + + // Pop plot rect clipping + ImGui::PopClipRect(); + + // Reset legend hover + plot.Items.Legend.Hovered = false; + + // Render legend + RenderLegend(); + + // Render mouse position + RenderMousePos(); + + // Legend context menu + if (ImGui::BeginPopup("##LegendContext")) { + ImGui::Text("Legend"); + ImGui::Separator(); + if (ShowLegendContextMenu(plot.Items.Legend, !ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_NoLegend))) + ImFlipFlag(plot.Flags, ImPlot3DFlags_NoLegend); + ImGui::EndPopup(); + } + + // Axis context menus + for (int i = 0; i < 3; i++) { + ImPlot3DAxis& axis = plot.Axes[i]; + if (ImGui::BeginPopup(axis_contexts[i])) { + ImGui::Text(axis.HasLabel() ? axis.GetLabel() : "%c-Axis", 'X' + i); + ImGui::Separator(); + ShowAxisContextMenu(plot, i); + ImGui::EndPopup(); + } + } + + // Plane context menus + for (int i = 0; i < 3; i++) { + if (ImGui::BeginPopup(plane_contexts[i])) { + ImGui::Text("%s", plane_labels[i]); + ImGui::Separator(); + ShowPlaneContextMenu(plot, i); + ImGui::EndPopup(); + } + } + + // Plot context menu + if (ImGui::BeginPopup("##PlotContext")) { + ShowPlotContextMenu(plot); + ImGui::EndPopup(); + } + + // Pop frame rect clipping + ImGui::PopClipRect(); + + // Reset current plot + gp.CurrentPlot = nullptr; + gp.CurrentItems = nullptr; + gp.CurrentItem = nullptr; + + // Reset the plot items for the next frame + for (int i = 0; i < plot.Items.GetItemCount(); i++) + plot.Items.GetItemByIndex(i)->SeenThisFrame = false; +} + +//----------------------------------------------------------------------------- +// [SECTION] Setup +//----------------------------------------------------------------------------- + +static const float ANIMATION_ANGULAR_VELOCITY = 2 * 3.1415f; + +float CalcAnimationTime(ImPlot3DQuat q0, ImPlot3DQuat q1) { + // Compute the angular distance between orientations + double dot_product = ImClamp(q0.Dot(q1), -1.0, 1.0); + float angle = 2.0f * acosf(fabsf((float)dot_product)); + + // Calculate animation time for constant the angular velocity + return angle / ANIMATION_ANGULAR_VELOCITY; +} + +void SetupAxis(ImAxis3D idx, const char* label, ImPlot3DAxisFlags flags) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "SetupAxis() needs to be called after BeginPlot() and before any setup locking functions (e.g. PlotX)!"); + + // Get plot and axis + ImPlot3DPlot& plot = *gp.CurrentPlot; + ImPlot3DAxis& axis = plot.Axes[idx]; + if (axis.PreviousFlags != flags) + axis.Flags = flags; + axis.PreviousFlags = flags; + axis.SetLabel(label); +} + +void SetupAxisLimits(ImAxis3D idx, double min_lim, double max_lim, ImPlot3DCond cond) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "SetupAxisLimits() needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + ImPlot3DAxis& axis = plot.Axes[idx]; + if (!plot.Initialized || cond == ImPlot3DCond_Always) { + axis.SetRange(min_lim, max_lim); + axis.RangeCond = cond; + axis.FitThisFrame = false; + // Apply equal aspect ratio constraint if needed + if (ImHasFlag(plot.Flags, ImPlot3DFlags_Equal)) + plot.ApplyEqualAspect(idx); + } +} + +void SetupAxisFormat(ImAxis3D idx, ImPlot3DFormatter formatter, void* data) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + ImPlot3DAxis& axis = plot.Axes[idx]; + axis.Formatter = formatter; + axis.FormatterData = data; +} + +void SetupAxisTicks(ImAxis3D idx, const double* values, int n_ticks, const char* const labels[], bool keep_default) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + ImPlot3DAxis& axis = plot.Axes[idx]; + axis.ShowDefaultTicks = keep_default; + AddTicksCustom(values, labels, n_ticks, axis.Ticker, axis.Formatter ? axis.Formatter : Formatter_Default, + (axis.Formatter && axis.FormatterData) ? axis.FormatterData : (void*)IMPLOT3D_LABEL_FORMAT); +} + +void SetupAxisTicks(ImAxis3D idx, double v_min, double v_max, int n_ticks, const char* const labels[], bool keep_default) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); + n_ticks = n_ticks < 2 ? 2 : n_ticks; + ImVector temp; + FillRange(temp, n_ticks, v_min, v_max); + SetupAxisTicks(idx, temp.Data, n_ticks, labels, keep_default); +} + +void SetupAxisScale(ImAxis3D idx, ImPlot3DScale scale) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + ImPlot3DAxis& axis = plot.Axes[idx]; + axis.Scale = scale; + switch (scale) { + case ImPlot3DScale_Log10: + axis.TransformForward = TransformForward_Log10; + axis.TransformInverse = TransformInverse_Log10; + axis.TransformData = nullptr; + axis.Locator = Locator_Log10; + axis.ConstraintRange = ImPlot3DRange(FLT_MIN, INFINITY); + break; + case ImPlot3DScale_SymLog: + axis.TransformForward = TransformForward_SymLog; + axis.TransformInverse = TransformInverse_SymLog; + axis.TransformData = nullptr; + axis.Locator = Locator_SymLog; + axis.ConstraintRange = ImPlot3DRange(-INFINITY, INFINITY); + break; + default: + axis.TransformForward = nullptr; + axis.TransformInverse = nullptr; + axis.TransformData = nullptr; + axis.Locator = nullptr; + axis.ConstraintRange = ImPlot3DRange(-INFINITY, INFINITY); + break; + } +} + +void SetupAxisScale(ImAxis3D idx, ImPlot3DTransform forward, ImPlot3DTransform inverse, void* data) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + ImPlot3DAxis& axis = plot.Axes[idx]; + axis.Scale = IMPLOT3D_AUTO; + axis.TransformForward = forward; + axis.TransformInverse = inverse; + axis.TransformData = data; +} + +void SetupAxisLimitsConstraints(ImAxis3D idx, double v_min, double v_max) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + ImPlot3DAxis& axis = plot.Axes[idx]; + axis.ConstraintRange.Min = v_min; + axis.ConstraintRange.Max = v_max; +} + +void SetupAxisZoomConstraints(ImAxis3D idx, double zoom_min, double zoom_max) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + ImPlot3DAxis& axis = plot.Axes[idx]; + axis.ConstraintZoom.Min = zoom_min; + axis.ConstraintZoom.Max = zoom_max; +} + +void SetupAxes(const char* x_label, const char* y_label, const char* z_label, ImPlot3DAxisFlags x_flags, ImPlot3DAxisFlags y_flags, + ImPlot3DAxisFlags z_flags) { + SetupAxis(ImAxis3D_X, x_label, x_flags); + SetupAxis(ImAxis3D_Y, y_label, y_flags); + SetupAxis(ImAxis3D_Z, z_label, z_flags); +} + +void SetupAxesLimits(double x_min, double x_max, double y_min, double y_max, double z_min, double z_max, ImPlot3DCond cond) { + SetupAxisLimits(ImAxis3D_X, x_min, x_max, cond); + SetupAxisLimits(ImAxis3D_Y, y_min, y_max, cond); + SetupAxisLimits(ImAxis3D_Z, z_min, z_max, cond); + if (cond == ImPlot3DCond_Once) + GImPlot3D->CurrentPlot->FitThisFrame = false; +} + +void SetupBoxRotation(double elevation, double azimuth, bool animate, ImPlot3DCond cond) { + // Convert angles from degrees to radians + double elev_rad = elevation * IM_PI / 180.0; + double azim_rad = azimuth * IM_PI / 180.0; + + // Call quaternion SetupBoxRotation + SetupBoxRotation(ImPlot3DQuat::FromElAz(elev_rad, azim_rad), animate, cond); +} + +void SetupBoxRotation(ImPlot3DQuat rotation, bool animate, ImPlot3DCond cond) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "SetupBoxRotation() needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + + if (!plot.Initialized || cond == ImPlot3DCond_Always) { + if (!animate) { + plot.Rotation = rotation; + plot.AnimationTime = 0.0f; // Force any running rotation animation to stop + } else { + plot.RotationAnimationEnd = rotation; + plot.AnimationTime = CalcAnimationTime(plot.Rotation, plot.RotationAnimationEnd); + } + plot.RotationCond = cond; + } +} + +void SetupBoxInitialRotation(double elevation, double azimuth) { + // Convert angles from degrees to radians + double elev_rad = elevation * IM_PI / 180.0; + double azim_rad = azimuth * IM_PI / 180.0; + + // Call quaternion SetupBoxInitialRotation + SetupBoxInitialRotation(ImPlot3DQuat::FromElAz(elev_rad, azim_rad)); +} + +void SetupBoxInitialRotation(ImPlot3DQuat rotation) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "SetupBoxInitialRotation() needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + + plot.InitialRotation = rotation; +} + +void SetupBoxScale(double x, double y, double z) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "SetupBoxScale() needs to be called after BeginPlot() and before any setup locking functions (e.g. PlotX)!"); + IM_ASSERT_USER_ERROR(x > 0.0 && y > 0.0 && z > 0.0, "SetupBoxScale() requires all aspect ratios to be greater than 0!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + plot.Axes[0].NDCScale = x; + plot.Axes[1].NDCScale = y; + plot.Axes[2].NDCScale = z; +} + +void SetupLegend(ImPlot3DLocation location, ImPlot3DLegendFlags flags) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "SetupLegend() needs to be called after BeginPlot() and before any setup locking functions (e.g. PlotX)!"); + IM_ASSERT_USER_ERROR(gp.CurrentItems != nullptr, "SetupLegend() needs to be called within an itemized context!"); + ImPlot3DLegend& legend = gp.CurrentItems->Legend; + if (legend.PreviousLocation != location) + legend.Location = location; + legend.PreviousLocation = location; + if (legend.PreviousFlags != flags) + legend.Flags = flags; + legend.PreviousFlags = flags; +} + +//----------------------------------------------------------------------------- +// [SECTION] Plot Utils +//----------------------------------------------------------------------------- + +ImPlot3DPlot* GetCurrentPlot() { return GImPlot3D->CurrentPlot; } + +void BustPlotCache() { + ImPlot3DContext& gp = *GImPlot3D; + gp.Plots.Clear(); +} + +ImVec2 PlotToPixels(const ImPlot3DPoint& point) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PlotToPixels() needs to be called between BeginPlot() and EndPlot()!"); + return NDCToPixels(PlotToNDC(point)); +} + +ImVec2 PlotToPixels(double x, double y, double z) { return PlotToPixels(ImPlot3DPoint(x, y, z)); } + +ImPlot3DRay PixelsToPlotRay(const ImVec2& pix) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PixelsToPlotRay() needs to be called between BeginPlot() and EndPlot()!"); + return NDCRayToPlotRay(PixelsToNDCRay(pix)); +} + +ImPlot3DRay PixelsToPlotRay(double x, double y) { return PixelsToPlotRay(ImVec2((float)x, (float)y)); } + +ImPlot3DPoint PixelsToPlotPlane(const ImVec2& pix, ImPlane3D plane, bool mask) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PixelsToPlotPlane() needs to be called between BeginPlot() and EndPlot()!"); + + ImPlot3DPlot& plot = *gp.CurrentPlot; + ImPlot3DRay ray = PixelsToNDCRay(pix); + const ImPlot3DPoint& O = ray.Origin; + const ImPlot3DPoint& D = ray.Direction; + + // Helper lambda to check intersection with a given coordinate and return intersection point if valid. + auto IntersectPlane = [&](double coord) -> ImPlot3DPoint { + // Solve for t in O[axis] + D[axis]*t = coord + double denom = 0.0; + double numer = 0.0; + if (plane == ImPlane3D_YZ) { + denom = D.x; + numer = coord - O.x; + } else if (plane == ImPlane3D_XZ) { + denom = D.y; + numer = coord - O.y; + } else if (plane == ImPlane3D_XY) { + denom = D.z; + numer = coord - O.z; + } + + if (ImAbs(denom) < 1e-12f) { + // Ray is parallel or nearly parallel to the plane + return ImPlot3DPoint(NAN, NAN, NAN); + } + + double t = numer / denom; + if (t < 0.0f) { + // Intersection behind the ray origin + return ImPlot3DPoint(NAN, NAN, NAN); + } + + return O + D * t; + }; + + // Compute which plane to intersect with + bool active_faces[3]; + ComputeActiveFaces(active_faces, plot.Rotation, plot.Axes); + + // Calculate intersection point with the planes + ImPlot3DPoint P = IntersectPlane(active_faces[plane] ? 0.5f * plot.Axes[plane].NDCScale : -0.5f * plot.Axes[plane].NDCScale); + if (P.IsNaN()) + return P; + + // Helper lambda to check if point P is within the plot box + auto InRange = [&](const ImPlot3DPoint& P) { + ImPlot3DPoint box_scale = plot.GetBoxScale(); + return P.x >= -0.5f * box_scale.x && P.x <= 0.5f * box_scale.x && P.y >= -0.5f * box_scale.y && P.y <= 0.5f * box_scale.y && + P.z >= -0.5f * box_scale.z && P.z <= 0.5f * box_scale.z; + }; + + // Handle mask (if one of the intersections is out of range, set it to NAN) + if (mask) { + switch (plane) { + case ImPlane3D_YZ: + if (!InRange(ImPlot3DPoint(0.0, P.y, P.z))) + return ImPlot3DPoint(NAN, NAN, NAN); + break; + case ImPlane3D_XZ: + if (!InRange(ImPlot3DPoint(P.x, 0.0, P.z))) + return ImPlot3DPoint(NAN, NAN, NAN); + break; + case ImPlane3D_XY: + if (!InRange(ImPlot3DPoint(P.x, P.y, 0.0))) + return ImPlot3DPoint(NAN, NAN, NAN); + break; + } + } + + return NDCToPlot(P); +} + +ImPlot3DPoint PixelsToPlotPlane(double x, double y, ImPlane3D plane, bool mask) { return PixelsToPlotPlane(ImVec2((float)x, (float)y), plane, mask); } + +ImVec2 GetPlotRectPos() { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetPlotRectPos() needs to be called between BeginPlot() and EndPlot()!"); + SetupLock(); + return gp.CurrentPlot->PlotRect.Min; +} + +ImVec2 GetPlotRectSize() { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetPlotRectSize() needs to be called between BeginPlot() and EndPlot()!"); + SetupLock(); + return gp.CurrentPlot->PlotRect.GetSize(); +} + +ImVec2 GetFramePos() { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetFramePos() needs to be called between BeginPlot() and EndPlot()!"); + return gp.CurrentPlot->FrameRect.Min; +} + +ImVec2 GetFrameSize() { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetFrameSize() needs to be called between BeginPlot() and EndPlot()!"); + return gp.CurrentPlot->FrameRect.GetSize(); +} + +ImPlot3DPoint PlotToNDC(const ImPlot3DPoint& point) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PlotToNDC() needs to be called between BeginPlot() and EndPlot()!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + SetupLock(); + + return PlotToNDC(plot, point); +} + +ImPlot3DPoint NDCToPlot(const ImPlot3DPoint& point) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "NDCToPlot() needs to be called between BeginPlot() and EndPlot()!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + SetupLock(); + + ImPlot3DPoint plot_point; + for (int i = 0; i < 3; i++) { + ImPlot3DAxis& axis = plot.Axes[i]; + double ndc_range = 0.5 * axis.NDCScale; + double ndc_point = point[i]; + double t = ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_Invert) ? (ndc_range - ndc_point) : (ndc_point + ndc_range); + t /= axis.NDCScale; + plot_point[i] = axis.NDCToPlot(t); + } + return plot_point; +} + +ImVec2 NDCToPixels(const ImPlot3DPoint& point) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "NDCToPixels() needs to be called between BeginPlot() and EndPlot()!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + SetupLock(); + + return NDCToPixels(plot, point); +} + +ImPlot3DRay PixelsToNDCRay(const ImVec2& pix) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PixelsToNDCRay() needs to be called between BeginPlot() and EndPlot()!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + SetupLock(); + + // Calculate zoom factor and plot center + float zoom = plot.GetViewScale(); + ImVec2 center = plot.PlotRect.GetCenter(); + + // Undo screen transformations to get back to NDC space + float x = (pix.x - center.x) / zoom; + float y = -(pix.y - center.y) / zoom; // Invert y-axis + + // Define near and far points in NDC space along the z-axis + ImPlot3DPoint ndc_near = plot.Rotation.Inverse() * ImPlot3DPoint(x, y, 10.0f); + ImPlot3DPoint ndc_far = plot.Rotation.Inverse() * ImPlot3DPoint(x, y, -10.0f); + + // Create the ray in NDC space + ImPlot3DRay ndc_ray; + ndc_ray.Origin = ndc_near; + ndc_ray.Direction = (ndc_far - ndc_near).Normalized(); + + return ndc_ray; +} + +ImPlot3DRay NDCRayToPlotRay(const ImPlot3DRay& ray) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "NDCRayToPlotRay() needs to be called between BeginPlot() and EndPlot()!"); + SetupLock(); + + // Convert NDC origin and a point along the ray to plot coordinates + ImPlot3DPoint plot_origin = NDCToPlot(ray.Origin); + ImPlot3DPoint ndc_point_along_ray = ray.Origin + ray.Direction; + ImPlot3DPoint plot_point_along_ray = NDCToPlot(ndc_point_along_ray); + + // Compute the direction in plot coordinates + ImPlot3DPoint plot_direction = (plot_point_along_ray - plot_origin).Normalized(); + + // Create the ray in plot coordinates + ImPlot3DRay plot_ray; + plot_ray.Origin = plot_origin; + plot_ray.Direction = plot_direction; + + return plot_ray; +} + +//----------------------------------------------------------------------------- +// [SECTION] Setup Utils +//----------------------------------------------------------------------------- + +static const float MOUSE_CURSOR_DRAG_THRESHOLD = 5.0f; + +void HandleInput(ImPlot3DPlot& plot) { + if (ImHasFlag(plot.Flags, ImPlot3DFlags_NoInputs)) + return; + + ImGuiIO& IO = ImGui::GetIO(); + + // clang-format off + const ImGuiButtonFlags plot_button_flags = ImGuiButtonFlags_AllowOverlap + | ImGuiButtonFlags_PressedOnClick + | ImGuiButtonFlags_PressedOnDoubleClick + | ImGuiButtonFlags_MouseButtonLeft + | ImGuiButtonFlags_MouseButtonRight + | ImGuiButtonFlags_MouseButtonMiddle; + // clang-format on + const bool plot_clicked = ImGui::ButtonBehavior(plot.PlotRect, plot.ID, &plot.Hovered, &plot.Held, plot_button_flags); +#if (IMGUI_VERSION_NUM < 18966) + ImGui::SetItemAllowOverlap(); // Handled by ButtonBehavior() +#endif + + // State + const ImVec2 rot_drag = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right); + const bool rotating = ImLengthSqr(rot_drag) > MOUSE_CURSOR_DRAG_THRESHOLD; + const bool axis_equal = ImHasFlag(plot.Flags, ImPlot3DFlags_Equal); + const bool allow_rotate = !ImHasFlag(plot.Flags, ImPlot3DFlags_NoRotate); + const bool allow_pan = !ImHasFlag(plot.Flags, ImPlot3DFlags_NoPan); + const bool allow_zoom = !ImHasFlag(plot.Flags, ImPlot3DFlags_NoZoom); + + // HOVERING STATE ------------------------------------------------------------------- + + // Check if any axis/plane is hovered + bool active_faces[3]; + ImVec2 corners_pix[8]; + ImPlot3DPoint corners[8]; + int plane_2d; + int axis_corners[3][2]; + GetAxesParameters(plot, active_faces, corners_pix, corners, plane_2d, axis_corners); + int hovered_plane_idx = -1; + int hovered_plane = GetMouseOverPlane(active_faces, corners_pix, &hovered_plane_idx); + int hovered_edge_idx = -1; + int hovered_axis = GetMouseOverAxis(plot, corners_pix, plane_2d, axis_corners, &hovered_edge_idx); + if (hovered_axis != -1) { + hovered_plane_idx = -1; + hovered_plane = -1; + } + + // If the user is no longer pressing the translation/zoom buttons, set axes as not held + if (!ImGui::IsMouseDown(ImGuiMouseButton_Left) && !ImGui::IsMouseDown(ImGuiMouseButton_Middle)) { + for (int i = 0; i < 3; i++) + plot.Axes[i].Held = false; + } + + // Reset held edge/plane indices (it will be set if mouse button is down) + if (!plot.Held) { + plot.HeldEdgeIdx = -1; + plot.HeldPlaneIdx = -1; + } + + // Check which axes should be transformed (fit/zoom/translate) + bool any_axis_held = plot.Axes[0].Held || plot.Axes[1].Held || plot.Axes[2].Held; + if (!any_axis_held) { + // Only update the transformation axes if the user is not already performing a transformation + plot.Axes[0].Hovered = plot.Axes[1].Hovered = plot.Axes[2].Hovered = false; + if (hovered_axis != -1) { + plot.Axes[hovered_axis].Hovered = true; + } else if (hovered_plane != -1) { + plot.Axes[(hovered_plane + 1) % 3].Hovered = true; + plot.Axes[(hovered_plane + 2) % 3].Hovered = true; + } else { + plot.Axes[0].Hovered = plot.Axes[1].Hovered = plot.Axes[2].Hovered = true; + } + } + + // Compute plane that is being hovered by mouse + ImPlane3D mouse_plane = ImPlane3D_XY; + if (plane_2d != -1) + mouse_plane = plane_2d; + else if (plot.Axes[1].Hovered && plot.Axes[2].Hovered) + mouse_plane = ImPlane3D_YZ; + else if (plot.Axes[0].Hovered && plot.Axes[2].Hovered) + mouse_plane = ImPlane3D_XZ; + else if (plot.Axes[0].Hovered && plot.Axes[1].Hovered) + mouse_plane = ImPlane3D_XY; + else if (plot.HeldEdgeIdx != -1 || hovered_edge_idx != -1) { + // Single axis hovered: use the edge index and active faces to pick the visible plane + // Each edge belongs to exactly 2 faces. We pick the active (visible) one. + + // If the user is holding an edge, use that index; otherwise, use the hovered edge index + int curr_edge_idx = plot.HeldEdgeIdx != -1 ? plot.HeldEdgeIdx : hovered_edge_idx; + + // Map edge index to the two faces it belongs to, and corresponding plane + // Format: {face_index, plane_enum} + static const int edge_to_faces[12][2][2] = { + {{1, ImPlane3D_XZ}, {2, ImPlane3D_XY}}, // Edge 0: Y-min face, Z-min face + {{2, ImPlane3D_XY}, {3, ImPlane3D_YZ}}, // Edge 1: Z-min face, X-max face + {{2, ImPlane3D_XY}, {4, ImPlane3D_XZ}}, // Edge 2: Z-min face, Y-max face + {{0, ImPlane3D_YZ}, {2, ImPlane3D_XY}}, // Edge 3: X-min face, Z-min face + {{1, ImPlane3D_XZ}, {5, ImPlane3D_XY}}, // Edge 4: Y-min face, Z-max face + {{3, ImPlane3D_YZ}, {5, ImPlane3D_XY}}, // Edge 5: X-max face, Z-max face + {{4, ImPlane3D_XZ}, {5, ImPlane3D_XY}}, // Edge 6: Y-max face, Z-max face + {{0, ImPlane3D_YZ}, {5, ImPlane3D_XY}}, // Edge 7: X-min face, Z-max face + {{0, ImPlane3D_YZ}, {1, ImPlane3D_XZ}}, // Edge 8: X-min face, Y-min face + {{1, ImPlane3D_XZ}, {3, ImPlane3D_YZ}}, // Edge 9: Y-min face, X-max face + {{3, ImPlane3D_YZ}, {4, ImPlane3D_XZ}}, // Edge 10: X-max face, Y-max face + {{0, ImPlane3D_YZ}, {4, ImPlane3D_XZ}}, // Edge 11: X-min face, Y-max face + }; + + // Check which of the two faces is active (visible from camera) + int face0 = edge_to_faces[curr_edge_idx][0][0]; + int face1 = edge_to_faces[curr_edge_idx][1][0]; + + // Determine which face is active based on active_faces + // Faces 0-2 are min faces (active when active_faces[i] == false) + // Faces 3-5 are max faces (active when active_faces[i] == true) + bool face0_active = (face0 < 3) ? !active_faces[face0] : active_faces[face0 - 3]; + bool face1_active = (face1 < 3) ? !active_faces[face1] : active_faces[face1 - 3]; + + // Pick the plane corresponding to the active face + if (face0_active) { + mouse_plane = (ImPlane3D)edge_to_faces[curr_edge_idx][0][1]; + } else if (face1_active) { + mouse_plane = (ImPlane3D)edge_to_faces[curr_edge_idx][1][1]; + } else { + // Fallback: both could be active in some edge cases, use first one + mouse_plane = (ImPlane3D)edge_to_faces[curr_edge_idx][0][1]; + } + } + ImVec2 mouse_pos = ImGui::GetMousePos(); + ImPlot3DPoint mouse_pos_plot = PixelsToPlotPlane(mouse_pos, mouse_plane, false); + + // AUTO FIT ------------------------------------------------------------------- + + // Handle translation/zoom fit with double click + if (plot_clicked && (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left) || ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Middle)) && + (allow_pan && allow_zoom)) { + plot.FitThisFrame = true; + for (int i = 0; i < 3; i++) + plot.Axes[i].FitThisFrame = plot.Axes[i].Hovered; + } + + // Handle auto fit + for (int i = 0; i < 3; i++) + if (plot.Axes[i].IsAutoFitting()) { + plot.FitThisFrame = true; + plot.Axes[i].FitThisFrame = true; + } + + // TRANSLATION ------------------------------------------------------------------- + + // Handle translation with right mouse button + if (plot.Held && ImGui::IsMouseDown(ImGuiMouseButton_Left) && allow_pan) { + ImVec2 delta(IO.MouseDelta.x, IO.MouseDelta.y); + + if (plot.Axes[0].Hovered && plot.Axes[1].Hovered && plot.Axes[2].Hovered) { + // Perform unconstrained translation (translate on the viewer's plane) + + // Compute delta_pixels in 3D (invert y-axis) + ImPlot3DPoint delta_pixels(delta.x, -delta.y, 0.0f); + + // Convert delta to NDC space + float zoom = plot.GetViewScale(); + ImPlot3DPoint delta_NDC = plot.Rotation.Inverse() * (delta_pixels / zoom); + + // Create points in NDC space representing the new shifted range + ImPlot3DPoint p_min_ndc, p_max_ndc; + for (int i = 0; i < 3; i++) { + double half_scale = 0.5 * plot.Axes[i].NDCScale; + p_min_ndc[i] = -half_scale - delta_NDC[i]; + p_max_ndc[i] = half_scale - delta_NDC[i]; + } + + // Convert these NDC points to Plot space to get the new range + // NDCToPlot handles axis inversions and non-linear transforms + ImPlot3DPoint p_min_plt = NDCToPlot(p_min_ndc); + ImPlot3DPoint p_max_plt = NDCToPlot(p_max_ndc); + + // Adjust plot range to translate the plot + for (int i = 0; i < 3; i++) { + if (plot.Axes[i].Hovered) { + double v1 = p_min_plt[i]; + double v2 = p_max_plt[i]; + double new_min = ImMin(v1, v2); + double new_max = ImMax(v1, v2); + + bool increasing = new_min > plot.Axes[i].Range.Min; + if ((new_min != plot.Axes[i].Range.Min || new_max != plot.Axes[i].Range.Max) && !plot.Axes[i].IsPanLocked(increasing)) { + // Update axis range + plot.Axes[i].SetRange(new_min, new_max); + // Apply equal aspect ratio constraint + if (axis_equal) + plot.ApplyEqualAspect(i); + } + plot.Axes[i].Held = true; + } + // If no axis was held before (user started translating in this frame), set the held edge/plane indices + if (!any_axis_held) { + plot.HeldEdgeIdx = hovered_edge_idx; + plot.HeldPlaneIdx = hovered_plane_idx; + } + } + } else if (plot.Axes[0].Hovered || plot.Axes[1].Hovered || plot.Axes[2].Hovered) { + // Translate along plane/axis + // + // For transforms like log scale, we use the approach from ImPlot: + // Transform reference points with the mouse delta applied, which properly handles non-linear scales. + // The key: use points that lie on the interaction plane, not arbitrary box corners. + + ImVec2 mouse_delta(IO.MouseDelta.x, IO.MouseDelta.y); + + // Create reference points on the interaction plane at the axis range extremes + // We use the current mouse position as a template, then vary each axis independently + ImPlot3DPoint ref_base = mouse_pos_plot; + + for (int i = 0; i < 3; i++) { + if (plot.Axes[i].Hovered) { + ImPlot3DAxis& axis = plot.Axes[i]; + + // Create two reference points on the interaction plane: + // - One at the minimum of this axis + // - One at the maximum of this axis + // Keep other coordinates the same (on the plane) + ImPlot3DPoint p_min = ref_base; + ImPlot3DPoint p_max = ref_base; + p_min[i] = axis.Range.Min; + p_max[i] = axis.Range.Max; + + // Transform to pixels, apply mouse delta, transform back + ImVec2 pix_min = PlotToPixels(plot, p_min); + ImVec2 pix_max = PlotToPixels(plot, p_max); + + pix_min.x -= mouse_delta.x; + pix_min.y -= mouse_delta.y; + pix_max.x -= mouse_delta.x; + pix_max.y -= mouse_delta.y; + + // Project back to plot space via the interaction plane + ImPlot3DPoint new_p_min = PixelsToPlotPlane(pix_min, mouse_plane, false); + ImPlot3DPoint new_p_max = PixelsToPlotPlane(pix_max, mouse_plane, false); + + // Extract the new range for this axis + double new_min = new_p_min[i]; + double new_max = new_p_max[i]; + + // Check if we should update + bool increasing = (new_min < axis.Range.Min); + if ((new_min != axis.Range.Min || new_max != axis.Range.Max) && !axis.IsPanLocked(increasing)) { + axis.SetRange(new_min, new_max); + + // Apply equal aspect ratio constraint + if (axis_equal) + plot.ApplyEqualAspect(i); + } + axis.Held = true; + } + if (!any_axis_held) { + plot.HeldEdgeIdx = hovered_edge_idx; + plot.HeldPlaneIdx = hovered_plane_idx; + } + } + } + } + + // ROTATION ------------------------------------------------------------------- + + // Handle reset rotation with left mouse double click + if (plot.Held && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Right) && !plot.IsRotationLocked() && allow_rotate) { + plot.RotationAnimationEnd = plot.Rotation; + + // Calculate rotation to align the z-axis with the camera direction + if (hovered_plane == -1) { + plot.RotationAnimationEnd = plot.InitialRotation; + } else { + // Compute plane normal + ImPlot3DPoint axis_normal = ImPlot3DPoint(0.0f, 0.0f, 0.0f); + axis_normal[hovered_plane] = active_faces[hovered_plane] ? -1.0f : 1.0f; + if (ImPlot3D::ImHasFlag(plot.Axes[hovered_plane].Flags, ImPlot3DAxisFlags_Invert)) + axis_normal[hovered_plane] *= -1; + + // Compute rotation to align the plane normal with the z-axis + ImPlot3DQuat align_normal = ImPlot3DQuat::FromTwoVectors(plot.RotationAnimationEnd * axis_normal, ImPlot3DPoint(0.0f, 0.0f, 1.0f)); + plot.RotationAnimationEnd = align_normal * plot.RotationAnimationEnd; + + if (hovered_plane != 2) { + // Compute rotation to point z-axis up + ImPlot3DQuat align_up = + ImPlot3DQuat::FromTwoVectors(plot.RotationAnimationEnd * ImPlot3DPoint(0.0f, 0.0f, 1.0f), ImPlot3DPoint(0.0f, 1.0f, 0.0f)); + plot.RotationAnimationEnd = align_up * plot.RotationAnimationEnd; + } else { + // Find the axis most aligned with the up direction + ImPlot3DPoint up(0.0f, 1.0f, 0.0f); + ImPlot3DPoint x_axis = plot.RotationAnimationEnd * ImPlot3DPoint(1.0f, 0.0f, 0.0f); + ImPlot3DPoint y_axis = plot.RotationAnimationEnd * ImPlot3DPoint(0.0f, 1.0f, 0.0f); + ImPlot3DPoint neg_x_axis = plot.RotationAnimationEnd * ImPlot3DPoint(-1.0f, 0.0f, 0.0f); + ImPlot3DPoint neg_y_axis = plot.RotationAnimationEnd * ImPlot3DPoint(0.0f, -1.0f, 0.0f); + + struct AxisAlignment { + ImPlot3DPoint axis; + float dot; + }; + + AxisAlignment candidates[] = { + {x_axis, (float)x_axis.Dot(up)}, + {y_axis, (float)y_axis.Dot(up)}, + {neg_x_axis, (float)neg_x_axis.Dot(up)}, + {neg_y_axis, (float)neg_y_axis.Dot(up)}, + }; + + // Find the candidate with the maximum dot product + AxisAlignment* best_candidate = &candidates[0]; + for (int i = 1; i < 4; i++) { + if (candidates[i].dot > best_candidate->dot) { + best_candidate = &candidates[i]; + } + } + + // Compute the rotation to align the best candidate with the up direction + ImPlot3DQuat align_up = ImPlot3DQuat::FromTwoVectors(best_candidate->axis, up); + plot.RotationAnimationEnd = align_up * plot.RotationAnimationEnd; + } + } + + // Calculate animation time + plot.AnimationTime = CalcAnimationTime(plot.Rotation, plot.RotationAnimationEnd); + } + + // Handle rotation with left mouse dragging + if (plot.Held && ImGui::IsMouseDown(ImGuiMouseButton_Right) && !plot.IsRotationLocked() && allow_rotate) { + ImVec2 delta(IO.MouseDelta.x, IO.MouseDelta.y); + + // Map delta to rotation angles (in radians) + float angle_x = delta.x * (3.1415f / 180.0f); + float angle_y = delta.y * (3.1415f / 180.0f); + + // If drag just started, determine and store the rotation axis + if (plot.DragRotationAxis == ImPlot3DPoint(0.0f, 0.0f, 0.0f)) { + ImPlot3DPoint up_vector = plot.Rotation * ImPlot3DPoint(0.0f, 0.0f, 1.0f); + bool is_upside_down = up_vector.z < 0.0f; + plot.DragRotationAxis = is_upside_down ? ImPlot3DPoint(0.0f, 0.0f, -1.0f) : ImPlot3DPoint(0.0f, 0.0f, 1.0f); + } + + // Create quaternions for the rotations + ImPlot3DQuat quat_x(angle_y, ImPlot3DPoint(1.0f, 0.0f, 0.0f)); + ImPlot3DQuat quat_z(angle_x, plot.DragRotationAxis); + + // Combine the new rotations with the current rotation + plot.Rotation = quat_x * plot.Rotation * quat_z; + plot.Rotation.Normalize(); + } else { + // Reset drag rotation axis when not dragging + plot.DragRotationAxis = ImPlot3DPoint(0.0f, 0.0f, 0.0f); + } + + // ZOOM ------------------------------------------------------------------- + + // Handle zoom with mouse wheel + if (plot.Hovered && allow_zoom) { + ImGui::SetKeyOwner(ImGuiKey_MouseWheelY, plot.ID); + if (ImGui::IsMouseDown(ImGuiMouseButton_Middle) || IO.MouseWheel != 0.0f) { + float delta = ImGui::IsMouseDown(ImGuiMouseButton_Middle) ? (-0.01f * IO.MouseDelta.y) : (-0.1f * IO.MouseWheel); + float zoom_rate = delta; // Positive = zoom in, negative = zoom out + + // For transforms like log scale, we use the approach from ImPlot: + // Transform reference points with zoom expansion/contraction applied in pixel/NDC space, + // which properly handles non-linear scales. + + const bool zoom_around_mouse = (hovered_axis != -1 || hovered_plane != -1); + + // Zoom all hovered axes independently + ImAxis3D ref_axis = ImAxis3D_X; + for (int i = 0; i < 3; i++) { + if (!plot.Axes[i].Hovered || plot.Axes[i].IsInputLocked()) + continue; + + ImPlot3DAxis& axis = plot.Axes[i]; + + // Create reference points on the interaction plane at range extremes + ImPlot3DPoint p_min = mouse_pos_plot; + ImPlot3DPoint p_max = mouse_pos_plot; + p_min[i] = axis.Range.Min; + p_max[i] = axis.Range.Max; + + // Transform to pixels + ImVec2 pix_min = PlotToPixels(plot, p_min); + ImVec2 pix_max = PlotToPixels(plot, p_max); + + // Compute the pixel distance from mouse to each endpoint + ImVec2 mouse_pix = PlotToPixels(plot, mouse_pos_plot); + float dist_min = + ImSqrt((pix_min.x - mouse_pix.x) * (pix_min.x - mouse_pix.x) + (pix_min.y - mouse_pix.y) * (pix_min.y - mouse_pix.y)); + float dist_max = + ImSqrt((pix_max.x - mouse_pix.x) * (pix_max.x - mouse_pix.x) + (pix_max.y - mouse_pix.y) * (pix_max.y - mouse_pix.y)); + + if (zoom_around_mouse && (dist_min > 0 || dist_max > 0)) { + // Zoom around mouse: expand/contract distances from mouse position + // Direction vectors from mouse to endpoints + ImVec2 dir_min = pix_min - mouse_pix; + ImVec2 dir_max = pix_max - mouse_pix; + + // Apply zoom by scaling the distances + // Note: zoom_rate is negative when zooming in (MouseWheel > 0), so we add it + pix_min = mouse_pix + dir_min * (1.0f + zoom_rate); + pix_max = mouse_pix + dir_max * (1.0f + zoom_rate); + + // Project back to plot space via the plane + ImPlot3DPoint new_p_min = PixelsToPlotPlane(pix_min, mouse_plane, false); + ImPlot3DPoint new_p_max = PixelsToPlotPlane(pix_max, mouse_plane, false); + + // Extract the new range for this axis + double new_min = new_p_min[i]; + double new_max = new_p_max[i]; + + // Update the range + axis.SetRange(new_min, new_max); + } else { + // Zoom around center + double ndc_limit = 0.5 * axis.NDCScale; + double zoom_factor = 1.0f + zoom_rate; + + // Create points in NDC space representing the new zoomed range + ImPlot3DPoint ndc_min(0.0f, 0.0f, 0.0f); + ImPlot3DPoint ndc_max(0.0f, 0.0f, 0.0f); + ndc_min[i] = -ndc_limit * zoom_factor; + ndc_max[i] = ndc_limit * zoom_factor; + + // Convert these NDC points to Plot space to get the new range + ImPlot3DPoint plt_min = NDCToPlot(ndc_min); + ImPlot3DPoint plt_max = NDCToPlot(ndc_max); + + axis.SetRange(plt_min[i], plt_max[i]); + } + + axis.Held = true; + + // Use a hovered axis as reference + ref_axis = (ImAxis3D)i; + } + + // Apply equal constraint using the reference axis + if (axis_equal) + plot.ApplyEqualAspect(ref_axis); + + // If no axis was held before (user started zoom in this frame), set the held edge/plane indices + if (!any_axis_held) { + plot.HeldEdgeIdx = hovered_edge_idx; + plot.HeldPlaneIdx = hovered_plane_idx; + } + } + } + + // CONTEXT MENU ------------------------------------------------------------------- + + // Handle context click with right mouse button + if (plot.Held && ImGui::IsMouseClicked(ImGuiMouseButton_Right) && !ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_NoMenus)) + plot.ContextClick = true; + if (rotating || (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Right) && allow_rotate)) + plot.ContextClick = false; + + // Handle context menu (should not happen if it is not a double click action) + bool not_double_click = allow_rotate ? (float)(ImGui::GetTime() - IO.MouseClickedTime[ImGuiMouseButton_Right]) > IO.MouseDoubleClickTime : true; + if (plot.Hovered && plot.ContextClick && not_double_click && !ImGui::IsMouseDown(ImGuiMouseButton_Right)) { + plot.ContextClick = false; + plot.OpenContextThisFrame = true; + } + + if (plot.OpenContextThisFrame) { + if (plot.Items.Legend.Hovered) + ImGui::OpenPopup("##LegendContext"); + else if (hovered_axis != -1) { + ImGui::OpenPopup(axis_contexts[hovered_axis]); + } else if (hovered_plane != -1) { + ImGui::OpenPopup(plane_contexts[hovered_plane]); + } else if (plot.Hovered) { + ImGui::OpenPopup("##PlotContext"); + } + } +} + +void SetupLock() { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "SetupLock() needs to be called between BeginPlot() and EndPlot()!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + if (plot.SetupLocked) + return; + // Lock setup + plot.SetupLocked = true; + + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImDrawList* draw_list = window->DrawList; + + // Set default formatter/locator + for (int i = 0; i < 3; i++) { + ImPlot3DAxis& axis = plot.Axes[i]; + + // Set formatter + if (axis.Formatter == nullptr) { + axis.Formatter = Formatter_Default; + if (axis.FormatterData == nullptr) + axis.FormatterData = (void*)IMPLOT3D_LABEL_FORMAT; + } + + // Set locator + if (axis.Locator == nullptr) + axis.Locator = Locator_Default; + } + + // Draw frame background + ImU32 f_bg_color = GetStyleColorU32(ImPlot3DCol_FrameBg); + draw_list->AddRectFilled(plot.FrameRect.Min, plot.FrameRect.Max, f_bg_color); + + // Compute canvas/canvas rectangle + plot.CanvasRect = ImRect(plot.FrameRect.Min + gp.Style.PlotPadding, plot.FrameRect.Max - gp.Style.PlotPadding); + plot.PlotRect = plot.CanvasRect; + + // Apply equal axis aspect constraint if not approximately equal + const bool axis_equal = ImHasFlag(plot.Flags, ImPlot3DFlags_Equal); + if (axis_equal) { + double xar = plot.Axes[ImAxis3D_X].GetAspect(); + double yar = plot.Axes[ImAxis3D_Y].GetAspect(); + double zar = plot.Axes[ImAxis3D_Z].GetAspect(); + if (!ImAlmostEqual(xar, yar) || !ImAlmostEqual(xar, zar)) { + double aspect = (xar + yar + zar) / 3.0; + plot.Axes[ImAxis3D_X].SetAspect(aspect); + plot.Axes[ImAxis3D_Y].SetAspect(aspect); + plot.Axes[ImAxis3D_Z].SetAspect(aspect); + } + } + + // Compute ticks + for (int i = 0; i < 3; i++) { + ImPlot3DAxis& axis = plot.Axes[i]; + if (axis.ShowDefaultTicks) { + float pixels = float(plot.GetViewScale() * axis.NDCScale); + axis.Locator(axis.Ticker, axis.Range, pixels, axis.Formatter, axis.FormatterData); + } + } + + // Cache axis colors + for (int i = 0; i < 3; i++) { + ImPlot3DAxis& axis = plot.Axes[i]; + axis.ColorBg = GetStyleColorU32(ImPlot3DCol_AxisBg); + axis.ColorHov = GetStyleColorU32(ImPlot3DCol_AxisBgHovered); + axis.ColorAct = GetStyleColorU32(ImPlot3DCol_AxisBgActive); + } + + // Render title + if (plot.HasTitle()) { + ImU32 col = GetStyleColorU32(ImPlot3DCol_TitleText); + ImVec2 top_center = ImVec2(plot.FrameRect.GetCenter().x, plot.CanvasRect.Min.y); + AddTextCentered(draw_list, top_center, col, plot.GetTitle()); + plot.PlotRect.Min.y += ImGui::GetTextLineHeight() + gp.Style.LabelPadding.y; + } + + // Handle animation + if (plot.AnimationTime > 0.0f) { + float dt = ImGui::GetIO().DeltaTime; + float t = ImClamp(dt / plot.AnimationTime, 0.0f, 1.0f); + plot.AnimationTime -= dt; + if (plot.AnimationTime < 0.0f) + plot.AnimationTime = 0.0f; + plot.Rotation = ImPlot3DQuat::Slerp(plot.Rotation, plot.RotationAnimationEnd, t); + } + + plot.Initialized = true; + + // Handle user input + HandleInput(plot); + + // Push plot rect clipping + ImGui::PushClipRect(plot.PlotRect.Min, plot.PlotRect.Max, true); + + // Render plot box + RenderPlotBox(draw_list, plot); +} + +//----------------------------------------------------------------------------- +// [SECTION] Miscellaneous +//----------------------------------------------------------------------------- + +ImDrawList* GetPlotDrawList() { return ImGui::GetWindowDrawList(); } + +//----------------------------------------------------------------------------- +// [SECTION] Styles +//----------------------------------------------------------------------------- + +struct ImPlot3DStyleVarInfo { + ImGuiDataType Type; + ImU32 Count; + ImU32 Offset; + void* GetVarPtr(ImPlot3DStyle* style) const { return (void*)((unsigned char*)style + Offset); } +}; + +static const ImPlot3DStyleVarInfo GPlot3DStyleVarInfo[] = { + // Item style + {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, LineWeight)}, // ImPlot3DStyleVar_LineWeight + {ImGuiDataType_S32, 1, (ImU32)offsetof(ImPlot3DStyle, Marker)}, // ImPlot3DStyleVar_Marker + {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, MarkerSize)}, // ImPlot3DStyleVar_MarkerSize + {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, FillAlpha)}, // ImPlot3DStyleVar_FillAlpha + + // Plot style + {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, PlotDefaultSize)}, // ImPlot3DStyleVar_PlotDefaultSize + {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, PlotMinSize)}, // ImPlot3DStyleVar_PlotMinSize + {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, PlotPadding)}, // ImPlot3DStyleVar_PlotPadding + {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LabelPadding)}, // ImPlot3DStyleVar_LabelPadding + {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, ViewScaleFactor)}, // ImPlot3DStyleVar_ViewScaleFactor + + // Legend style + {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LegendPadding)}, // ImPlot3DStyleVar_LegendPadding + {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LegendInnerPadding)}, // ImPlot3DStyleVar_LegendInnerPadding + {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LegendSpacing)}, // ImPlot3DStyleVar_LegendSpacing +}; + +static const ImPlot3DStyleVarInfo* GetPlotStyleVarInfo(ImPlot3DStyleVar idx) { + IM_ASSERT(idx >= 0 && idx < ImPlot3DStyleVar_COUNT); + IM_ASSERT(IM_ARRAYSIZE(GPlot3DStyleVarInfo) == ImPlot3DStyleVar_COUNT); + return &GPlot3DStyleVarInfo[idx]; +} + +ImPlot3DStyle& GetStyle() { return GImPlot3D->Style; } +void SetStyle(const ImPlot3DStyle& style) { GImPlot3D->Style = style; } + +void StyleColorsAuto(ImPlot3DStyle* dst) { + ImPlot3DStyle* style = dst ? dst : &ImPlot3D::GetStyle(); + ImVec4* colors = style->Colors; + + colors[ImPlot3DCol_TitleText] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_InlayText] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_FrameBg] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_PlotBg] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_PlotBorder] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_LegendBg] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_LegendBorder] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_LegendText] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_AxisText] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_AxisGrid] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_AxisTick] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_AxisBg] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_AxisBgHovered] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_AxisBgActive] = IMPLOT3D_AUTO_COL; +} + +void StyleColorsDark(ImPlot3DStyle* dst) { + ImPlot3DStyle* style = dst ? dst : &ImPlot3D::GetStyle(); + ImVec4* colors = style->Colors; + + colors[ImPlot3DCol_TitleText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlot3DCol_InlayText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlot3DCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f); + colors[ImPlot3DCol_PlotBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.50f); + colors[ImPlot3DCol_PlotBorder] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); + colors[ImPlot3DCol_LegendBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); + colors[ImPlot3DCol_LegendBorder] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); + colors[ImPlot3DCol_LegendText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlot3DCol_AxisText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlot3DCol_AxisGrid] = ImVec4(1.00f, 1.00f, 1.00f, 0.25f); + colors[ImPlot3DCol_AxisTick] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_AxisBg] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_AxisBgHovered] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_AxisBgActive] = IMPLOT3D_AUTO_COL; +} + +void StyleColorsLight(ImPlot3DStyle* dst) { + ImPlot3DStyle* style = dst ? dst : &ImPlot3D::GetStyle(); + ImVec4* colors = style->Colors; + + colors[ImPlot3DCol_TitleText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlot3DCol_InlayText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlot3DCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlot3DCol_PlotBg] = ImVec4(0.42f, 0.57f, 1.00f, 0.13f); + colors[ImPlot3DCol_PlotBorder] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImPlot3DCol_LegendBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.98f); + colors[ImPlot3DCol_LegendBorder] = ImVec4(0.82f, 0.82f, 0.82f, 0.80f); + colors[ImPlot3DCol_LegendText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlot3DCol_AxisText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlot3DCol_AxisGrid] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlot3DCol_AxisTick] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_AxisBg] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_AxisBgHovered] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_AxisBgActive] = IMPLOT3D_AUTO_COL; +} + +void StyleColorsClassic(ImPlot3DStyle* dst) { + ImPlot3DStyle* style = dst ? dst : &ImPlot3D::GetStyle(); + ImVec4* colors = style->Colors; + + colors[ImPlot3DCol_TitleText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImPlot3DCol_InlayText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImPlot3DCol_FrameBg] = ImVec4(0.43f, 0.43f, 0.43f, 0.39f); + colors[ImPlot3DCol_PlotBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.35f); + colors[ImPlot3DCol_PlotBorder] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f); + colors[ImPlot3DCol_LegendBg] = ImVec4(0.11f, 0.11f, 0.14f, 0.92f); + colors[ImPlot3DCol_LegendBorder] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f); + colors[ImPlot3DCol_LegendText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImPlot3DCol_AxisText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImPlot3DCol_AxisGrid] = ImVec4(0.90f, 0.90f, 0.90f, 0.25f); + colors[ImPlot3DCol_AxisTick] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_AxisBg] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_AxisBgHovered] = IMPLOT3D_AUTO_COL; + colors[ImPlot3DCol_AxisBgActive] = IMPLOT3D_AUTO_COL; +} + +bool ShowStyleSelector(const char* label) { + static int style_idx = -1; + if (ImGui::Combo(label, &style_idx, "Auto\0Classic\0Dark\0Light\0")) { + switch (style_idx) { + case 0: StyleColorsAuto(); break; + case 1: StyleColorsClassic(); break; + case 2: StyleColorsDark(); break; + case 3: StyleColorsLight(); break; + } + return true; + } + return false; +} + +bool ShowColormapSelector(const char* label) { + ImPlot3DContext& gp = *GImPlot3D; + bool set = false; + if (ImGui::BeginCombo(label, gp.ColormapData.GetName(gp.Style.Colormap))) { + for (int i = 0; i < gp.ColormapData.Count; ++i) { + const char* name = gp.ColormapData.GetName(i); + if (ImGui::Selectable(name, gp.Style.Colormap == i)) { + gp.Style.Colormap = i; + BustItemCache(); + set = true; + } + } + ImGui::EndCombo(); + } + return set; +} + +void PushStyleColor(ImPlot3DCol idx, ImU32 col) { + ImPlot3DContext& gp = *GImPlot3D; + ImGuiColorMod backup; + backup.Col = (ImGuiCol)idx; + backup.BackupValue = gp.Style.Colors[idx]; + gp.ColorModifiers.push_back(backup); + gp.Style.Colors[idx] = ImGui::ColorConvertU32ToFloat4(col); +} + +void PushStyleColor(ImPlot3DCol idx, const ImVec4& col) { + ImPlot3DContext& gp = *GImPlot3D; + ImGuiColorMod backup; + backup.Col = (ImGuiCol)idx; + backup.BackupValue = gp.Style.Colors[idx]; + gp.ColorModifiers.push_back(backup); + gp.Style.Colors[idx] = col; +} + +void PopStyleColor(int count) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(count <= gp.ColorModifiers.Size, "You can't pop more modifiers than have been pushed!"); + while (count > 0) { + ImGuiColorMod& backup = gp.ColorModifiers.back(); + gp.Style.Colors[backup.Col] = backup.BackupValue; + gp.ColorModifiers.pop_back(); + count--; + } +} + +void PushStyleVar(ImPlot3DStyleVar idx, float val) { + ImPlot3DContext& gp = *GImPlot3D; + const ImPlot3DStyleVarInfo* var_info = GetPlotStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) { + float* pvar = (float*)var_info->GetVarPtr(&gp.Style); + gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar)); + *pvar = val; + return; + } + IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!"); +} + +void PushStyleVar(ImPlot3DStyleVar idx, int val) { + ImPlot3DContext& gp = *GImPlot3D; + const ImPlot3DStyleVarInfo* var_info = GetPlotStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_S32 && var_info->Count == 1) { + int* pvar = (int*)var_info->GetVarPtr(&gp.Style); + gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar)); + *pvar = val; + return; + } else if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) { + float* pvar = (float*)var_info->GetVarPtr(&gp.Style); + gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar)); + *pvar = (float)val; + return; + } + IM_ASSERT(0 && "Called PushStyleVar() int variant but variable is not a int!"); +} + +void PushStyleVar(ImPlot3DStyleVar idx, const ImVec2& val) { + ImPlot3DContext& gp = *GImPlot3D; + const ImPlot3DStyleVarInfo* var_info = GetPlotStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2) { + ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&gp.Style); + gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar)); + *pvar = val; + return; + } + IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!"); +} + +void PopStyleVar(int count) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(count <= gp.StyleModifiers.Size, "You can't pop more modifiers than have been pushed!"); + while (count > 0) { + ImGuiStyleMod& backup = gp.StyleModifiers.back(); + const ImPlot3DStyleVarInfo* info = GetPlotStyleVarInfo(backup.VarIdx); + void* data = info->GetVarPtr(&gp.Style); + if (info->Type == ImGuiDataType_Float && info->Count == 1) { + ((float*)data)[0] = backup.BackupFloat[0]; + } else if (info->Type == ImGuiDataType_Float && info->Count == 2) { + ((float*)data)[0] = backup.BackupFloat[0]; + ((float*)data)[1] = backup.BackupFloat[1]; + } else if (info->Type == ImGuiDataType_S32 && info->Count == 1) { + ((int*)data)[0] = backup.BackupInt[0]; + } + gp.StyleModifiers.pop_back(); + count--; + } +} + +ImVec4 GetStyleColorVec4(ImPlot3DCol idx) { return IsColorAuto(idx) ? GetAutoColor(idx) : GImPlot3D->Style.Colors[idx]; } + +ImU32 GetStyleColorU32(ImPlot3DCol idx) { return ImGui::ColorConvertFloat4ToU32(ImPlot3D::GetStyleColorVec4(idx)); } + +ImPlot3DMarker NextMarker() { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentItems != nullptr, "NextMarker() needs to be called between BeginPlot() and EndPlot()!"); + const int idx = gp.CurrentItems->MarkerIdx % ImPlot3DMarker_COUNT; + ++gp.CurrentItems->MarkerIdx; + return idx; +} + +//------------------------------------------------------------------------------ +// [SECTION] Colormaps +//------------------------------------------------------------------------------ + +ImPlot3DColormap AddColormap(const char* name, const ImVec4* colormap, int size, bool qual) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(size > 1, "The colormap size must be greater than 1!"); + IM_ASSERT_USER_ERROR(gp.ColormapData.GetIndex(name) == -1, "The colormap name has already been used!"); + ImVector buffer; + buffer.resize(size); + for (int i = 0; i < size; i++) + buffer[i] = ImGui::ColorConvertFloat4ToU32(colormap[i]); + return gp.ColormapData.Append(name, buffer.Data, size, qual); +} + +ImPlot3DColormap AddColormap(const char* name, const ImU32* colormap, int size, bool qual) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(size > 1, "The colormap size must be greater than 1!"); + IM_ASSERT_USER_ERROR(gp.ColormapData.GetIndex(name) == -1, "The colormap name has already be used!"); + return gp.ColormapData.Append(name, colormap, size, qual); +} + +int GetColormapCount() { + ImPlot3DContext& gp = *GImPlot3D; + return gp.ColormapData.Count; +} + +const char* GetColormapName(ImPlot3DColormap colormap) { + ImPlot3DContext& gp = *GImPlot3D; + return gp.ColormapData.GetName(colormap); +} + +ImPlot3DColormap GetColormapIndex(const char* name) { + ImPlot3DContext& gp = *GImPlot3D; + return gp.ColormapData.GetIndex(name); +} + +void PushColormap(ImPlot3DColormap colormap) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(colormap >= 0 && colormap < gp.ColormapData.Count, "The colormap index is invalid!"); + gp.ColormapModifiers.push_back(gp.Style.Colormap); + gp.Style.Colormap = colormap; +} + +void PushColormap(const char* name) { + ImPlot3DContext& gp = *GImPlot3D; + ImPlot3DColormap idx = gp.ColormapData.GetIndex(name); + IM_ASSERT_USER_ERROR(idx != -1, "The colormap name is invalid!"); + PushColormap(idx); +} + +void PopColormap(int count) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(count <= gp.ColormapModifiers.Size, "You can't pop more modifiers than have been pushed!"); + while (count > 0) { + const ImPlot3DColormap& backup = gp.ColormapModifiers.back(); + gp.Style.Colormap = backup; + gp.ColormapModifiers.pop_back(); + count--; + } +} + +ImU32 NextColormapColorU32() { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentItems != nullptr, "NextColormapColor() needs to be called between BeginPlot() and EndPlot()!"); + int idx = gp.CurrentItems->ColormapIdx % gp.ColormapData.GetKeyCount(gp.Style.Colormap); + ImU32 col = gp.ColormapData.GetKeyColor(gp.Style.Colormap, idx); + gp.CurrentItems->ColormapIdx++; + return col; +} + +ImVec4 NextColormapColor() { return ImGui::ColorConvertU32ToFloat4(NextColormapColorU32()); } + +int GetColormapSize(ImPlot3DColormap cmap) { + ImPlot3DContext& gp = *GImPlot3D; + cmap = cmap == IMPLOT3D_AUTO ? gp.Style.Colormap : cmap; + IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!"); + return gp.ColormapData.GetKeyCount(cmap); +} + +ImU32 GetColormapColorU32(int idx, ImPlot3DColormap cmap) { + ImPlot3DContext& gp = *GImPlot3D; + cmap = cmap == IMPLOT3D_AUTO ? gp.Style.Colormap : cmap; + IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!"); + idx = idx % gp.ColormapData.GetKeyCount(cmap); + return gp.ColormapData.GetKeyColor(cmap, idx); +} + +ImVec4 GetColormapColor(int idx, ImPlot3DColormap cmap) { return ImGui::ColorConvertU32ToFloat4(GetColormapColorU32(idx, cmap)); } + +ImU32 SampleColormapU32(float t, ImPlot3DColormap cmap) { + ImPlot3DContext& gp = *GImPlot3D; + cmap = cmap == IMPLOT3D_AUTO ? gp.Style.Colormap : cmap; + IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!"); + return gp.ColormapData.LerpTable(cmap, t); +} + +ImVec4 SampleColormap(float t, ImPlot3DColormap cmap) { return ImGui::ColorConvertU32ToFloat4(SampleColormapU32(t, cmap)); } + +void RenderColorBar(const ImU32* colors, int size, ImDrawList& DrawList, const ImRect& bounds, bool vert, bool reversed, bool continuous) { + const int n = continuous ? size - 1 : size; + ImU32 col1, col2; + if (vert) { + const float step = bounds.GetHeight() / n; + ImRect rect(bounds.Min.x, bounds.Min.y, bounds.Max.x, bounds.Min.y + step); + for (int i = 0; i < n; ++i) { + if (reversed) { + col1 = colors[size - i - 1]; + col2 = continuous ? colors[size - i - 2] : col1; + } else { + col1 = colors[i]; + col2 = continuous ? colors[i + 1] : col1; + } + DrawList.AddRectFilledMultiColor(rect.Min, rect.Max, col1, col1, col2, col2); + rect.TranslateY(step); + } + } else { + const float step = bounds.GetWidth() / n; + ImRect rect(bounds.Min.x, bounds.Min.y, bounds.Min.x + step, bounds.Max.y); + for (int i = 0; i < n; ++i) { + if (reversed) { + col1 = colors[size - i - 1]; + col2 = continuous ? colors[size - i - 2] : col1; + } else { + col1 = colors[i]; + col2 = continuous ? colors[i + 1] : col1; + } + DrawList.AddRectFilledMultiColor(rect.Min, rect.Max, col1, col2, col2, col1); + rect.TranslateX(step); + } + } +} + +bool ColormapSlider(const char* label, float* t, ImVec4* out, const char* format, ImPlot3DColormap cmap) { + *t = ImClamp(*t, 0.0f, 1.0f); + ImGuiContext& G = *GImGui; + ImGuiWindow* Window = G.CurrentWindow; + if (Window->SkipItems) + return false; + ImPlot3DContext& gp = *GImPlot3D; + cmap = cmap == IMPLOT3D_AUTO ? gp.Style.Colormap : cmap; + IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!"); + const ImU32* keys = gp.ColormapData.GetKeys(cmap); + const int count = gp.ColormapData.GetKeyCount(cmap); + const bool qual = gp.ColormapData.IsQual(cmap); + const ImVec2 pos = ImGui::GetCurrentWindow()->DC.CursorPos; + const float w = ImGui::CalcItemWidth(); + const float h = ImGui::GetFrameHeight(); + const ImRect rect = ImRect(pos.x, pos.y, pos.x + w, pos.y + h); + RenderColorBar(keys, count, *ImGui::GetWindowDrawList(), rect, false, false, !qual); + const ImU32 grab = CalcTextColor(gp.ColormapData.LerpTable(cmap, *t)); + // const ImU32 text = CalcTextColor(gp.ColormapData.LerpTable(cmap,0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBg, IM_COL32_BLACK_TRANS); + ImGui::PushStyleColor(ImGuiCol_FrameBgActive, IM_COL32_BLACK_TRANS); + ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImVec4(1, 1, 1, 0.1f)); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, grab); + ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, grab); + ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 2); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0); + const bool changed = ImGui::SliderFloat(label, t, 0, 1, format); + ImGui::PopStyleColor(5); + ImGui::PopStyleVar(2); + if (out != nullptr) + *out = ImGui::ColorConvertU32ToFloat4(gp.ColormapData.LerpTable(cmap, *t)); + return changed; +} + +//----------------------------------------------------------------------------- +// [SECTION] Context Utils +//----------------------------------------------------------------------------- + +#define IMPLOT3D_APPEND_CMAP(name, qual) ctx->ColormapData.Append(#name, name, sizeof(name) / sizeof(ImU32), qual) +#define IM_RGB(r, g, b) IM_COL32(r, g, b, 255) + +void InitializeContext(ImPlot3DContext* ctx) { + ResetContext(ctx); + + const ImU32 Deep[] = {4289753676, 4283598045, 4285048917, 4283584196, 4289950337, 4284512403, 4291005402, 4287401100, 4285839820, 4291671396}; + const ImU32 Dark[] = {4280031972, 4290281015, 4283084621, 4288892568, 4278222847, 4281597951, 4280833702, 4290740727, 4288256409}; + const ImU32 Pastel[] = {4289639675, 4293119411, 4291161036, 4293184478, 4289124862, 4291624959, 4290631909, 4293712637, 4294111986}; + const ImU32 Paired[] = {4293119554, 4290017311, 4287291314, 4281114675, 4288256763, 4280031971, + 4285513725, 4278222847, 4292260554, 4288298346, 4288282623, 4280834481}; + const ImU32 Viridis[] = {4283695428, 4285867080, 4287054913, 4287455029, 4287526954, 4287402273, + 4286883874, 4285579076, 4283552122, 4280737725, 4280674301}; + const ImU32 Plasma[] = {4287039501, 4288480321, 4289200234, 4288941455, 4287638193, 4286072780, + 4284638433, 4283139314, 4281771772, 4280667900, 4280416752}; + const ImU32 Hot[] = {4278190144, 4278190208, 4278190271, 4278190335, 4278206719, 4278223103, + 4278239231, 4278255615, 4283826175, 4289396735, 4294967295}; + const ImU32 Cool[] = {4294967040, 4294960666, 4294954035, 4294947661, 4294941030, 4294934656, + 4294928025, 4294921651, 4294915020, 4294908646, 4294902015}; + const ImU32 Pink[] = {4278190154, 4282532475, 4284308894, 4285690554, 4286879686, 4287870160, + 4288794330, 4289651940, 4291685869, 4293392118, 4294967295}; + const ImU32 Jet[] = {4289331200, 4294901760, 4294923520, 4294945280, 4294967040, 4289396565, + 4283826090, 4278255615, 4278233855, 4278212095, 4278190335}; + const ImU32 Twilight[] = {IM_RGB(226, 217, 226), IM_RGB(166, 191, 202), IM_RGB(109, 144, 192), IM_RGB(95, 88, 176), + IM_RGB(83, 30, 124), IM_RGB(47, 20, 54), IM_RGB(100, 25, 75), IM_RGB(159, 60, 80), + IM_RGB(192, 117, 94), IM_RGB(208, 179, 158), IM_RGB(226, 217, 226)}; + const ImU32 RdBu[] = {IM_RGB(103, 0, 31), IM_RGB(178, 24, 43), IM_RGB(214, 96, 77), IM_RGB(244, 165, 130), + IM_RGB(253, 219, 199), IM_RGB(247, 247, 247), IM_RGB(209, 229, 240), IM_RGB(146, 197, 222), + IM_RGB(67, 147, 195), IM_RGB(33, 102, 172), IM_RGB(5, 48, 97)}; + const ImU32 BrBG[] = {IM_RGB(84, 48, 5), IM_RGB(140, 81, 10), IM_RGB(191, 129, 45), IM_RGB(223, 194, 125), + IM_RGB(246, 232, 195), IM_RGB(245, 245, 245), IM_RGB(199, 234, 229), IM_RGB(128, 205, 193), + IM_RGB(53, 151, 143), IM_RGB(1, 102, 94), IM_RGB(0, 60, 48)}; + const ImU32 PiYG[] = {IM_RGB(142, 1, 82), IM_RGB(197, 27, 125), IM_RGB(222, 119, 174), IM_RGB(241, 182, 218), + IM_RGB(253, 224, 239), IM_RGB(247, 247, 247), IM_RGB(230, 245, 208), IM_RGB(184, 225, 134), + IM_RGB(127, 188, 65), IM_RGB(77, 146, 33), IM_RGB(39, 100, 25)}; + const ImU32 Spectral[] = {IM_RGB(158, 1, 66), IM_RGB(213, 62, 79), IM_RGB(244, 109, 67), IM_RGB(253, 174, 97), + IM_RGB(254, 224, 139), IM_RGB(255, 255, 191), IM_RGB(230, 245, 152), IM_RGB(171, 221, 164), + IM_RGB(102, 194, 165), IM_RGB(50, 136, 189), IM_RGB(94, 79, 162)}; + const ImU32 Greys[] = {IM_COL32_WHITE, IM_COL32_BLACK}; + + IMPLOT3D_APPEND_CMAP(Deep, true); + IMPLOT3D_APPEND_CMAP(Dark, true); + IMPLOT3D_APPEND_CMAP(Pastel, true); + IMPLOT3D_APPEND_CMAP(Paired, true); + IMPLOT3D_APPEND_CMAP(Viridis, false); + IMPLOT3D_APPEND_CMAP(Plasma, false); + IMPLOT3D_APPEND_CMAP(Hot, false); + IMPLOT3D_APPEND_CMAP(Cool, false); + IMPLOT3D_APPEND_CMAP(Pink, false); + IMPLOT3D_APPEND_CMAP(Jet, false); + IMPLOT3D_APPEND_CMAP(Twilight, false); + IMPLOT3D_APPEND_CMAP(RdBu, false); + IMPLOT3D_APPEND_CMAP(BrBG, false); + IMPLOT3D_APPEND_CMAP(PiYG, false); + IMPLOT3D_APPEND_CMAP(Spectral, false); + IMPLOT3D_APPEND_CMAP(Greys, false); +} + +void ResetContext(ImPlot3DContext* ctx) { + ctx->Plots.Clear(); + ctx->CurrentPlot = nullptr; + ctx->CurrentItems = nullptr; + ctx->CurrentItem = nullptr; + ctx->NextItemData.Reset(); + ctx->Style = ImPlot3DStyle(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Style Utils +//----------------------------------------------------------------------------- + +bool IsColorAuto(const ImVec4& col) { return col.w == -1.0f; } + +bool IsColorAuto(ImPlot3DCol idx) { return IsColorAuto(GImPlot3D->Style.Colors[idx]); } + +ImVec4 GetAutoColor(ImPlot3DCol idx) { + switch (idx) { + case ImPlot3DCol_TitleText: return ImGui::GetStyleColorVec4(ImGuiCol_Text); + case ImPlot3DCol_InlayText: return ImGui::GetStyleColorVec4(ImGuiCol_Text); + case ImPlot3DCol_FrameBg: return ImGui::GetStyleColorVec4(ImGuiCol_FrameBg); + case ImPlot3DCol_PlotBg: return ImGui::GetStyleColorVec4(ImGuiCol_WindowBg); + case ImPlot3DCol_PlotBorder: return ImGui::GetStyleColorVec4(ImGuiCol_Border); + case ImPlot3DCol_LegendBg: return ImGui::GetStyleColorVec4(ImGuiCol_PopupBg); + case ImPlot3DCol_LegendBorder: return ImGui::GetStyleColorVec4(ImGuiCol_Border); + case ImPlot3DCol_LegendText: return ImGui::GetStyleColorVec4(ImGuiCol_Text); + case ImPlot3DCol_AxisText: return ImGui::GetStyleColorVec4(ImGuiCol_Text); + case ImPlot3DCol_AxisGrid: return ImGui::GetStyleColorVec4(ImGuiCol_Text) * ImVec4(1, 1, 1, 0.25f); + case ImPlot3DCol_AxisTick: return GetStyleColorVec4(ImPlot3DCol_AxisGrid); + case ImPlot3DCol_AxisBg: return ImVec4(0, 0, 0, 0); + case ImPlot3DCol_AxisBgHovered: return ImGui::GetStyleColorVec4(ImGuiCol_ButtonHovered); + case ImPlot3DCol_AxisBgActive: return ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive); + default: return IMPLOT3D_AUTO_COL; + } +} + +const char* GetStyleColorName(ImPlot3DCol idx) { + static const char* color_names[ImPlot3DCol_COUNT] = { + "TitleText", "InlayText", "FrameBg", "PlotBg", "PlotBorder", "LegendBg", "LegendBorder", + "LegendText", "AxisText", "AxisGrid", "AxisTick", "AxisBg", "AxisBgHovered", "AxisBgActive", + }; + return color_names[idx]; +} + +const ImPlot3DNextItemData& GetItemData() { return GImPlot3D->NextItemData; } + +} // namespace ImPlot3D + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot3DPoint +//----------------------------------------------------------------------------- + +ImPlot3DPoint ImPlot3DPoint::operator*(double rhs) const { return ImPlot3DPoint(x * rhs, y * rhs, z * rhs); } +ImPlot3DPoint ImPlot3DPoint::operator/(double rhs) const { return ImPlot3DPoint(x / rhs, y / rhs, z / rhs); } +ImPlot3DPoint ImPlot3DPoint::operator+(const ImPlot3DPoint& rhs) const { return ImPlot3DPoint(x + rhs.x, y + rhs.y, z + rhs.z); } +ImPlot3DPoint ImPlot3DPoint::operator-(const ImPlot3DPoint& rhs) const { return ImPlot3DPoint(x - rhs.x, y - rhs.y, z - rhs.z); } +ImPlot3DPoint ImPlot3DPoint::operator*(const ImPlot3DPoint& rhs) const { return ImPlot3DPoint(x * rhs.x, y * rhs.y, z * rhs.z); } +ImPlot3DPoint ImPlot3DPoint::operator/(const ImPlot3DPoint& rhs) const { return ImPlot3DPoint(x / rhs.x, y / rhs.y, z / rhs.z); } +ImPlot3DPoint ImPlot3DPoint::operator-() const { return ImPlot3DPoint(-x, -y, -z); } + +ImPlot3DPoint& ImPlot3DPoint::operator*=(double rhs) { + x *= rhs; + y *= rhs; + z *= rhs; + return *this; +} +ImPlot3DPoint& ImPlot3DPoint::operator/=(double rhs) { + x /= rhs; + y /= rhs; + z /= rhs; + return *this; +} +ImPlot3DPoint& ImPlot3DPoint::operator+=(const ImPlot3DPoint& rhs) { + x += rhs.x; + y += rhs.y; + z += rhs.z; + return *this; +} +ImPlot3DPoint& ImPlot3DPoint::operator-=(const ImPlot3DPoint& rhs) { + x -= rhs.x; + y -= rhs.y; + z -= rhs.z; + return *this; +} +ImPlot3DPoint& ImPlot3DPoint::operator*=(const ImPlot3DPoint& rhs) { + x *= rhs.x; + y *= rhs.y; + z *= rhs.z; + return *this; +} +ImPlot3DPoint& ImPlot3DPoint::operator/=(const ImPlot3DPoint& rhs) { + x /= rhs.x; + y /= rhs.y; + z /= rhs.z; + return *this; +} + +bool ImPlot3DPoint::operator==(const ImPlot3DPoint& rhs) const { return x == rhs.x && y == rhs.y && z == rhs.z; } +bool ImPlot3DPoint::operator!=(const ImPlot3DPoint& rhs) const { return !(*this == rhs); } + +double ImPlot3DPoint::Dot(const ImPlot3DPoint& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z; } + +ImPlot3DPoint ImPlot3DPoint::Cross(const ImPlot3DPoint& rhs) const { + return ImPlot3DPoint(y * rhs.z - z * rhs.y, z * rhs.x - x * rhs.z, x * rhs.y - y * rhs.x); +} + +double ImPlot3DPoint::Length() const { return sqrt(x * x + y * y + z * z); } + +double ImPlot3DPoint::LengthSquared() const { return x * x + y * y + z * z; } + +void ImPlot3DPoint::Normalize() { + double l = Length(); + x /= l; + y /= l; + z /= l; +} + +ImPlot3DPoint ImPlot3DPoint::Normalized() const { + double l = Length(); + return ImPlot3DPoint(x / l, y / l, z / l); +} + +ImPlot3DPoint operator*(double lhs, const ImPlot3DPoint& rhs) { return ImPlot3DPoint(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z); } + +bool ImPlot3DPoint::IsNaN() const { return ImPlot3D::ImNan(x) || ImPlot3D::ImNan(y) || ImPlot3D::ImNan(z); } + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot3DBox +//----------------------------------------------------------------------------- + +void ImPlot3DBox::Expand(const ImPlot3DPoint& point) { + Min.x = ImMin(Min.x, point.x); + Min.y = ImMin(Min.y, point.y); + Min.z = ImMin(Min.z, point.z); + Max.x = ImMax(Max.x, point.x); + Max.y = ImMax(Max.y, point.y); + Max.z = ImMax(Max.z, point.z); +} + +bool ImPlot3DBox::Contains(const ImPlot3DPoint& point) const { + return (point.x >= Min.x && point.x <= Max.x) && (point.y >= Min.y && point.y <= Max.y) && (point.z >= Min.z && point.z <= Max.z); +} + +bool ImPlot3DBox::ClipLineSegment(const ImPlot3DPoint& p0, const ImPlot3DPoint& p1, ImPlot3DPoint& p0_clipped, ImPlot3DPoint& p1_clipped) const { + // Check if the line segment is completely inside the box + if (Contains(p0) && Contains(p1)) { + p0_clipped = p0; + p1_clipped = p1; + return true; + } + + // Perform Liang-Barsky 3D clipping + double t0 = 0.0; + double t1 = 1.0; + ImPlot3DPoint d = p1 - p0; + + // Define the clipping boundaries + const double xmin = Min.x, xmax = Max.x; + const double ymin = Min.y, ymax = Max.y; + const double zmin = Min.z, zmax = Max.z; + + // Lambda function to update t0 and t1 + auto update = [&](double p, double q) -> bool { + if (p == 0.0) { + if (q < 0.0) + return false; // Line is parallel and outside the boundary + else + return true; // Line is parallel and inside or coincident with boundary + } + double r = q / p; + if (p < 0.0) { + if (r > t1) + return false; // Line is outside + if (r > t0) + t0 = r; // Move up t0 + } else { + if (r < t0) + return false; // Line is outside + if (r < t1) + t1 = r; // Move down t1 + } + return true; + }; + + // Clip against each boundary + if (!update(-d.x, p0.x - xmin)) + return false; // Left + if (!update(d.x, xmax - p0.x)) + return false; // Right + if (!update(-d.y, p0.y - ymin)) + return false; // Bottom + if (!update(d.y, ymax - p0.y)) + return false; // Top + if (!update(-d.z, p0.z - zmin)) + return false; // Near + if (!update(d.z, zmax - p0.z)) + return false; // Far + + // Compute clipped points + p0_clipped = p0 + d * t0; + p1_clipped = p0 + d * t1; + + return true; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot3DRange +//----------------------------------------------------------------------------- + +void ImPlot3DRange::Expand(double value) { + Min = ImMin(Min, value); + Max = ImMax(Max, value); +} + +bool ImPlot3DRange::Contains(double value) const { return value >= Min && value <= Max; } + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot3DQuat +//----------------------------------------------------------------------------- + +ImPlot3DQuat::ImPlot3DQuat(double _angle, const ImPlot3DPoint& _axis) { + double half_angle = _angle * 0.5; + double s = sin(half_angle); + x = s * _axis.x; + y = s * _axis.y; + z = s * _axis.z; + w = cos(half_angle); +} + +ImPlot3DQuat ImPlot3DQuat::FromTwoVectors(const ImPlot3DPoint& v0, const ImPlot3DPoint& v1) { + ImPlot3DQuat q; + + // Compute the dot product and lengths of the vectors + double dot = v0.Dot(v1); + double length_v0 = v0.Length(); + double length_v1 = v1.Length(); + + // Normalize the dot product + double normalized_dot = dot / (length_v0 * length_v1); + + // Handle edge cases: if vectors are very close or identical + const double epsilon = 1e-6; + if (ImAbs(normalized_dot - 1.0) < epsilon) { + // v0 and v1 are nearly identical; return an identity quaternion + q.x = 0.0; + q.y = 0.0; + q.z = 0.0; + q.w = 1.0; + return q; + } + + // Handle edge case: if vectors are opposite + if (ImAbs(normalized_dot + 1.0) < epsilon) { + // v0 and v1 are opposite; choose an arbitrary orthogonal axis + ImPlot3DPoint arbitrary_axis = ImAbs(v0.x) > ImAbs(v0.z) ? ImPlot3DPoint(-v0.y, v0.x, 0.0) : ImPlot3DPoint(0.0, -v0.z, v0.y); + arbitrary_axis.Normalize(); + q.x = arbitrary_axis.x; + q.y = arbitrary_axis.y; + q.z = arbitrary_axis.z; + q.w = 0.0; + return q; + } + + // General case + ImPlot3DPoint axis = v0.Cross(v1); + axis.Normalize(); + double angle = acos(normalized_dot); + double half_angle = angle * 0.5; + double s = sin(half_angle); + q.x = s * axis.x; + q.y = s * axis.y; + q.z = s * axis.z; + q.w = cos(half_angle); + + return q; +} + +ImPlot3DQuat ImPlot3DQuat::FromElAz(double elevation, double azimuth) { + // Create quaternions for azimuth and elevation + ImPlot3DQuat azimuth_quat(azimuth, ImPlot3DPoint(0.0, 0.0, 1.0)); // Rotate around Z-axis + ImPlot3DQuat elevation_quat(elevation, ImPlot3DPoint(1.0, 0.0, 0.0)); // Rotate around X-axis + ImPlot3DQuat zero_quat(-IM_PI / 2, ImPlot3DPoint(1.0, 0.0, 0.0)); // Rotate to zero azimuth/elevation orientation + + // Combine rotations + return elevation_quat * zero_quat * azimuth_quat; +} + +double ImPlot3DQuat::Length() const { return sqrt(x * x + y * y + z * z + w * w); } + +ImPlot3DQuat ImPlot3DQuat::Normalized() const { + double l = Length(); + return ImPlot3DQuat(x / l, y / l, z / l, w / l); +} + +ImPlot3DQuat ImPlot3DQuat::Conjugate() const { return ImPlot3DQuat(-x, -y, -z, w); } + +ImPlot3DQuat ImPlot3DQuat::Inverse() const { + double l_squared = x * x + y * y + z * z + w * w; + return ImPlot3DQuat(-x / l_squared, -y / l_squared, -z / l_squared, w / l_squared); +} + +ImPlot3DQuat ImPlot3DQuat::operator*(const ImPlot3DQuat& rhs) const { + return ImPlot3DQuat(w * rhs.x + x * rhs.w + y * rhs.z - z * rhs.y, w * rhs.y - x * rhs.z + y * rhs.w + z * rhs.x, + w * rhs.z + x * rhs.y - y * rhs.x + z * rhs.w, w * rhs.w - x * rhs.x - y * rhs.y - z * rhs.z); +} + +ImPlot3DQuat& ImPlot3DQuat::Normalize() { + double l = Length(); + x /= l; + y /= l; + z /= l; + w /= l; + return *this; +} + +ImPlot3DPoint ImPlot3DQuat::operator*(const ImPlot3DPoint& point) const { + // Extract vector part of the quaternion + ImPlot3DPoint qv(x, y, z); + + // Compute the cross products needed for rotation + ImPlot3DPoint uv = qv.Cross(point); // uv = qv x point + ImPlot3DPoint uuv = qv.Cross(uv); // uuv = qv x uv + + // Compute the rotated vector + return point + (uv * w * 2.0) + (uuv * 2.0); +} + +bool ImPlot3DQuat::operator==(const ImPlot3DQuat& rhs) const { return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w; } + +bool ImPlot3DQuat::operator!=(const ImPlot3DQuat& rhs) const { return !(*this == rhs); } + +ImPlot3DQuat ImPlot3DQuat::Slerp(const ImPlot3DQuat& q1, const ImPlot3DQuat& q2, double t) { + // Clamp t to [0, 1] + t = ImClamp(t, 0.0, 1.0); + + // Compute the dot product (cosine of the angle between quaternions) + double dot = q1.x * q2.x + q1.y * q2.y + q1.z * q2.z + q1.w * q2.w; + + // If the dot product is negative, negate one quaternion to take the shorter path + ImPlot3DQuat q2_ = q2; + if (dot < 0.0) { + q2_ = ImPlot3DQuat(-q2.x, -q2.y, -q2.z, -q2.w); + dot = -dot; + } + + // If the quaternions are very close, use linear interpolation to avoid numerical instability + if (dot > 0.9995) { + return ImPlot3DQuat(q1.x + t * (q2_.x - q1.x), q1.y + t * (q2_.y - q1.y), q1.z + t * (q2_.z - q1.z), q1.w + t * (q2_.w - q1.w)).Normalized(); + } + + // Compute the angle and the interpolation factors + double theta_0 = acos(dot); // Angle between input quaternions + double theta = theta_0 * t; // Interpolated angle + double sin_theta = sin(theta); // Sine of interpolated angle + double sin_theta_0 = sin(theta_0); // Sine of original angle + + double s1 = cos(theta) - dot * sin_theta / sin_theta_0; + double s2 = sin_theta / sin_theta_0; + + // Interpolate and return the result + return ImPlot3DQuat(s1 * q1.x + s2 * q2_.x, s1 * q1.y + s2 * q2_.y, s1 * q1.z + s2 * q2_.z, s1 * q1.w + s2 * q2_.w); +} + +double ImPlot3DQuat::Dot(const ImPlot3DQuat& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z + w * rhs.w; } + +//----------------------------------------------------------------------------- +// [SECTION] ImDrawList3D +//----------------------------------------------------------------------------- + +void ImDrawList3D::PrimReserve(int idx_count, int vtx_count) { + IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0 && idx_count % 3 == 0); + + int vtx_buffer_old_size = VtxBuffer.Size; + VtxBuffer.resize(vtx_buffer_old_size + vtx_count); + _VtxWritePtr = VtxBuffer.Data + vtx_buffer_old_size; + + int idx_buffer_old_size = IdxBuffer.Size; + IdxBuffer.resize(idx_buffer_old_size + idx_count); + _IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size; + + int z_buffer_old_size = ZBuffer.Size; + ZBuffer.resize(z_buffer_old_size + idx_count / 3); + _ZWritePtr = ZBuffer.Data + z_buffer_old_size; +} + +void ImDrawList3D::PrimUnreserve(int idx_count, int vtx_count) { + IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0 && idx_count % 3 == 0); + + VtxBuffer.shrink(VtxBuffer.Size - vtx_count); + IdxBuffer.shrink(IdxBuffer.Size - idx_count); + ZBuffer.shrink(ZBuffer.Size - idx_count / 3); +} + +void ImDrawList3D::SetTexture(ImTextureRef tex_ref) { + if (_TextureBuffer.empty()) { + // First texture assignment + _TextureBuffer.push_back({tex_ref, _VtxCurrentIdx}); + return; + } + + ImTextureBufferItem& prev_item = _TextureBuffer.back(); + if (prev_item.VtxIdx == _VtxCurrentIdx) { + // Same vertex index: update existing texture ID + prev_item.TexRef = tex_ref; + + // If the previous texture was the same, remove current texture + if (_TextureBuffer.Size >= 2) { + if (_TextureBuffer[_TextureBuffer.Size - 2].TexRef == tex_ref) { + _TextureBuffer.pop_back(); + } + } + } else if (prev_item.TexRef != tex_ref) { + // New vertex index and different texture: insert new item + _TextureBuffer.push_back({tex_ref, _VtxCurrentIdx}); + } +} + +void ImDrawList3D::ResetTexture() { SetTexture(ImTextureID(0)); } + +#ifdef IMGUI_HAS_TEXTURES +#define SET_TEX_REF(cmd, tex_ref) (cmd).TexRef = (tex_ref) +#define GET_TEX_REF(cmd) (cmd).TexRef +#else +#define SET_TEX_REF(cmd, tex_ref) (cmd).TextureId = (tex_ref) +#define GET_TEX_REF(cmd) (cmd).TextureId +#endif + +void ImDrawList3D::SortedMoveToImGuiDrawList() { + ImDrawList& draw_list = *ImGui::GetWindowDrawList(); + + const int tri_count = ZBuffer.Size; + if (tri_count == 0) { + // No triangles, just reset buffers and return + ResetBuffers(); + return; + } + + // Build an array of (z, tri_idx) + struct TriRef { + double z; + int tri_idx; + }; + TriRef* tris = (TriRef*)IM_ALLOC(sizeof(TriRef) * tri_count); + for (int i = 0; i < tri_count; i++) { + tris[i].z = ZBuffer[i]; + tris[i].tri_idx = i; + } + + // Sort by z (distance from viewer) + ImQsort(tris, (size_t)tri_count, sizeof(TriRef), [](const void* a, const void* b) { + double za = ((const TriRef*)a)->z; + double zb = ((const TriRef*)b)->z; + return (za < zb) ? -1 : (za > zb) ? 1 : 0; + }); + + // Reserve space in the ImGui draw list + draw_list.PrimReserve(IdxBuffer.Size, VtxBuffer.Size); + + // Copy vertices (no reordering needed) + memcpy(draw_list._VtxWritePtr, VtxBuffer.Data, VtxBuffer.Size * sizeof(ImDrawVert)); + unsigned int idx_offset = draw_list._VtxCurrentIdx; + draw_list._VtxWritePtr += VtxBuffer.Size; + draw_list._VtxCurrentIdx += (unsigned int)VtxBuffer.Size; + + // Maximum index allowed to not overflow ImDrawIdx + unsigned int max_index_allowed = MaxIdx() - idx_offset; + + // Copy indices with triangle sorting based on distance from viewer + ImDrawIdx* idx_out_begin = draw_list._IdxWritePtr; + ImDrawIdx* idx_out = idx_out_begin; + ImDrawIdx* idx_in = IdxBuffer.Data; + for (int i = 0; i < tri_count; i++) { + int tri_i = tris[i].tri_idx; + int base_idx = tri_i * 3; + unsigned int i0 = (unsigned int)idx_in[base_idx + 0]; + unsigned int i1 = (unsigned int)idx_in[base_idx + 1]; + unsigned int i2 = (unsigned int)idx_in[base_idx + 2]; + + // Check if after adding offset any of these indices exceed max_index_allowed + if (i0 > max_index_allowed || i1 > max_index_allowed || i2 > max_index_allowed) + continue; + + idx_out[0] = (ImDrawIdx)(i0 + idx_offset); + idx_out[1] = (ImDrawIdx)(i1 + idx_offset); + idx_out[2] = (ImDrawIdx)(i2 + idx_offset); + + idx_out += 3; + } + ImDrawIdx* idx_out_end = idx_out; + draw_list._IdxWritePtr = idx_out_end; + + // If multiple textures were used (e.g. PlotImage was called), generate multiple ImDrawCmd + if (_TextureBuffer.Size > 1) { + ImTextureRef default_tex = GET_TEX_REF(draw_list._CmdHeader); + ImTextureRef curr_tex = default_tex; + + // Remove elements reserved from PrimReserve + draw_list.CmdBuffer.back().ElemCount -= IdxBuffer.Size; + ImDrawIdx* last_cmd_buffer_idx = idx_out_begin; + + // For each triangle added to the draw_list + for (idx_out = idx_out_begin; idx_out < idx_out_end; idx_out += 3) { + // Get index of first vertex in the triangle + unsigned int vtx_idx = (unsigned int)(*idx_out - idx_offset); + + // Get the texture for this triangle + const ImTextureRef invalid_tex = ImTextureID(0); + ImTextureRef tri_tex = invalid_tex; + for (int j = 0; j < _TextureBuffer.Size; j++) + if (vtx_idx >= _TextureBuffer[j].VtxIdx) + tri_tex = _TextureBuffer[j].TexRef; + + // If tri_tex is invalid, the default texture should be used + if (tri_tex == invalid_tex) + tri_tex = default_tex; + + if (tri_tex != curr_tex) { + // Update element count of previous draw cmd + draw_list.CmdBuffer.back().ElemCount += (unsigned int)(idx_out - last_cmd_buffer_idx); + last_cmd_buffer_idx = idx_out; + + // Set custom texture + curr_tex = tri_tex; + SET_TEX_REF(draw_list._CmdHeader, curr_tex); + + // Add new draw cmd for the new texture + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = draw_list._CmdHeader.ClipRect; + SET_TEX_REF(draw_cmd, GET_TEX_REF(draw_list._CmdHeader)); + draw_cmd.VtxOffset = draw_list._CmdHeader.VtxOffset; + draw_cmd.IdxOffset = (unsigned int)(idx_out - draw_list.IdxBuffer.Data); + draw_list.CmdBuffer.push_back(draw_cmd); + } + } + // Flush last elements to cmd buffer + draw_list.CmdBuffer.back().ElemCount += (unsigned int)(&draw_list.IdxBuffer.back() - last_cmd_buffer_idx + 1); + + // Check if the last texture was not the default texture + if (curr_tex != default_tex) { + // Restore default texture + SET_TEX_REF(draw_list._CmdHeader, default_tex); + + // Flush last draw cmd with custom texture + draw_list.AddDrawCmd(); + } + } + + // Reset buffers since we've moved them + ResetBuffers(); + + IM_FREE(tris); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot3DAxis +//----------------------------------------------------------------------------- + +bool ImPlot3DAxis::HasLabel() const { return !Label.empty() && !ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_NoLabel); } +bool ImPlot3DAxis::HasGridLines() const { return !ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_NoGridLines); } +bool ImPlot3DAxis::HasTickLabels() const { return !ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_NoTickLabels); } +bool ImPlot3DAxis::HasTickMarks() const { return !ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_NoTickMarks); } +bool ImPlot3DAxis::IsAutoFitting() const { return ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_AutoFit); } + +void ImPlot3DAxis::ExtendFit(double value) { + // Only extend fit with values that are within the constraint range + // This is critical for log scale where negative/zero values should be ignored + if (!ImPlot3D::ImNanOrInf(value) && value >= ConstraintRange.Min && value <= ConstraintRange.Max) { + FitExtents.Min = ImMin(FitExtents.Min, value); + FitExtents.Max = ImMax(FitExtents.Max, value); + } +} + +void ImPlot3DAxis::ApplyFit() { + if (!IsLockedMin() && !ImPlot3D::ImNanOrInf(FitExtents.Min)) + Range.Min = FitExtents.Min; + if (!IsLockedMax() && !ImPlot3D::ImNanOrInf(FitExtents.Max)) + Range.Max = FitExtents.Max; + if (ImPlot3D::ImAlmostEqual(Range.Min, Range.Max)) { + Range.Max += 0.5; + Range.Min -= 0.5; + } + Constrain(); + UpdateTransformCache(); + FitExtents.Min = HUGE_VAL; + FitExtents.Max = -HUGE_VAL; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot3DPlot +//----------------------------------------------------------------------------- + +void ImPlot3DPlot::ExtendFit(const ImPlot3DPoint& point) { + for (int i = 0; i < 3; i++) { + if (!ImPlot3D::ImNanOrInf(point[i]) && Axes[i].FitThisFrame) + Axes[i].ExtendFit(point[i]); + } +} + +ImPlot3DPoint ImPlot3DPlot::RangeMin() const { return ImPlot3DPoint(Axes[0].Range.Min, Axes[1].Range.Min, Axes[2].Range.Min); } + +ImPlot3DPoint ImPlot3DPlot::RangeMax() const { return ImPlot3DPoint(Axes[0].Range.Max, Axes[1].Range.Max, Axes[2].Range.Max); } + +ImPlot3DPoint ImPlot3DPlot::RangeCenter() const { + return ImPlot3DPoint((Axes[0].Range.Min + Axes[0].Range.Max) * 0.5f, (Axes[1].Range.Min + Axes[1].Range.Max) * 0.5f, + (Axes[2].Range.Min + Axes[2].Range.Max) * 0.5f); +} + +void ImPlot3DPlot::SetRange(const ImPlot3DPoint& min, const ImPlot3DPoint& max) { + Axes[0].SetRange(min.x, max.x); + Axes[1].SetRange(min.y, max.y); + Axes[2].SetRange(min.z, max.z); +} + +float ImPlot3DPlot::GetViewScale() const { + return ImMin(PlotRect.GetWidth(), PlotRect.GetHeight()) / 1.8f * ImPlot3D::GImPlot3D->Style.ViewScaleFactor; +} + +ImPlot3DPoint ImPlot3DPlot::GetBoxScale() const { return ImPlot3DPoint(Axes[0].NDCSize(), Axes[1].NDCSize(), Axes[2].NDCSize()); } + +void ImPlot3DPlot::ApplyEqualAspect(ImAxis3D ref_axis) { + double aspect = Axes[ref_axis].GetAspect(); + for (int i = 0; i < 3; i++) { + if (i != ref_axis && !Axes[i].IsInputLocked()) { + Axes[i].SetAspect(aspect); + } + } +} + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot3DStyle +//----------------------------------------------------------------------------- + +ImPlot3DStyle::ImPlot3DStyle() { + // Item style + LineWeight = 1.0f; + Marker = ImPlot3DMarker_None; + MarkerSize = 4.0f; + FillAlpha = 1.0f; + // Plot style + PlotDefaultSize = ImVec2(400, 400); + PlotMinSize = ImVec2(200, 200); + PlotPadding = ImVec2(10, 10); + LabelPadding = ImVec2(5, 5); + ViewScaleFactor = 1.0f; + // Legend style + LegendPadding = ImVec2(10, 10); + LegendInnerPadding = ImVec2(5, 5); + LegendSpacing = ImVec2(5, 0); + // Colors + ImPlot3D::StyleColorsAuto(this); + Colormap = ImPlot3DColormap_Deep; +}; + +//----------------------------------------------------------------------------- +// [SECTION] Metrics +//----------------------------------------------------------------------------- + +void ShowTicksMetrics(const ImPlot3DTicker& ticker) { ImGui::BulletText("Size: %d", ticker.TickCount()); } + +void ShowAxisMetrics(const ImPlot3DAxis& axis) { + ImGui::BulletText("Label: %s", axis.GetLabel()); + ImGui::BulletText("Flags: 0x%08X", axis.Flags); + // Range + ImGui::BulletText("Range: [%f,%f]", axis.Range.Min, axis.Range.Max); + ImGui::BulletText("NDC Scale: %f", axis.NDCScale); + ImGui::BulletText("NDC Range: [%f,%f]", -0.5f * axis.NDCScale, 0.5f * axis.NDCScale); + ImGui::BulletText("Aspect: %f", axis.GetAspect()); + // Ticks + ImGui::BulletText("ShowDefaultTicks: %s", axis.ShowDefaultTicks ? "true" : "false"); + // Fit data + ImGui::BulletText("FitThisFrame: %s", axis.FitThisFrame ? "true" : "false"); + ImGui::BulletText("FitExtents: [%f,%f]", axis.FitExtents.Min, axis.FitExtents.Min); + // Constraints + ImGui::BulletText("ConstraintRange: [%f,%f]", axis.ConstraintRange.Min, axis.ConstraintRange.Min); + ImGui::BulletText("ConstraintZoom: [%f,%f]", axis.ConstraintZoom.Min, axis.ConstraintZoom.Min); + // User input + ImGui::BulletText("Hovered: %s", axis.Hovered ? "true" : "false"); + ImGui::BulletText("Held: %s", axis.Held ? "true" : "false"); + + if (ImGui::TreeNode("Ticks")) { + ShowTicksMetrics(axis.Ticker); + ImGui::TreePop(); + } +} + +void ImPlot3D::ShowMetricsWindow(bool* p_popen) { + static bool show_frame_rects = false; + static bool show_canvas_rects = false; + static bool show_plot_rects = false; + static bool show_plot_box = false; + static bool show_axis_line = false; + static bool show_axis_corner_indexes = false; + static bool show_axis_face_indexes = false; + static bool show_axis_edge_indexes = false; + static bool show_legend_rects = false; + + ImDrawList& fg = *ImGui::GetForegroundDrawList(); + + ImPlot3DContext& gp = *GImPlot3D; + ImGuiIO& io = ImGui::GetIO(); + ImGui::Begin("Metrics (ImPlot3D)", p_popen); + ImGui::Text("ImPlot3D " IMPLOT3D_VERSION); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::Text("Mouse Position: [%.0f,%.0f]", io.MousePos.x, io.MousePos.y); + ImGui::Separator(); + if (ImGui::TreeNode("Tools")) { + if (ImGui::Button("Bust Plot Cache")) + BustPlotCache(); + ImGui::SameLine(); + if (ImGui::Button("Bust Item Cache")) + BustItemCache(); + ImGui::Checkbox("Show Frame Rects", &show_frame_rects); + ImGui::Checkbox("Show Canvas Rects", &show_canvas_rects); + ImGui::Checkbox("Show Plot Rects", &show_plot_rects); + ImGui::Checkbox("Show Plot Box", &show_plot_box); + ImGui::Checkbox("Show Axis Line", &show_axis_line); + ImGui::Checkbox("Show Axis Corner Indexes", &show_axis_corner_indexes); + ImGui::Checkbox("Show Axis Face Indexes", &show_axis_face_indexes); + ImGui::Checkbox("Show Axis Edge Indexes", &show_axis_edge_indexes); + ImGui::Checkbox("Show Legend Rects", &show_legend_rects); + ImGui::TreePop(); + } + const int n_plots = gp.Plots.GetBufSize(); + bool active_faces[3]; + ImVec2 corners_pix[8]; + ImPlot3DPoint corners[8]; + int plane_2d = -1; + int axis_corners[3][2]; + char buff[16]; + // Enum used to indicate how a certain type will be displayed + enum class DisplayedType { + Hidden, // Hidden type that is not displayed. Used when the object should not be displayed. Will be used when: + // 1. 2D plot and this type should not be used, + // 2. The flag show_plot_box is disabled + Active, // Part of the faces of the box that are active + NotActive // Part of the faces of the box that are not active when show_plot_box is active + }; + + // Render rectangles + for (int p = 0; p < n_plots; ++p) { + ImPlot3DPlot& plot = *gp.Plots.GetByIndex(p); + if (show_frame_rects) + fg.AddRect(plot.FrameRect.Min, plot.FrameRect.Max, IM_COL32(255, 0, 255, 255)); + if (show_canvas_rects) + fg.AddRect(plot.CanvasRect.Min, plot.CanvasRect.Max, IM_COL32(0, 255, 255, 255)); + if (show_plot_rects) + fg.AddRect(plot.PlotRect.Min, plot.PlotRect.Max, IM_COL32(255, 255, 0, 255)); + if (show_plot_box || show_axis_line || show_axis_corner_indexes || show_axis_face_indexes || show_axis_edge_indexes) + GetAxesParameters(plot, active_faces, corners_pix, corners, plane_2d, axis_corners); + if (show_plot_box || show_axis_edge_indexes) { + // Determine which display type each of the edges are + DisplayedType edge_types[12]; + for (int e = 0; e < 12; e++) { + if (plane_2d == -1 && show_plot_box) + edge_types[e] = DisplayedType::NotActive; + else + edge_types[e] = DisplayedType::Hidden; + } + for (int a = 0; a < 3; a++) { + int face_idx = a + 3 * active_faces[a]; + for (size_t i = 0; (plane_2d == -1 || a == plane_2d) && i < 4; i++) + edge_types[face_edges[face_idx][i]] = DisplayedType::Active; + } + + // Go through each edge and use the display type + for (int e = 0; e < 12; e++) { + int idx0 = edges[e][0]; + int idx1 = edges[e][1]; + + if (show_plot_box) { + // Draw different lines depending on the type that the renderer thinks it is + if (edge_types[e] == DisplayedType::Active) + fg.AddLine(corners_pix[idx0], corners_pix[idx1], IM_COL32(255, 200, 0, 255)); + else if (edge_types[e] == DisplayedType::NotActive) + fg.AddLine(corners_pix[idx0], corners_pix[idx1], IM_COL32(100, 255, 0, 125)); + // If the render edge type is Hidden then there this edge does not get rendered + } + if (show_axis_edge_indexes) { + if (edge_types[e] == DisplayedType::Active || edge_types[e] == DisplayedType::NotActive) { + // Display the text in the middle between the points and at the same angle between the two points + ImVec2 edge_middle = (corners_pix[idx0] + corners_pix[idx1]) / 2; + ImVec2 point_difference = (corners_pix[idx1] - corners_pix[idx0]); + float angle = ImAtan2(-point_difference.y, point_difference.x); + // Adjust angle to keep labels upright + if (angle > IM_PI * 0.5f) + angle -= IM_PI; + if (angle < -IM_PI * 0.5f) + angle += IM_PI; + + ImFormatString(buff, IM_ARRAYSIZE(buff), "E%d", e); + AddTextRotated(&fg, edge_middle, angle, IM_COL32(200, 0, 0, 200), buff); + } + } + } + } + if (show_axis_line) { + // For each axis plot a line between the axis corners + for (int a = 0; a < 3; a++) { + if (plane_2d != -1 && a == plane_2d) + continue; + int idx0 = axis_corners[a][0]; + int idx1 = axis_corners[a][1]; + + // Draw axis line + ImVec2 axis_start_pix = corners_pix[idx0]; + ImVec2 axis_end_pix = corners_pix[idx1]; + fg.AddLine(axis_start_pix, axis_end_pix, IM_COL32(0, 255, 255, 255)); + } + } + if (show_axis_corner_indexes) { + // Determine which display type each of the corners are + DisplayedType corner_types[8]; + for (int c = 0; c < 8; c++) { + if (plane_2d == -1 && show_plot_box) + corner_types[c] = DisplayedType::NotActive; + else + corner_types[c] = DisplayedType::Hidden; + } + for (int a = 0; a < 3; a++) { + int face_idx = a + 3 * active_faces[a]; + for (size_t i = 0; (plane_2d == -1 || a == plane_2d) && i < 4; i++) + corner_types[faces[face_idx][i]] = DisplayedType::Active; + } + // Go through each corner and use the display type + for (int c = 0; c < 8; c++) { + if (corner_types[c] == DisplayedType::Active || corner_types[c] == DisplayedType::NotActive) { + ImVec2 corner = corners_pix[c]; + ImFormatString(buff, IM_ARRAYSIZE(buff), "C%d", c); + AddTextRotated(&fg, corner, 0.0f, IM_COL32(0, 200, 0, 200), buff); + } + } + } + if (show_axis_face_indexes) { + // Go through each axis and then face to display the face index + for (int a = 0; a < 3; a++) { + for (int f = 0; f < 2; f++) { + if ((plane_2d == -1 || a == plane_2d) && (f == int(active_faces[a]) || show_plot_box)) { + const int face_idx = a + 3 * f; + const int* face_indexes = faces[face_idx]; + // Display the text in the middle of the square by determining the point between two of opposite corner pixels + ImVec2 middle_of_face_sqaure = (corners_pix[face_indexes[0]] + corners_pix[face_indexes[2]]) / 2; + ImFormatString(buff, IM_ARRAYSIZE(buff), "F%d", face_idx); + AddTextRotated(&fg, middle_of_face_sqaure, 0.0f, IM_COL32(0, 200, 200, 200), buff); + } + } + } + } + if (show_legend_rects && plot.Items.GetLegendCount() > 0) { + fg.AddRect(plot.Items.Legend.Rect.Min, plot.Items.Legend.Rect.Max, IM_COL32(255, 192, 0, 255)); + fg.AddRect(plot.Items.Legend.RectClamped.Min, plot.Items.Legend.RectClamped.Max, IM_COL32(255, 128, 0, 255)); + } + } + if (ImGui::TreeNode("Plots", "Plots (%d)", n_plots)) { + for (int p = 0; p < n_plots; ++p) { + ImPlot3DPlot& plot = *gp.Plots.GetByIndex(p); + ImGui::PushID(p); + if (ImGui::TreeNode("Plot", "Plot [0x%08X]", plot.ID)) { + int n_items = plot.Items.GetItemCount(); + if (ImGui::TreeNode("Items", "Items (%d)", n_items)) { + for (int i = 0; i < n_items; ++i) { + ImPlot3DItem* item = plot.Items.GetItemByIndex(i); + ImGui::PushID(i); + if (ImGui::TreeNode("Item", "Item [0x%08X]", item->ID)) { + ImGui::Bullet(); + ImGui::Checkbox("Show", &item->Show); + ImGui::Bullet(); + ImVec4 temp = ImGui::ColorConvertU32ToFloat4(item->Color); + if (ImGui::ColorEdit4("Color", &temp.x, ImGuiColorEditFlags_NoInputs)) + item->Color = ImGui::ColorConvertFloat4ToU32(temp); + + ImGui::BulletText("NameOffset: %d", item->NameOffset); + ImGui::BulletText("Name: %s", item->NameOffset != -1 ? plot.Items.Legend.Labels.Buf.Data + item->NameOffset : "N/A"); + ImGui::BulletText("Hovered: %s", item->LegendHovered ? "true" : "false"); + ImGui::TreePop(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Axes")) { + // Get the axes parameters of this plot and use it to plot + GetAxesParameters(plot, active_faces, corners_pix, corners, plane_2d, axis_corners); + + for (int a = 0; a < 3; ++a) { + if (plane_2d != -1 && plane_2d == a) + continue; + if (ImGui::TreeNode(axis_labels[a])) { + ShowAxisMetrics(plot.Axes[a]); + ImGui::TreePop(); + } + } + + if (plane_2d != -1) + ImGui::BulletText("Plane2D: %d %s", plane_2d, plane_labels[plane_2d]); + else { + int active_corner_index = Active3DFacesToAxisLookupIndex(active_faces); + ImGui::BulletText("3D Active Faces: [%s,%s,%s]=%d", active_faces[0] ? "X-max" : "X-min", active_faces[1] ? "Y-max" : "Y-min", + active_faces[2] ? "Z-max" : "Z-min", active_corner_index); + ImGui::BulletText("3D Active Corner Lookup: [[%d,%d],[%d, %d],[%d, %d]]", axis_corners_lookup_3d[active_corner_index][0][0], + axis_corners_lookup_3d[active_corner_index][0][1], axis_corners_lookup_3d[active_corner_index][1][0], + axis_corners_lookup_3d[active_corner_index][1][1], axis_corners_lookup_3d[active_corner_index][2][0], + axis_corners_lookup_3d[active_corner_index][2][1]); + ImGui::BulletText("3D Active Edges Lookup: [%d,%d,%d]", axis_edges_lookup_3d[active_corner_index][0], + axis_edges_lookup_3d[active_corner_index][1], axis_edges_lookup_3d[active_corner_index][2]); + } + + for (int a = 0; a < 3; a++) + ImGui::BulletText("%s Label Corners: [%d,%d]", axis_labels[a], axis_corners[a][0], axis_corners[a][1]); + for (int c = 0; c < 8; c++) + ImGui::BulletText("Corner %d: [%.2f,%.2f,%.2f] [%.2f,%.2f]", c, corners[c].x, corners[c].y, corners[c].z, corners_pix[c].x, + corners_pix[c].y); + + ImGui::TreePop(); + } + + ImGui::BulletText("Title: %s", plot.HasTitle() ? plot.GetTitle() : "none"); + ImGui::BulletText("Flags: 0x%08X", plot.Flags); + ImGui::BulletText("Initialized: %s", plot.Initialized ? "true" : "false"); + ImGui::BulletText("Hovered: %s", plot.Hovered ? "true" : "false"); + ImGui::BulletText("Held: %s", plot.Held ? "true" : "false"); + ImGui::BulletText("HeldEdgeIdx: %d", plot.HeldEdgeIdx); + ImGui::BulletText("HeldPlaneIdx: %d", plot.HeldPlaneIdx); + ImGui::BulletText("LegendLocation: %s", GetShortLegendLocationName(plot.Items.Legend.Location)); + ImGui::BulletText("LegendHovered: %s", plot.Items.Legend.Hovered ? "true" : "false"); + ImGui::BulletText("LegendHeld: %s", plot.Items.Legend.Held ? "true" : "false"); + ImGui::BulletText("RotationCond: 0x%08X", plot.RotationCond); + ImGui::BulletText("InitialRotation: [%.2f,%.2f,%.2f,%.2f]", plot.InitialRotation.x, plot.InitialRotation.y, plot.InitialRotation.z, + plot.InitialRotation.w); + ImGui::BulletText("Rotation: [%.2f,%.2f,%.2f,%.2f]", plot.Rotation.x, plot.Rotation.y, plot.Rotation.z, plot.Rotation.w); + ImGui::BulletText("Animation: Time=%.4f RotationEnd=[%.2f,%.2f,%.2f,%.2f]", plot.AnimationTime, plot.RotationAnimationEnd.x, + plot.RotationAnimationEnd.y, plot.Rotation.z, plot.RotationAnimationEnd.w); + ImGui::BulletText("ViewScale: %.2f", plot.GetViewScale()); + + ImGui::TreePop(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Colormaps")) { + ImGui::BulletText("Colormaps: %d", gp.ColormapData.Count); + ImGui::BulletText("Memory: %d bytes", gp.ColormapData.Tables.Size * (int)(sizeof(gp.ColormapData.Tables.Data[0]))); + if (ImGui::TreeNode("Data")) { + for (int m = 0; m < gp.ColormapData.Count; ++m) { + if (ImGui::TreeNode(gp.ColormapData.GetName(m))) { + int count = gp.ColormapData.GetKeyCount(m); + int size = gp.ColormapData.GetTableSize(m); + bool qual = gp.ColormapData.IsQual(m); + ImGui::BulletText("Qualitative: %s", qual ? "true" : "false"); + ImGui::BulletText("Key Count: %d", count); + ImGui::BulletText("Table Size: %d", size); + ImGui::Indent(); + + static float t = 0.5; + ImVec4 samp; + float wid = 32 * 10 - ImGui::GetFrameHeight() - ImGui::GetStyle().ItemSpacing.x; + ImGui::SetNextItemWidth(wid); + ColormapSlider("##Sample", &t, &samp, "%.3f", m); + ImGui::SameLine(); + ImGui::ColorButton("Sampler", samp); + ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + for (int c = 0; c < size; ++c) { + ImVec4 col = ImGui::ColorConvertU32ToFloat4(gp.ColormapData.GetTableColor(m, c)); + ImGui::PushID(m * 1000 + c); + ImGui::ColorButton("", col, 0, ImVec2(10, 10)); + ImGui::PopID(); + if ((c + 1) % 32 != 0 && c != size - 1) + ImGui::SameLine(); + } + ImGui::PopStyleVar(); + ImGui::PopStyleColor(); + ImGui::Unindent(); + ImGui::TreePop(); + } + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Obsolete API +//----------------------------------------------------------------------------- + +#ifndef IMPLOT3D_DISABLE_OBSOLETE_FUNCTIONS + +namespace ImPlot3D { + +// OBSOLETED in v0.3 +ImVec2 GetPlotPos() { return GetPlotRectPos(); } +ImVec2 GetPlotSize() { return GetPlotRectSize(); } + +} // namespace ImPlot3D + +#endif // #ifndef IMPLOT3D_DISABLE_OBSOLETE_FUNCTIONS + +#endif // #ifndef IMGUI_DISABLE diff --git a/tools/upstream/implot3d.h b/tools/upstream/implot3d.h new file mode 100644 index 0000000..3c9450d --- /dev/null +++ b/tools/upstream/implot3d.h @@ -0,0 +1,1135 @@ +// SPDX-License-Identifier: MIT +// SPDX-FileCopyrightText: 2024-2026 Breno Cunha Queiroz + +// ImPlot3D v0.5 WIP + +// Acknowledgments: +// ImPlot3D is heavily inspired by ImPlot +// (https://github.com/epezent/implot) by Evan Pezent, +// and follows a similar code style and structure to +// maintain consistency with ImPlot's API. + +// Table of Contents: +// [SECTION] Macros and Defines +// [SECTION] Forward declarations and basic types +// [SECTION] Flags & Enumerations +// [SECTION] Specs API +// [SECTION] Callbacks +// [SECTION] Context +// [SECTION] Begin/End Plot +// [SECTION] Setup +// [SECTION] Plot Items +// [SECTION] Plot Utils +// [SECTION] Miscellaneous +// [SECTION] Styles API (legacy) +// [SECTION] Demo +// [SECTION] Debugging +// [SECTION] ImPlot3DPoint +// [SECTION] ImPlot3DRay +// [SECTION] ImPlot3DPlane +// [SECTION] ImPlot3DBox +// [SECTION] ImPlot3DQuat +// [SECTION] ImPlot3DStyle +// [SECTION] Meshes +// [SECTION] Obsolete API + +#pragma once +#include "imgui.h" +#ifndef IMGUI_DISABLE + +//----------------------------------------------------------------------------- +// [SECTION] Macros and Defines +//----------------------------------------------------------------------------- + +#ifndef IMPLOT3D_API +#define IMPLOT3D_API +#endif + +#define IMPLOT3D_VERSION "0.5 WIP" // ImPlot3D version +#define IMPLOT3D_VERSION_NUM 500 // Integer encoded version +#define IMPLOT3D_AUTO -1 // Deduce variable automatically +#define IMPLOT3D_AUTO_COL ImVec4(0, 0, 0, -1) // Deduce color automatically +#define IMPLOT3D_TMP template IMPLOT3D_API + +//----------------------------------------------------------------------------- +// [SECTION] Forward declarations and basic types +//----------------------------------------------------------------------------- + +// Forward declarations +struct ImPlot3DContext; +struct ImPlot3DStyle; +struct ImPlot3DPoint; +struct ImPlot3DRay; +struct ImPlot3DPlane; +struct ImPlot3DBox; +struct ImPlot3DRange; +struct ImPlot3DQuat; + +// Enums +typedef int ImPlot3DCond; // -> ImPlot3DCond_ // Enum: Condition for flags +typedef int ImPlot3DCol; // -> ImPlot3DCol_ // Enum: Styling colors +typedef int ImPlot3DStyleVar; // -> ImPlot3DStyleVar_ // Enum: Style variables +typedef int ImPlot3DMarker; // -> ImPlot3DMarker_ // Enum: Marker styles +typedef int ImPlot3DLocation; // -> ImPlot3DLocation_ // Enum: Locations +typedef int ImAxis3D; // -> ImAxis3D_ // Enum: Axis indices +typedef int ImPlane3D; // -> ImPlane3D_ // Enum: Plane indices +typedef int ImPlot3DScale; // -> ImPlot3DScale_ // Enum: Axis scale (linear, log, etc.) +typedef int ImPlot3DColormap; // -> ImPlot3DColormap_ // Enum: Colormaps +typedef int ImPlot3DProp; // -> ImPlot3DProp_ // Enum: Plot properties + +// Flags +typedef int ImPlot3DFlags; // -> ImPlot3DFlags_ // Flags: for BeginPlot() +typedef int ImPlot3DItemFlags; // -> ImPlot3DItemFlags_ // Flags: Item flags +typedef int ImPlot3DScatterFlags; // -> ImPlot3DScatterFlags_ // Flags: Scatter plot flags +typedef int ImPlot3DLineFlags; // -> ImPlot3DLineFlags_ // Flags: Line plot flags +typedef int ImPlot3DTriangleFlags; // -> ImPlot3DTriangleFlags_ // Flags: Triangle plot flags +typedef int ImPlot3DQuadFlags; // -> ImPlot3DQuadFlags_ // Flags: Quad plot flags +typedef int ImPlot3DSurfaceFlags; // -> ImPlot3DSurfaceFlags_ // Flags: Surface plot flags +typedef int ImPlot3DMeshFlags; // -> ImPlot3DMeshFlags_ // Flags: Mesh plot flags +typedef int ImPlot3DImageFlags; // -> ImPlot3DImageFlags_ // Flags: Image plot flags +typedef int ImPlot3DDummyFlags; // -> ImPlot3DDummyFlags_ // Flags: Dummy flags +typedef int ImPlot3DLegendFlags; // -> ImPlot3DLegendFlags_ // Flags: Legend flags +typedef int ImPlot3DAxisFlags; // -> ImPlot3DAxisFlags_ // Flags: Axis flags + +// Fallback for ImGui versions before v1.92: define ImTextureRef as ImTextureID +// You can `#define IMPLOT3D_NO_IMTEXTUREREF` to avoid this fallback +#if !defined(IMGUI_HAS_TEXTURES) && !defined(IMPLOT3D_NO_IMTEXTUREREF) +typedef ImTextureID ImTextureRef; +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Flags & Enumerations +//----------------------------------------------------------------------------- + +// Plotting properties. These provide syntactic sugar for creating ImPlot3DSpec from (ImPlot3DProp,value) pairs +enum ImPlot3DProp_ { + ImPlot3DProp_LineColor, // Line color; IMPLOT3D_AUTO_COL will use next Colormap color + ImPlot3DProp_LineColors, // Array of line colors (ImU32*); if nullptr, use LineColor for all + ImPlot3DProp_LineWeight, // Line weight in pixels + ImPlot3DProp_FillColor, // Fill color (applies to shaded regions); IMPLOT3D_AUTO_COL will use next Colormap color + ImPlot3DProp_FillColors, // Array of fill colors (ImU32*); if nullptr, use FillColor for all + ImPlot3DProp_FillAlpha, // Alpha multiplier (applies to FillColor, FillColors, MarkerFillColor, and MarkerFillColors) + ImPlot3DProp_Marker, // Marker type + ImPlot3DProp_MarkerSize, // Size of markers (radius) *in pixels* + ImPlot3DProp_MarkerSizes, // Array of marker sizes (float*); if nullptr, use MarkerSize for all + ImPlot3DProp_MarkerLineColor, // Marker outline color; IMPLOT3D_AUTO_COL will use next LineColor + ImPlot3DProp_MarkerLineColors, // Array of marker outline colors (ImU32*); if nullptr, use MarkerLineColor for all + ImPlot3DProp_MarkerFillColor, // Marker fill color; IMPLOT3D_AUTO_COL will use LineColor + ImPlot3DProp_MarkerFillColors, // Array of marker fill colors (ImU32*); if nullptr, use MarkerFillColor for all + ImPlot3DProp_Offset, // Data index offset + ImPlot3DProp_Stride, // Data stride in bytes; IMPLOT3D_AUTO will result in sizeof(T) where T is the type passed to PlotX + ImPlot3DProp_Flags // Optional item flags; can be composed from common ImPlot3DItemFlags and/or specialized ImPlot3DXFlags +}; + +// Flags for ImPlot3D::BeginPlot() +enum ImPlot3DFlags_ { + ImPlot3DFlags_None = 0, // Default + ImPlot3DFlags_NoTitle = 1 << 0, // Hide plot title + ImPlot3DFlags_NoLegend = 1 << 1, // Hide plot legend + ImPlot3DFlags_NoMouseText = 1 << 2, // Hide mouse position in plot coordinates + ImPlot3DFlags_NoClip = 1 << 3, // Disable 3D box clipping + ImPlot3DFlags_NoMenus = 1 << 4, // The user will not be able to open context menus + ImPlot3DFlags_Equal = 1 << 5, // X, Y, and Z axes will be constrained to have the same units/pixel + ImPlot3DFlags_NoRotate = 1 << 6, // Lock rotation interaction + ImPlot3DFlags_NoPan = 1 << 7, // Lock panning/translation interaction + ImPlot3DFlags_NoZoom = 1 << 8, // Lock zoom interaction + ImPlot3DFlags_NoInputs = 1 << 9, // Disable all user inputs + ImPlot3DFlags_CanvasOnly = ImPlot3DFlags_NoTitle | ImPlot3DFlags_NoLegend | ImPlot3DFlags_NoMouseText, +}; + +// Represents a condition for SetupAxisLimits etc. (same as ImGuiCond, but we only support a subset of those enums) +enum ImPlot3DCond_ { + ImPlot3DCond_None = ImGuiCond_None, // No condition (always set the variable), same as _Always + ImPlot3DCond_Always = ImGuiCond_Always, // No condition (always set the variable) + ImPlot3DCond_Once = ImGuiCond_Once, // Set the variable once per runtime session (only the first call will succeed) +}; + +enum ImPlot3DCol_ { + // Plot colors + ImPlot3DCol_TitleText, // Title color + ImPlot3DCol_InlayText, // Color for texts appearing inside of plots + ImPlot3DCol_FrameBg, // Frame background color + ImPlot3DCol_PlotBg, // Plot area background color + ImPlot3DCol_PlotBorder, // Plot area border color + // Legend colors + ImPlot3DCol_LegendBg, // Legend background color + ImPlot3DCol_LegendBorder, // Legend border color + ImPlot3DCol_LegendText, // Legend text color + // Axis colors + ImPlot3DCol_AxisText, // Axis label and tick lables color + ImPlot3DCol_AxisGrid, // Axis grid color + ImPlot3DCol_AxisTick, // Axis tick color (defaults to AxisGrid) + ImPlot3DCol_AxisBg, // Background color of axis hover region (defaults to transparent) + ImPlot3DCol_AxisBgHovered, // Axis hover color (defaults to ImGuiCol_ButtonHovered) + ImPlot3DCol_AxisBgActive, // Axis active color (defaults to ImGuiCol_ButtonActive) + ImPlot3DCol_COUNT, +}; + +// Plot styling variables +enum ImPlot3DStyleVar_ { + // Item style + ImPlot3DStyleVar_LineWeight, // float, plot item line weight in pixels + ImPlot3DStyleVar_Marker, // int, marker specification + ImPlot3DStyleVar_MarkerSize, // float, marker size in pixels (roughly the marker's "radius") + ImPlot3DStyleVar_FillAlpha, // float, alpha modifier applied to all plot item fills + // Plot style + ImPlot3DStyleVar_PlotDefaultSize, // ImVec2, default size used when ImVec2(0,0) is passed to BeginPlot + ImPlot3DStyleVar_PlotMinSize, // ImVec2, minimum size plot frame can be when shrunk + ImPlot3DStyleVar_PlotPadding, // ImVec2, padding between widget frame and plot area, labels, or outside legends (i.e. main padding) + ImPlot3DStyleVar_LabelPadding, // ImVec2, padding between axes labels, tick labels, and plot edge + ImPlot3DStyleVar_ViewScaleFactor, // float, scale factor for 3D view, you can use it to make the whole plot larger or smaller + // Legend style + ImPlot3DStyleVar_LegendPadding, // ImVec2, legend padding from plot edges + ImPlot3DStyleVar_LegendInnerPadding, // ImVec2, legend inner padding from legend edges + ImPlot3DStyleVar_LegendSpacing, // ImVec2, spacing between legend entries + ImPlot3DStyleVar_COUNT +}; + +enum ImPlot3DMarker_ { + ImPlot3DMarker_None = -2, // No marker + ImPlot3DMarker_Auto = -1, // Automatic marker selection + ImPlot3DMarker_Circle, // Circle marker (default) + ImPlot3DMarker_Square, // Square maker + ImPlot3DMarker_Diamond, // Diamond marker + ImPlot3DMarker_Up, // Upward-pointing triangle marker + ImPlot3DMarker_Down, // Downward-pointing triangle marker + ImPlot3DMarker_Left, // Leftward-pointing triangle marker + ImPlot3DMarker_Right, // Rightward-pointing triangle marker + ImPlot3DMarker_Cross, // Cross marker (not fillable) + ImPlot3DMarker_Plus, // Plus marker (not fillable) + ImPlot3DMarker_Asterisk, // Asterisk marker (not fillable) + ImPlot3DMarker_COUNT +}; + +// Flags for items +enum ImPlot3DItemFlags_ { + ImPlot3DItemFlags_None = 0, // Default + ImPlot3DItemFlags_NoLegend = 1 << 0, // The item won't have a legend entry displayed + ImPlot3DItemFlags_NoFit = 1 << 1, // The item won't be considered for plot fits +}; + +// Flags for PlotScatter +enum ImPlot3DScatterFlags_ { + ImPlot3DScatterFlags_None = 0, // Default + ImPlot3DScatterFlags_NoLegend = ImPlot3DItemFlags_NoLegend, + ImPlot3DScatterFlags_NoFit = ImPlot3DItemFlags_NoFit, +}; + +// Flags for PlotLine +enum ImPlot3DLineFlags_ { + ImPlot3DLineFlags_None = 0, // Default + ImPlot3DLineFlags_NoLegend = ImPlot3DItemFlags_NoLegend, + ImPlot3DLineFlags_NoFit = ImPlot3DItemFlags_NoFit, + ImPlot3DLineFlags_Segments = 1 << 10, // A line segment will be rendered from every two consecutive points + ImPlot3DLineFlags_Loop = 1 << 11, // The last and first point will be connected to form a closed loop + ImPlot3DLineFlags_SkipNaN = 1 << 12, // NaNs values will be skipped instead of rendered as missing data +}; + +// Flags for PlotTriangle +enum ImPlot3DTriangleFlags_ { + ImPlot3DTriangleFlags_None = 0, // Default + ImPlot3DTriangleFlags_NoLegend = ImPlot3DItemFlags_NoLegend, + ImPlot3DTriangleFlags_NoFit = ImPlot3DItemFlags_NoFit, + ImPlot3DTriangleFlags_NoLines = 1 << 10, // No lines will be rendered + ImPlot3DTriangleFlags_NoFill = 1 << 11, // No fill will be rendered + ImPlot3DTriangleFlags_NoMarkers = 1 << 12, // No markers will be rendered +}; + +// Flags for PlotQuad +enum ImPlot3DQuadFlags_ { + ImPlot3DQuadFlags_None = 0, // Default + ImPlot3DQuadFlags_NoLegend = ImPlot3DItemFlags_NoLegend, + ImPlot3DQuadFlags_NoFit = ImPlot3DItemFlags_NoFit, + ImPlot3DQuadFlags_NoLines = 1 << 10, // No lines will be rendered + ImPlot3DQuadFlags_NoFill = 1 << 11, // No fill will be rendered + ImPlot3DQuadFlags_NoMarkers = 1 << 12, // No markers will be rendered +}; + +// Flags for PlotSurface +enum ImPlot3DSurfaceFlags_ { + ImPlot3DSurfaceFlags_None = 0, // Default + ImPlot3DSurfaceFlags_NoLegend = ImPlot3DItemFlags_NoLegend, + ImPlot3DSurfaceFlags_NoFit = ImPlot3DItemFlags_NoFit, + ImPlot3DSurfaceFlags_NoLines = 1 << 10, // No lines will be rendered + ImPlot3DSurfaceFlags_NoFill = 1 << 11, // No fill will be rendered + ImPlot3DSurfaceFlags_NoMarkers = 1 << 12, // No markers will be rendered +}; + +// Flags for PlotMesh +enum ImPlot3DMeshFlags_ { + ImPlot3DMeshFlags_None = 0, // Default + ImPlot3DMeshFlags_NoLegend = ImPlot3DItemFlags_NoLegend, + ImPlot3DMeshFlags_NoFit = ImPlot3DItemFlags_NoFit, + ImPlot3DMeshFlags_NoLines = 1 << 10, // No lines will be rendered + ImPlot3DMeshFlags_NoFill = 1 << 11, // No fill will be rendered + ImPlot3DMeshFlags_NoMarkers = 1 << 12, // No markers will be rendered +}; + +// Flags for PlotImage +enum ImPlot3DImageFlags_ { + ImPlot3DImageFlags_None = 0, // Default + ImPlot3DImageFlags_NoLegend = ImPlot3DItemFlags_NoLegend, + ImPlot3DImageFlags_NoFit = ImPlot3DItemFlags_NoFit, +}; + +// Flags for PlotDummy +enum ImPlot3DDummyFlags_ { + ImPlot3DDummyFlags_None = 0 // Default +}; + +// Flags for legends +enum ImPlot3DLegendFlags_ { + ImPlot3DLegendFlags_None = 0, // Default + ImPlot3DLegendFlags_NoButtons = 1 << 0, // Legend icons will not function as hide/show buttons + ImPlot3DLegendFlags_NoHighlightItem = 1 << 1, // Plot items will not be highlighted when their legend entry is hovered + ImPlot3DLegendFlags_Horizontal = 1 << 2, // Legend entries will be displayed horizontally +}; + +// Used to position legend on a plot +enum ImPlot3DLocation_ { + ImPlot3DLocation_Center = 0, // Center-center + ImPlot3DLocation_North = 1 << 0, // Top-center + ImPlot3DLocation_South = 1 << 1, // Bottom-center + ImPlot3DLocation_West = 1 << 2, // Center-left + ImPlot3DLocation_East = 1 << 3, // Center-right + ImPlot3DLocation_NorthWest = ImPlot3DLocation_North | ImPlot3DLocation_West, // Top-left + ImPlot3DLocation_NorthEast = ImPlot3DLocation_North | ImPlot3DLocation_East, // Top-right + ImPlot3DLocation_SouthWest = ImPlot3DLocation_South | ImPlot3DLocation_West, // Bottom-left + ImPlot3DLocation_SouthEast = ImPlot3DLocation_South | ImPlot3DLocation_East // Bottom-right +}; + +// Flags for axis +enum ImPlot3DAxisFlags_ { + ImPlot3DAxisFlags_None = 0, // Default + ImPlot3DAxisFlags_NoLabel = 1 << 0, // No axis label will be displayed + ImPlot3DAxisFlags_NoGridLines = 1 << 1, // No grid lines will be displayed + ImPlot3DAxisFlags_NoTickMarks = 1 << 2, // No tick marks will be displayed + ImPlot3DAxisFlags_NoTickLabels = 1 << 3, // No tick labels will be displayed + ImPlot3DAxisFlags_LockMin = 1 << 4, // The axis minimum value will be locked when panning/zooming + ImPlot3DAxisFlags_LockMax = 1 << 5, // The axis maximum value will be locked when panning/zooming + ImPlot3DAxisFlags_AutoFit = 1 << 6, // Axis will be auto-fitting to data extents + ImPlot3DAxisFlags_Invert = 1 << 7, // The axis will be inverted + ImPlot3DAxisFlags_PanStretch = 1 << 8, // Panning in a locked or constrained state will cause the axis to stretch if possible + ImPlot3DAxisFlags_Lock = ImPlot3DAxisFlags_LockMin | ImPlot3DAxisFlags_LockMax, + ImPlot3DAxisFlags_NoDecorations = ImPlot3DAxisFlags_NoLabel | ImPlot3DAxisFlags_NoGridLines | ImPlot3DAxisFlags_NoTickLabels, +}; + +// Axis indices +enum ImAxis3D_ { + ImAxis3D_X = 0, // X-axis + ImAxis3D_Y, // Y-axis + ImAxis3D_Z, // Z-axis + ImAxis3D_COUNT, +}; + +// Plane indices +enum ImPlane3D_ { + ImPlane3D_YZ = 0, // YZ plane (perpendicular to X-axis) + ImPlane3D_XZ, // XZ plane (perpendicular to Y-axis) + ImPlane3D_XY, // XY plane (perpendicular to Z-axis) + ImPlane3D_COUNT, +}; + +// Axis scale +enum ImPlot3DScale_ { + ImPlot3DScale_Linear = 0, // Default linear scale + ImPlot3DScale_Log10, // Base 10 log scale + ImPlot3DScale_SymLog, // Symmetric base 10 log scale +}; + +// Colormaps +enum ImPlot3DColormap_ { + ImPlot3DColormap_Deep = 0, // Same as seaborn "deep" + ImPlot3DColormap_Dark = 1, // Same as matplotlib "Set1" + ImPlot3DColormap_Pastel = 2, // Same as matplotlib "Pastel1" + ImPlot3DColormap_Paired = 3, // Same as matplotlib "Paired" + ImPlot3DColormap_Viridis = 4, // Same as matplotlib "viridis" + ImPlot3DColormap_Plasma = 5, // Same as matplotlib "plasma" + ImPlot3DColormap_Hot = 6, // Same as matplotlib/MATLAB "hot" + ImPlot3DColormap_Cool = 7, // Same as matplotlib/MATLAB "cool" + ImPlot3DColormap_Pink = 8, // Same as matplotlib/MATLAB "pink" + ImPlot3DColormap_Jet = 9, // Same as matplotlib/MATLAB "jet" + ImPlot3DColormap_Twilight = 10, // Same as matplotlib "twilight" + ImPlot3DColormap_RdBu = 11, // Same as matplotlib "RdBu" + ImPlot3DColormap_BrBG = 12, // Same as matplotlib "BrGB" + ImPlot3DColormap_PiYG = 13, // Same as matplotlib "PiYG" + ImPlot3DColormap_Spectral = 14, // Same as matplotlib "Spectral" + ImPlot3DColormap_Greys = 15, // White/black +}; + +//----------------------------------------------------------------------------- +// [SECTION] Specs API +//----------------------------------------------------------------------------- + +// Plot item styling specification. Provide these to PlotX functions to override styling, specify +// offsetting or stride, or set optional flags. This struct can be used in the following ways: +// +// 1. By declaring and defining a struct instance: +// +// ImPlot3DSpec spec; +// spec.LineColor = ImVec4(1,0,0,1); +// spec.LineWeight = 2.0f; +// spec.Marker = ImPlot3DMarker_Circle; +// spec.Flags = ImPlot3DItemFlags_NoLegend | ImPlot3DLineFlags_Segments; +// ImPlot3D::PlotLine("MyLine", xs, ys, zs, 100, spec); +// +// 2. Inline using ImPlot3DProp,value pairs (order does NOT matter): +// +// ImPlot3D::PlotLine("MyLine", xs, ys, zs, 100, { +// ImPlot3DProp_LineColor, ImVec4(1,0,0,1), +// ImPlot3DProp_LineWeight, 2.0f, +// ImPlot3DProp_Marker, ImPlot3DMarker_Circle, +// ImPlot3DProp_Flags, ImPlot3DItemFlags_NoLegend | ImPlot3DLineFlags_Segments +// }); +struct ImPlot3DSpec { + ImVec4 LineColor = IMPLOT3D_AUTO_COL; // Line color; IMPLOT3D_AUTO_COL will use next Colormap color + ImU32* LineColors = nullptr; // Per-index line colors; if nullptr, use LineColor for all + float LineWeight = 1.0f; // Line weight in pixels + ImVec4 FillColor = IMPLOT3D_AUTO_COL; // Fill color (applies to shaded regions); IMPLOT3D_AUTO_COL will use next Colormap color + ImU32* FillColors = nullptr; // Per-index fill colors; if nullptr, use FillColor for all + float FillAlpha = IMPLOT3D_AUTO; // Alpha multiplier (applies to FillColor, FillColors, MarkerFillColor, and MarkerFillColors) + ImPlot3DMarker Marker = ImPlot3DMarker_Auto; // Marker type + float MarkerSize = IMPLOT3D_AUTO; // Size of markers (radius) *in pixels* + float* MarkerSizes = nullptr; // Per-index marker sizes; if nullptr, use MarkerSize for all + ImVec4 MarkerLineColor = IMPLOT3D_AUTO_COL; // Marker outline color; IMPLOT3D_AUTO_COL will use LineColor + ImU32* MarkerLineColors = nullptr; // Per-index marker outline colors; if nullptr, use MarkerLineColor for all + ImVec4 MarkerFillColor = IMPLOT3D_AUTO_COL; // Marker fill color; IMPLOT3D_AUTO_COL will use LineColor + ImU32* MarkerFillColors = nullptr; // Per-index marker fill colors; if nullptr, use MarkerFillColor for all + int Offset = 0; // Data index offset + int Stride = IMPLOT3D_AUTO; // Data stride in bytes; IMPLOT3D_AUTO will result in sizeof(T) where T is the type passed to PlotX + ImPlot3DItemFlags Flags = + ImPlot3DItemFlags_None; // Optional item flags; can be composed from common ImPlot3DItemFlags and/or specialized ImPlot3DXFlags + + ImPlot3DSpec() {} + + // Construct a plot item specification from (ImPlot3DProp,value) pairs in any order + // E.g. ImPlot3DSpec(ImPlot3DProp_LineColor, my_color, ImPlot3DProp_Marker, ImPlot3DMarker_Circle) + template ImPlot3DSpec(Args... args) { + static_assert((sizeof...(Args)) % 2 == 0, "Odd number of arguments! You must provide (ImPlot3DProp,value) pairs!"); + SetProp(args...); + } + + // Set properties from (ImPlot3DProp,value) pairs in any order + // E.g. SetProp(ImPlot3DProp_LineColor, my_color, ImPlot3DProp_Marker, ImPlot3DMarker_Circle) + template void SetProp(ImPlot3DProp prop, Arg arg, Args... args) { + static_assert((sizeof...(Args)) % 2 == 0, "Odd number of arguments! You must provide (ImPlot3DProp,value) pairs!"); + SetProp(prop, arg); + SetProp(args...); + } + + // Set a property from a scalar value. + template void SetProp(ImPlot3DProp prop, T v) { + switch (prop) { + case ImPlot3DProp_LineColor: LineColor = ImGui::ColorConvertU32ToFloat4((ImU32)v); return; + case ImPlot3DProp_LineWeight: LineWeight = (float)v; return; + case ImPlot3DProp_FillColor: FillColor = ImGui::ColorConvertU32ToFloat4((ImU32)v); return; + case ImPlot3DProp_FillAlpha: FillAlpha = (float)v; return; + case ImPlot3DProp_Marker: Marker = (ImPlot3DMarker)v; return; + case ImPlot3DProp_MarkerSize: MarkerSize = (float)v; return; + case ImPlot3DProp_MarkerLineColor: MarkerLineColor = ImGui::ColorConvertU32ToFloat4((ImU32)v); return; + case ImPlot3DProp_MarkerFillColor: MarkerFillColor = ImGui::ColorConvertU32ToFloat4((ImU32)v); return; + case ImPlot3DProp_Offset: Offset = (int)v; return; + case ImPlot3DProp_Stride: Stride = (int)v; return; + case ImPlot3DProp_Flags: Flags = (ImPlot3DItemFlags)v; return; + default: break; + } + IM_ASSERT(0 && "User provided an ImPlot3DProp which cannot be set from scalar value!"); + } + + // Set a property from an ImU32* array (per-index colors). + void SetProp(ImPlot3DProp prop, ImU32* v) { + switch (prop) { + case ImPlot3DProp_LineColors: LineColors = v; return; + case ImPlot3DProp_FillColors: FillColors = v; return; + case ImPlot3DProp_MarkerLineColors: MarkerLineColors = v; return; + case ImPlot3DProp_MarkerFillColors: MarkerFillColors = v; return; + default: break; + } + IM_ASSERT(0 && "User provided an ImPlot3DProp which cannot be set from ImU32* value!"); + } + + // Set a property from a float* array (per-index sizes). + void SetProp(ImPlot3DProp prop, float* v) { + switch (prop) { + case ImPlot3DProp_MarkerSizes: MarkerSizes = v; return; + default: break; + } + IM_ASSERT(0 && "User provided an ImPlot3DProp which cannot be set from float* value!"); + } + + // Set a property from an ImVec4 value. + void SetProp(ImPlot3DProp prop, const ImVec4& v) { + switch (prop) { + case ImPlot3DProp_LineColor: LineColor = v; return; + case ImPlot3DProp_FillColor: FillColor = v; return; + case ImPlot3DProp_MarkerLineColor: MarkerLineColor = v; return; + case ImPlot3DProp_MarkerFillColor: MarkerFillColor = v; return; + default: break; + } + IM_ASSERT(0 && "User provided an ImPlot3DProp which cannot be set from ImVec4 value!"); + } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Callbacks +//----------------------------------------------------------------------------- + +// Callback signature for axis tick label formatter. +// Given a numeric #value, format it into #buff with maximum #size characters. +// Optionally use #user_data for context. Return the number of characters written (excluding null terminator) +typedef int (*ImPlot3DFormatter)(double value, char* buff, int size, void* user_data); + +// Callback signature for axis transform +typedef double (*ImPlot3DTransform)(double value, void* user_data); + +namespace ImPlot3D { + +//----------------------------------------------------------------------------- +// [SECTION] Context +//----------------------------------------------------------------------------- + +// Creates a new ImPlot3D context. Call this after ImGui::CreateContext +IMPLOT3D_API ImPlot3DContext* CreateContext(); +// Destroys an ImPlot3D context. Call this before ImGui::DestroyContext. nullptr = destroy current context +IMPLOT3D_API void DestroyContext(ImPlot3DContext* ctx = nullptr); +// Returns the current ImPlot3D context. nullptr if no context has been set +IMPLOT3D_API ImPlot3DContext* GetCurrentContext(); +// Sets the current ImPlot3D context +IMPLOT3D_API void SetCurrentContext(ImPlot3DContext* ctx); + +//----------------------------------------------------------------------------- +// [SECTION] Begin/End Plot +//----------------------------------------------------------------------------- + +// Starts a 3D plotting context. If this function returns true, EndPlot() MUST +// be called! You are encouraged to use the following convention: +// +// if (ImPlot3D::BeginPlot(...)) { +// ImPlot3D::PlotLine(...); +// ... +// ImPlot3D::EndPlot(); +// } +// +// Important notes: +// - #title_id must be unique to the current ImGui ID scope. If you need to avoid ID +// collisions or don't want to display a title in the plot, use double hashes +// (e.g. "MyPlot##HiddenIdText" or "##NoTitle"). +// - #size is the **frame** size of the plot widget, not the plot area. +IMPLOT3D_API bool BeginPlot(const char* title_id, const ImVec2& size = ImVec2(-1, 0), ImPlot3DFlags flags = 0); +IMPLOT3D_API void EndPlot(); // Only call if BeginPlot() returns true! + +//----------------------------------------------------------------------------- +// [SECTION] Setup +//----------------------------------------------------------------------------- + +// The following API allows you to setup and customize various aspects of the +// current plot. The functions should be called immediately after BeginPlot() +// and before any other API calls. Typical usage is as follows: + +// if (ImPlot3D::BeginPlot(...)) { 1) Begin a new plot +// ImPlot3D::SetupAxis(ImAxis3D_X, "My X-Axis"); 2) Make Setup calls +// ImPlot3D::SetupAxis(ImAxis3D_Y, "My Y-Axis"); +// ImPlot3D::SetupLegend(ImPlotLocation_North); +// ... +// ImPlot3D::SetupFinish(); 3) [Optional] Explicitly finish setup +// ImPlot3D::PlotLine(...); 4) Plot items +// ... +// ImPlot3D::EndPlot(); 5) End the plot +// } +// +// Important notes: +// +// - Always call Setup code at the top of your BeginPlot conditional statement. +// - Setup is locked once you start plotting or explicitly call SetupFinish. +// Do NOT call Setup code after you begin plotting or after you make +// any non-Setup API calls (e.g. utils like PlotToPixels also lock Setup). +// - Calling SetupFinish is OPTIONAL, but probably good practice. If you do not +// call it yourself, then the first subsequent plotting or utility function will +// call it for you. + +// Enables an axis or sets the label and/or flags for an existing axis. Leave #label = nullptr for no label +IMPLOT3D_API void SetupAxis(ImAxis3D axis, const char* label = nullptr, ImPlot3DAxisFlags flags = 0); + +// Sets an axis range limits. If ImPlot3DCond_Always is used, the axis limits will be locked. +// Note: To invert an axis, use ImPlot3DAxisFlags_Invert with SetupAxis instead of swapping min/max +IMPLOT3D_API void SetupAxisLimits(ImAxis3D axis, double v_min, double v_max, ImPlot3DCond cond = ImPlot3DCond_Once); + +// Sets the format of numeric axis labels via formatter callback. Given value, write a label into buff. Optionally pass user data +IMPLOT3D_API void SetupAxisFormat(ImAxis3D axis, ImPlot3DFormatter formatter, void* data = nullptr); + +// Sets an axis' ticks and optionally the labels. To keep the default ticks, set #keep_default=true +IMPLOT3D_API void SetupAxisTicks(ImAxis3D axis, const double* values, int n_ticks, const char* const labels[] = nullptr, bool keep_default = false); + +// Sets an axis' ticks and optionally the labels for the next plot. To keep the default ticks, set #keep_default=true +IMPLOT3D_API void SetupAxisTicks(ImAxis3D axis, double v_min, double v_max, int n_ticks, const char* const labels[] = nullptr, + bool keep_default = false); + +// Sets an axis' scale using built-in options +IMPLOT3D_API void SetupAxisScale(ImAxis3D axis, ImPlot3DScale scale); + +// Sets an axis' scale using user supplied forward and inverse transforms +IMPLOT3D_API void SetupAxisScale(ImAxis3D axis, ImPlot3DTransform forward, ImPlot3DTransform inverse, void* data = nullptr); + +// Sets an axis' limits constraints. The axis will be constrained to never go below #v_min or above #v_max +IMPLOT3D_API void SetupAxisLimitsConstraints(ImAxis3D axis, double v_min, double v_max); + +// Sets an axis' zoom constraints. The zoom (axis range size: range.max - range.min) will be constrained between #zoom_min and #zoom_max +IMPLOT3D_API void SetupAxisZoomConstraints(ImAxis3D axis, double zoom_min, double zoom_max); + +// Sets the label and/or flags for primary X/Y/Z axes (shorthand for three calls to SetupAxis) +IMPLOT3D_API void SetupAxes(const char* x_label, const char* y_label, const char* z_label, ImPlot3DAxisFlags x_flags = 0, + ImPlot3DAxisFlags y_flags = 0, ImPlot3DAxisFlags z_flags = 0); + +// Sets the X/Y/Z axes range limits. If ImPlot3DCond_Always is used, the axes limits will be locked (shorthand for three calls to SetupAxisLimits) +IMPLOT3D_API void SetupAxesLimits(double x_min, double x_max, double y_min, double y_max, double z_min, double z_max, + ImPlot3DCond cond = ImPlot3DCond_Once); + +// Sets the plot box rotation given the elevation and azimuth angles in degrees. If ImPlot3DCond_Always is used, the rotation will be locked +IMPLOT3D_API void SetupBoxRotation(double elevation, double azimuth, bool animate = false, ImPlot3DCond cond = ImPlot3DCond_Once); + +// Sets the plot box rotation given a quaternion. If ImPlot3DCond_Always is used, the rotation will be locked +IMPLOT3D_API void SetupBoxRotation(ImPlot3DQuat rotation, bool animate = false, ImPlot3DCond cond = ImPlot3DCond_Once); + +// Sets the plot box initial rotation given the elevation and azimuth angles in degrees. The initial rotation is the rotation the plot goes back to +// when a left mouse button double click happens +IMPLOT3D_API void SetupBoxInitialRotation(double elevation, double azimuth); + +// Sets the plot box initial rotation given a quaternion. The initial rotation is the rotation the plot goes back to when a left mouse button double +// click happens +IMPLOT3D_API void SetupBoxInitialRotation(ImPlot3DQuat rotation); + +// Sets the plot box X/Y/Z scale. A scale of 1.0 is the default. Values greater than 1.0 enlarge the plot, while values between 0.0 and 1.0 shrink it +IMPLOT3D_API void SetupBoxScale(double x, double y, double z); + +// Sets up the plot legend location and flags +IMPLOT3D_API void SetupLegend(ImPlot3DLocation location, ImPlot3DLegendFlags flags = 0); + +//----------------------------------------------------------------------------- +// [SECTION] Plot Items +//----------------------------------------------------------------------------- + +// The plotting API is provided below. Call these functions between +// BeginPlot/EndPlot and after any Setup API calls. +// +// The templated functions are explicitly instantiated in implot3d_items.cpp. +// They are not intended to be used generically with custom types. You will get +// a linker error if you try! All functions support the following scalar types: +// +// float, double, ImS8, ImU8, ImS16, ImU16, ImS32, ImU32, ImS64, ImU64 +// +// If you need to plot custom or non-homogenous data you have a few options: +// +// 1. If your data is a simple struct/class (e.g. Vector3f), you can use striding. +// This is the most performant option if applicable. +// +// struct Vector3f { float X, Y, Z; }; +// ... +// Vector3f data[42]; +// ImPlot3D::PlotLine("line", &data[0].X, &data[0].Y, &data[0].Z, 42, {ImPlot3DProp_Stride, sizeof(Vector2f)}); +// +// 2. If your data is in separate arrays or requires computation, you can copy/transform +// it into temporary float or double arrays before plotting. +// +// NB: All types are converted to double before plotting. You may lose information +// if you try plotting extremely large 64-bit integral types. Proceed with caution! + +// Plots a scatter plot in 3D. Points are rendered as markers at the specified coordinates +IMPLOT3D_TMP void PlotScatter(const char* label_id, const T* xs, const T* ys, const T* zs, int count, const ImPlot3DSpec& spec = ImPlot3DSpec()); + +// Plots a line in 3D. Consecutive points are connected with line segments +IMPLOT3D_TMP void PlotLine(const char* label_id, const T* xs, const T* ys, const T* zs, int count, const ImPlot3DSpec& spec = ImPlot3DSpec()); + +// Plots triangles in 3D. Every 3 consecutive points define a triangle +IMPLOT3D_TMP void PlotTriangle(const char* label_id, const T* xs, const T* ys, const T* zs, int count, const ImPlot3DSpec& spec = ImPlot3DSpec()); + +// Plots quads in 3D. Every 4 consecutive points define a quadrilateral +IMPLOT3D_TMP void PlotQuad(const char* label_id, const T* xs, const T* ys, const T* zs, int count, const ImPlot3DSpec& spec = ImPlot3DSpec()); + +// Plot the surface defined by a grid of vertices. The grid is defined by the x and y arrays, and the z array contains the height of each vertex. A +// total of x_count * y_count vertices are expected for each array. Leave #scale_min and #scale_max both at 0 for automatic color scaling, or set them +// to a predefined range +IMPLOT3D_TMP void PlotSurface(const char* label_id, const T* xs, const T* ys, const T* zs, int x_count, int y_count, double scale_min = 0.0, + double scale_max = 0.0, const ImPlot3DSpec& spec = ImPlot3DSpec()); + +// Plots a 3D mesh given vertex positions as separate coordinate arrays and an index buffer. +// Triangles are defined by the index buffer (every 3 indices form a triangle). +// Spec.Offset and Spec.Stride apply to the vertex coordinate arrays only, not to the index buffer. +// Color array semantics: +// - FillColors / LineColors: idx_count entries, indexed by position in the index buffer. +// Each triangle has 3 consecutive color entries (one per corner). +// Setting all 3 to the same value gives flat per-triangle shading. +// Setting different values enables Gouraud shading (GPU-interpolated). +// To shade by vertex, map: FillColors[i] = vtx_colors[idxs[i]]. +// - MarkerFillColors / MarkerLineColors: vtx_count entries, one per unique vertex. +IMPLOT3D_TMP void PlotMesh(const char* label_id, const T* vtx_xs, const T* vtx_ys, const T* vtx_zs, const unsigned int* idxs, int vtx_count, + int idx_count, const ImPlot3DSpec& spec = ImPlot3DSpec()); + +// Plots a rectangular image in 3D defined by its center and two direction vectors (axes). +// #center is the center of the rectangle in plot coordinates. +// #axis_u and #axis_v define the local axes and half-extents of the rectangle in 3D space. +// The rectangle is formed by moving from the center along ±axis_u and ±axis_v. +// #uv0 and #uv1 define the texture mapping. +// #tint_col can be used to tint the image. +IMPLOT3D_API void PlotImage(const char* label_id, ImTextureRef tex_ref, const ImPlot3DPoint& center, const ImPlot3DPoint& axis_u, + const ImPlot3DPoint& axis_v, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), + const ImVec4& tint_col = ImVec4(1, 1, 1, 1), const ImPlot3DSpec& spec = ImPlot3DSpec()); + +// Plots an image using four arbitrary 3D points that define a quad in space. +// Each corner (p0 to p3) corresponds to a corner in the image, and #uv0 to #uv3 are the texture coordinates for each. +// This overload allows full control over orientation, shape, and distortion. +// Note: The quad is internally split into two triangles, so non-rectangular quads may produce rendering artifacts +// since distortion is interpolated per triangle rather than over the full quad. +IMPLOT3D_API void PlotImage(const char* label_id, ImTextureRef tex_ref, const ImPlot3DPoint& p0, const ImPlot3DPoint& p1, const ImPlot3DPoint& p2, + const ImPlot3DPoint& p3, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 0), + const ImVec2& uv2 = ImVec2(1, 1), const ImVec2& uv3 = ImVec2(0, 1), const ImVec4& tint_col = ImVec4(1, 1, 1, 1), + const ImPlot3DSpec& spec = ImPlot3DSpec()); + +// Plots a centered text label at point x,y,z with optional rotation angle (in radians) and pixel offset +IMPLOT3D_API void PlotText(const char* text, double x, double y, double z, double angle = 0.0, const ImVec2& pix_offset = ImVec2(0, 0)); + +// Plots a dummy item (can be used to modify legend entry appearance when called after plotting an item, or add a dummy legend entry) +IMPLOT3D_API void PlotDummy(const char* label_id, const ImPlot3DSpec& spec = ImPlot3DSpec()); + +//----------------------------------------------------------------------------- +// [SECTION] Plot Utils +//----------------------------------------------------------------------------- + +// Convert a position in the current plot's coordinate system to pixels +IMPLOT3D_API ImVec2 PlotToPixels(const ImPlot3DPoint& point); +IMPLOT3D_API ImVec2 PlotToPixels(double x, double y, double z); + +// Convert a pixel coordinate to a ray in the current plot's coordinate system. Useful for 3D picking and intersection tests +IMPLOT3D_API ImPlot3DRay PixelsToPlotRay(const ImVec2& pix); +IMPLOT3D_API ImPlot3DRay PixelsToPlotRay(double x, double y); + +// Convert a pixel coordinate to a point on one of the plot box's axis-aligned planes (XY, XZ, or YZ). +// By default, the result is masked to the axis ranges. Set #mask=false to project to the infinite plane. +// Returns ImPlot3DPoint(NAN, NAN, NAN) if the ray does not intersect the plane +IMPLOT3D_API ImPlot3DPoint PixelsToPlotPlane(const ImVec2& pix, ImPlane3D plane, bool mask = true); +IMPLOT3D_API ImPlot3DPoint PixelsToPlotPlane(double x, double y, ImPlane3D plane, bool mask = true); + +// Get the current plot rect position (top-left) in absolute screen coordinates +IMPLOT3D_API ImVec2 GetPlotRectPos(); +// Get the current plot rect size in pixels +IMPLOT3D_API ImVec2 GetPlotRectSize(); + +//----------------------------------------------------------------------------- +// [SECTION] Miscellaneous +//----------------------------------------------------------------------------- + +// Returns the ImDrawList used for rendering plot items. Use this to add custom rendering inside plots +IMPLOT3D_API ImDrawList* GetPlotDrawList(); + +//----------------------------------------------------------------------------- +// [SECTION] Styles API (legacy) +//----------------------------------------------------------------------------- + +// Get current style +IMPLOT3D_API ImPlot3DStyle& GetStyle(); +IMPLOT3D_API void SetStyle(const ImPlot3DStyle& style); + +// Set color styles +IMPLOT3D_API void StyleColorsAuto(ImPlot3DStyle* dst = nullptr); // Set colors with ImGui style +IMPLOT3D_API void StyleColorsDark(ImPlot3DStyle* dst = nullptr); // Set colors with dark style +IMPLOT3D_API void StyleColorsLight(ImPlot3DStyle* dst = nullptr); // Set colors with light style +IMPLOT3D_API void StyleColorsClassic(ImPlot3DStyle* dst = nullptr); // Set colors with classic style + +// Temporarily modify a style color. Don't forget to call PopStyleColor! +IMPLOT3D_API void PushStyleColor(ImPlot3DCol idx, ImU32 col); +IMPLOT3D_API void PushStyleColor(ImPlot3DCol idx, const ImVec4& col); +// Undo temporary style color modification(s). Undo multiple pushes at once by increasing count +IMPLOT3D_API void PopStyleColor(int count = 1); + +// Temporarily modify a style variable of float type. Don't forget to call PopStyleVar! +IMPLOT3D_API void PushStyleVar(ImPlot3DStyleVar idx, float val); +// Temporarily modify a style variable of int type. Don't forget to call PopStyleVar! +IMPLOT3D_API void PushStyleVar(ImPlot3DStyleVar idx, int val); +// Temporarily modify a style variable of ImVec2 type. Don't forget to call PopStyleVar! +IMPLOT3D_API void PushStyleVar(ImPlot3DStyleVar idx, const ImVec2& val); +// Undo temporary style variable modification(s). Undo multiple pushes at once by increasing count +IMPLOT3D_API void PopStyleVar(int count = 1); + +// Get color +IMPLOT3D_API ImVec4 GetStyleColorVec4(ImPlot3DCol idx); +IMPLOT3D_API ImU32 GetStyleColorU32(ImPlot3DCol idx); + +// Returns the next marker and advances the marker for the current plot. You need to call this between Begin/EndPlot! +IMPLOT3D_API ImPlot3DMarker NextMarker(); + +//----------------------------------------------------------------------------- +// [SECTION] Colormaps +//----------------------------------------------------------------------------- + +// Item styling is based on colormaps when the relevant ImPlot3DCol_XXX is set to +// IMPLOT3D_AUTO_COL (default). Several built-in colormaps are available. You can +// add and then push/pop your own colormaps as well. To permanently set a colormap, +// modify the Colormap index member of your ImPlot3DStyle. + +// Colormap data will be ignored and a custom color will be used if you have done one of the following: +// 1) Modified an item style color in your ImPlot3DStyle to anything other than IMPLOT3D_AUTO_COL. + +// Add a new colormap. The color data will be copied. The colormap can be used by pushing either the returned index or the +// string name with PushColormap. The colormap name must be unique and the size must be greater than 1. You will receive +// an assert otherwise! By default colormaps are considered to be qualitative (i.e. discrete). If you want to create a +// continuous colormap, set #qual=false. This will treat the colors you provide as keys, and ImPlot3D will build a linearly +// interpolated lookup table. The memory footprint of this table will be exactly ((size-1)*255+1)*4 bytes. + +IMPLOT3D_API ImPlot3DColormap AddColormap(const char* name, const ImVec4* cols, int size, bool qual = true); +IMPLOT3D_API ImPlot3DColormap AddColormap(const char* name, const ImU32* cols, int size, bool qual = true); + +// Returns the number of available colormaps (i.e. the built-in + user-added count) +IMPLOT3D_API int GetColormapCount(); +// Returns a null terminated string name for a colormap given an index. Returns nullptr if index is invalid +IMPLOT3D_API const char* GetColormapName(ImPlot3DColormap cmap); +// Returns an index number for a colormap given a valid string name. Returns -1 if name is invalid +IMPLOT3D_API ImPlot3DColormap GetColormapIndex(const char* name); + +// Temporarily switch to one of the built-in (i.e. ImPlot3DColormap_XXX) or user-added colormaps (i.e. a return value of AddColormap). Don't forget to +// call PopColormap! +IMPLOT3D_API void PushColormap(ImPlot3DColormap cmap); +// Push a colormap by string name. Use built-in names such as "Default", "Deep", "Jet", etc. or a string you provided to AddColormap. Don't forget to +// call PopColormap! +IMPLOT3D_API void PushColormap(const char* name); +// Undo temporary colormap modification(s). Undo multiple pushes at once by increasing count +IMPLOT3D_API void PopColormap(int count = 1); + +// Returns the next color from the current colormap and advances the colormap for the current plot +// Can also be used with no return value to skip colors if desired. You need to call it between Begin/EndPlot! +IMPLOT3D_API ImVec4 NextColormapColor(); + +// Returns the size of a colormap +IMPLOT3D_API int GetColormapSize(ImPlot3DColormap cmap = IMPLOT3D_AUTO); +// Returns a color from a colormap given an index >= 0 (modulo will be performed) +IMPLOT3D_API ImVec4 GetColormapColor(int idx, ImPlot3DColormap cmap = IMPLOT3D_AUTO); +// Sample a color from the current colormap given t between 0 and 1 +IMPLOT3D_API ImVec4 SampleColormap(float t, ImPlot3DColormap cmap = IMPLOT3D_AUTO); + +//----------------------------------------------------------------------------- +// [SECTION] Demo +//----------------------------------------------------------------------------- +// Add implot3d_demo.cpp to your sources to use methods in this section + +// Shows the ImPlot3D demo window +IMPLOT3D_API void ShowDemoWindow(bool* p_open = nullptr); +// Shows all ImPlot3D demos, without enclosing window +IMPLOT3D_API void ShowAllDemos(); + +// Shows ImPlot3D style editor block (not a window) +IMPLOT3D_API void ShowStyleEditor(ImPlot3DStyle* ref = nullptr); +// Shows ImPlot3D style selector and returns true if selection is changed (not a window) +IMPLOT3D_API bool ShowStyleSelector(const char* label); +// Shows ImPlot3D colormap selector and returns true if selection is changed (not a window) +IMPLOT3D_API bool ShowColormapSelector(const char* label); + +// Shows ImPlot3D metrics/debug information window. +IMPLOT3D_API void ShowMetricsWindow(bool* p_popen = nullptr); + +// Shows ImPlot3D about window. +IMPLOT3D_API void ShowAboutWindow(bool* p_open = nullptr); + +} // namespace ImPlot3D + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot3DPoint +//----------------------------------------------------------------------------- + +// ImPlot3DPoint: 3D vector to store points in 3D space +struct ImPlot3DPoint { + double x, y, z; // Coordinates + constexpr ImPlot3DPoint() : x(0.0), y(0.0), z(0.0) {} + constexpr ImPlot3DPoint(double _x, double _y, double _z) : x(_x), y(_y), z(_z) {} + + // Accessors + double& operator[](size_t idx) { + IM_ASSERT(idx == 0 || idx == 1 || idx == 2); + return ((double*)(void*)(char*)this)[idx]; + } + double operator[](size_t idx) const { + IM_ASSERT(idx == 0 || idx == 1 || idx == 2); + return ((const double*)(const void*)(const char*)this)[idx]; + } + + // Binary operators + IMPLOT3D_API ImPlot3DPoint operator*(double rhs) const; + IMPLOT3D_API ImPlot3DPoint operator/(double rhs) const; + IMPLOT3D_API ImPlot3DPoint operator+(const ImPlot3DPoint& rhs) const; + IMPLOT3D_API ImPlot3DPoint operator-(const ImPlot3DPoint& rhs) const; + IMPLOT3D_API ImPlot3DPoint operator*(const ImPlot3DPoint& rhs) const; + IMPLOT3D_API ImPlot3DPoint operator/(const ImPlot3DPoint& rhs) const; + + // Unary operator + IMPLOT3D_API ImPlot3DPoint operator-() const; + + // Compound assignment operators + IMPLOT3D_API ImPlot3DPoint& operator*=(double rhs); + IMPLOT3D_API ImPlot3DPoint& operator/=(double rhs); + IMPLOT3D_API ImPlot3DPoint& operator+=(const ImPlot3DPoint& rhs); + IMPLOT3D_API ImPlot3DPoint& operator-=(const ImPlot3DPoint& rhs); + IMPLOT3D_API ImPlot3DPoint& operator*=(const ImPlot3DPoint& rhs); + IMPLOT3D_API ImPlot3DPoint& operator/=(const ImPlot3DPoint& rhs); + + // Comparison operators + IMPLOT3D_API bool operator==(const ImPlot3DPoint& rhs) const; + IMPLOT3D_API bool operator!=(const ImPlot3DPoint& rhs) const; + + // Dot product + IMPLOT3D_API double Dot(const ImPlot3DPoint& rhs) const; + + // Cross product + IMPLOT3D_API ImPlot3DPoint Cross(const ImPlot3DPoint& rhs) const; + + // Get vector length + IMPLOT3D_API double Length() const; + + // Get vector squared length + IMPLOT3D_API double LengthSquared() const; + + // Normalize to unit length + IMPLOT3D_API void Normalize(); + + // Return vector normalized to unit length + IMPLOT3D_API ImPlot3DPoint Normalized() const; + + // Friend binary operators to allow commutative behavior + IMPLOT3D_API friend ImPlot3DPoint operator*(double lhs, const ImPlot3DPoint& rhs); + + // Check if the point is NaN + IMPLOT3D_API bool IsNaN() const; + +#ifdef IMPLOT3D_POINT_CLASS_EXTRA + IMPLOT3D_POINT_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math + // types and ImPlot3DPoint +#endif +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot3DRay +//----------------------------------------------------------------------------- + +// ImPlot3DRay: Represents a ray in 3D space with an origin and direction +struct ImPlot3DRay { + ImPlot3DPoint Origin; // Ray origin point + ImPlot3DPoint Direction; // Ray direction (not necessarily normalized) +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot3DPlane +//----------------------------------------------------------------------------- + +// ImPlot3DPlane: Represents a plane in 3D space defined by a point and normal vector +struct ImPlot3DPlane { + ImPlot3DPoint Point; // A point on the plane + ImPlot3DPoint Normal; // Plane normal vector +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot3DBox +//----------------------------------------------------------------------------- + +// ImPlot3DBox: Axis-aligned bounding box in 3D space +struct ImPlot3DBox { + ImPlot3DPoint Min; // Minimum corner of the box + ImPlot3DPoint Max; // Maximum corner of the box + + // Default constructor + constexpr ImPlot3DBox() : Min(ImPlot3DPoint()), Max(ImPlot3DPoint()) {} + + // Constructor with two points + constexpr ImPlot3DBox(const ImPlot3DPoint& min, const ImPlot3DPoint& max) : Min(min), Max(max) {} + + // Method to expand the box to include a point + IMPLOT3D_API void Expand(const ImPlot3DPoint& point); + + // Method to check if a point is inside the box + IMPLOT3D_API bool Contains(const ImPlot3DPoint& point) const; + + // Method to clip a line segment against the box + IMPLOT3D_API bool ClipLineSegment(const ImPlot3DPoint& p0, const ImPlot3DPoint& p1, ImPlot3DPoint& p0_clipped, ImPlot3DPoint& p1_clipped) const; +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot3DRange +//----------------------------------------------------------------------------- + +// ImPlot3DRange: Represents a 1D range with min and max values +struct ImPlot3DRange { + double Min; // Minimum value + double Max; // Maximum value + + constexpr ImPlot3DRange() : Min(0.0), Max(0.0) {} + constexpr ImPlot3DRange(double min, double max) : Min(min), Max(max) {} + + IMPLOT3D_API void Expand(double value); // Expand range to include value + IMPLOT3D_API bool Contains(double value) const; // Check if value is within range + double Size() const { return Max - Min; } // Get range size +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot3DQuat +//----------------------------------------------------------------------------- + +// ImPlot3DQuat: Quaternion for representing 3D rotations +struct ImPlot3DQuat { + double x, y, z, w; // Quaternion components + + // Constructors + constexpr ImPlot3DQuat() : x(0.0), y(0.0), z(0.0), w(1.0) {} + constexpr ImPlot3DQuat(double _x, double _y, double _z, double _w) : x(_x), y(_y), z(_z), w(_w) {} + + // Construct quaternion from angle-axis representation (angle in radians) + IMPLOT3D_API ImPlot3DQuat(double _angle, const ImPlot3DPoint& _axis); + + // Create quaternion that rotates from v0 to v1 + IMPLOT3D_API static ImPlot3DQuat FromTwoVectors(const ImPlot3DPoint& v0, const ImPlot3DPoint& v1); + + // Create quaternion from elevation and azimuth angles (in radians) + IMPLOT3D_API static ImPlot3DQuat FromElAz(double elevation, double azimuth); + + // Get quaternion length + IMPLOT3D_API double Length() const; + + // Get normalized quaternion + IMPLOT3D_API ImPlot3DQuat Normalized() const; + + // Conjugate of the quaternion + IMPLOT3D_API ImPlot3DQuat Conjugate() const; + + // Inverse of the quaternion + IMPLOT3D_API ImPlot3DQuat Inverse() const; + + // Binary operators + IMPLOT3D_API ImPlot3DQuat operator*(const ImPlot3DQuat& rhs) const; // Quaternion multiplication + + // Normalize the quaternion in place + IMPLOT3D_API ImPlot3DQuat& Normalize(); + + // Rotate a 3D point using the quaternion + IMPLOT3D_API ImPlot3DPoint operator*(const ImPlot3DPoint& point) const; + + // Comparison operators + IMPLOT3D_API bool operator==(const ImPlot3DQuat& rhs) const; + IMPLOT3D_API bool operator!=(const ImPlot3DQuat& rhs) const; + + // Spherical linear interpolation between two quaternions (t in [0,1]) + IMPLOT3D_API static ImPlot3DQuat Slerp(const ImPlot3DQuat& q1, const ImPlot3DQuat& q2, double t); + + // Get quaternion dot product + IMPLOT3D_API double Dot(const ImPlot3DQuat& rhs) const; + +#ifdef IMPLOT3D_QUAT_CLASS_EXTRA + IMPLOT3D_QUAT_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math + // types and ImPlot3DQuat +#endif +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImPlot3DStyle +//----------------------------------------------------------------------------- + +struct ImPlot3DStyle { + // Item style + float LineWeight; // Line weight in pixels + int Marker; // Default marker type (ImPlot3DMarker_None) + float MarkerSize; // Marker size in pixels (roughly the marker's "radius") + float FillAlpha; // Alpha modifier applied to plot fills + // Plot style + ImVec2 PlotDefaultSize; // Default size used when ImVec2(0,0) is passed to BeginPlot + ImVec2 PlotMinSize; // Minimum size plot frame can be when shrunk + ImVec2 PlotPadding; // Padding between widget frame and plot area + ImVec2 LabelPadding; // Padding between axes labels, tick labels, and plot edge + float ViewScaleFactor; // Scale factor for 3D view + // Legend style + ImVec2 LegendPadding; // Legend padding from plot edges + ImVec2 LegendInnerPadding; // Legend inner padding from legend edges + ImVec2 LegendSpacing; // Spacing between legend entries + // Colors + ImVec4 Colors[ImPlot3DCol_COUNT]; // Array of plot colors + inline ImVec4 GetColor(ImPlot3DCol idx) const { return Colors[idx]; } + inline void SetColor(ImPlot3DCol idx, const ImVec4& col) { Colors[idx] = col; } + // Colormap + ImPlot3DColormap Colormap; // The current colormap (ImPlot3DColormap_ enum or index from AddColormap) + // Constructor + IMPLOT3D_API ImPlot3DStyle(); + ImPlot3DStyle(const ImPlot3DStyle& other) = default; + ImPlot3DStyle& operator=(const ImPlot3DStyle& other) = default; +}; + +//----------------------------------------------------------------------------- +// [SECTION] Meshes +//----------------------------------------------------------------------------- + +namespace ImPlot3D { + +// Cube +constexpr int CUBE_VTX_COUNT = 8; // Number of cube vertices +constexpr int CUBE_IDX_COUNT = 36; // Number of cube indices (12 triangles) +extern ImPlot3DPoint cube_vtx[CUBE_VTX_COUNT]; // Cube vertices +extern unsigned int cube_idx[CUBE_IDX_COUNT]; // Cube indices + +// Sphere +constexpr int SPHERE_VTX_COUNT = 162; // Number of sphere vertices for 128 triangles +constexpr int SPHERE_IDX_COUNT = 960; // Number of sphere indices (128 triangles) +extern ImPlot3DPoint sphere_vtx[SPHERE_VTX_COUNT]; // Sphere vertices +extern unsigned int sphere_idx[SPHERE_IDX_COUNT]; // Sphere indices + +// Duck (Rubber Duck by Poly by Google [CC-BY] via Poly Pizza) +constexpr int DUCK_VTX_COUNT = 254; // Number of duck vertices +constexpr int DUCK_IDX_COUNT = 1428; // Number of duck indices +extern ImPlot3DPoint duck_vtx[DUCK_VTX_COUNT]; // Duck vertices +extern unsigned int duck_idx[DUCK_IDX_COUNT]; // Duck indices + +} // namespace ImPlot3D + +//----------------------------------------------------------------------------- +// [SECTION] Obsolete API +//----------------------------------------------------------------------------- + +// The following functions will be removed! Keep your copy of ImPlot3D up to date! +// Occasionally set '#define IMPLOT3D_DISABLE_OBSOLETE_FUNCTIONS' to stay ahead. +// If you absolutely must use these functions and do not want to receive compiler +// warnings, set '#define IMPLOT3D_DISABLE_OBSOLETE_WARNINGS'. + +#ifndef IMPLOT3D_DISABLE_OBSOLETE_FUNCTIONS + +#ifndef IMPLOT3D_DISABLE_OBSOLETE_WARNINGS +#if __cplusplus > 201402L +#define IMPLOT3D_DEPRECATED(method) [[deprecated]] method +#elif defined(__GNUC__) && !defined(__INTEL_COMPILER) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) +#define IMPLOT3D_DEPRECATED(method) method __attribute__((deprecated)) +#elif defined(_MSC_VER) +#define IMPLOT3D_DEPRECATED(method) __declspec(deprecated) method +#else +#define IMPLOT3D_DEPRECATED(method) method +#endif +#else +#define IMPLOT3D_DEPRECATED(method) method +#endif + +namespace ImPlot3D { + +// OBSOLETED in v0.4 (from February 2026) +// IMPLOT_API void SetNextLineStyle(const ImVec4& col = IMPLOT_AUTO_COL, float weight = IMPLOT_AUTO); // OBSOLETED IN v0.4 // Set +// ImPlotSpec.LineColor/LineWeight or construct ImPlotSpec with { ImPlotSpec_LineColor, color, ImPlotSpec_LineWeight, weight }. + +// IMPLOT_API void SetNextFillStyle(const ImVec4& col = IMPLOT_AUTO_COL, float alpha_mod = IMPLOT_AUTO);// OBSOLETED IN v0.4 // Set +// ImPlotSpec.FillColor/FillAlpha or construct ImPlotSpec with { ImPlotSpec_FillColor, color, ImPlotSpec_FillAlpha, alpha }. + +// IMPLOT_API void SetNextMarkerStyle(ImPlotMarker marker = IMPLOT_AUTO, float size = IMPLOT_AUTO, const ImVec4& fill = IMPLOT_AUTO_COL, float weight +// = IMPLOT_AUTO, const ImVec4& outline = IMPLOT_AUTO_COL); // OBSOLETED IN v0.4 // Set +// ImPlotSpec.Marker/MarkerSize/MarkerFillColor/LineWeight/MarkerLineColor or construct ImPlotSpec with { ImPlotSpec_Marker, marker, +// ImPlotSpec_MarkerSize, size, ImPlotSpec_MarkerFillColor, fill_color, ImPlotSpec_LineWeight, weight, ImPlotSpec_MarkerLineColor, outline }. + +// OBSOLETED in v0.3 -> PLANNED REMOVAL in v1.0 +IMPLOT3D_DEPRECATED(IMPLOT3D_API ImVec2 GetPlotPos()); // Renamed to GetPlotRectPos() +IMPLOT3D_DEPRECATED(IMPLOT3D_API ImVec2 GetPlotSize()); // Renamed to GetPlotRectSize() + +// OBSOLETED in v0.4 -> PLANNED REMOVAL in v1.0 +// Use PlotMesh(label_id, vtx_xs, vtx_ys, vtx_zs, idx, vtx_count, idx_count, spec) instead. +IMPLOT3D_DEPRECATED(IMPLOT3D_API void PlotMesh(const char* label_id, const ImPlot3DPoint* vtx, const unsigned int* idxs, int vtx_count, int idx_count, + const ImPlot3DSpec& spec = ImPlot3DSpec())); + +} // namespace ImPlot3D + +#endif // #ifndef IMPLOT3D_DISABLE_OBSOLETE_FUNCTIONS + +#endif // #ifndef IMGUI_DISABLE diff --git a/tools/upstream/implot3d_demo.cpp b/tools/upstream/implot3d_demo.cpp new file mode 100644 index 0000000..a5fc0f7 --- /dev/null +++ b/tools/upstream/implot3d_demo.cpp @@ -0,0 +1,2402 @@ +// SPDX-License-Identifier: MIT +// SPDX-FileCopyrightText: 2024-2026 Breno Cunha Queiroz + +// ImPlot3D v0.5 WIP + +// Acknowledgments: +// ImPlot3D is heavily inspired by ImPlot +// (https://github.com/epezent/implot) by Evan Pezent, +// and follows a similar code style and structure to +// maintain consistency with ImPlot's API. + +// Table of Contents: +// [SECTION] User Namespace +// [SECTION] Helpers +// [SECTION] Plots +// [SECTION] Axes +// [SECTION] Tools +// [SECTION] Custom +// [SECTION] Config +// [SECTION] Demo Window +// [SECTION] Style Editor +// [SECTION] User Namespace Implementation + +// We define this to avoid accidentally using the deprecated API +#ifndef IMPLOT_DISABLE_OBSOLETE_FUNCTIONS +#define IMPLOT_DISABLE_OBSOLETE_FUNCTIONS +#endif + +#include "implot3d.h" +#include "implot3d_internal.h" + +// Helper to wire demo markers located in code to an interactive browser (e.g. imgui_explorer) +#if IMGUI_VERSION_NUM >= 19263 +namespace ImGui { +extern IMGUI_API void DemoMarker(const char* file, int line, const char* section); +}; +#define IMGUI_DEMO_MARKER(section) \ + do { \ + ImGui::DemoMarker("implot3d_demo.cpp", __LINE__, section); \ + } while (0) +#else +#define IMGUI_DEMO_MARKER(section) +#endif + +//----------------------------------------------------------------------------- +// [SECTION] User Namespace +//----------------------------------------------------------------------------- + +// Encapsulates examples for customizing ImPlot3D +namespace MyImPlot3D { + +// Example for Custom Styles section +void StyleSeaborn(); + +} // namespace MyImPlot3D + +namespace ImPlot3D { + +//----------------------------------------------------------------------------- +// [SECTION] Helpers +//----------------------------------------------------------------------------- + +#define CHECKBOX_FLAG(flags, flag) ImGui::CheckboxFlags(#flag, (unsigned int*)&flags, flag) + +static void HelpMarker(const char* desc) { + ImGui::TextDisabled("(?)"); + if (ImGui::BeginItemTooltip()) { + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); + ImGui::TextUnformatted(desc); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } +} + +// Utility structure for realtime plot +struct ScrollingBuffer { + int MaxSize; + int Offset; + ImVector Data; + ScrollingBuffer(int max_size = 2000) { + MaxSize = max_size; + Offset = 0; + Data.reserve(MaxSize); + } + void AddPoint(float x) { + if (Data.size() < MaxSize) + Data.push_back(x); + else { + Data[Offset] = x; + Offset = (Offset + 1) % MaxSize; + } + } + void Erase() { + if (Data.size() > 0) { + Data.shrink(0); + Offset = 0; + } + } +}; + +// Custom axis formatter that adds metric prefixes (G, M, k, m, u, n) +int MetricFormatter(double value, char* buff, int size, void* data) { + const char* unit = (const char*)data; + static double v[] = {1000000000, 1000000, 1000, 1, 0.001, 0.000001, 0.000000001}; + static const char* p[] = {"G", "M", "k", "", "m", "u", "n"}; + if (value == 0) { + return snprintf(buff, size, "0 %s", unit); + } + for (int i = 0; i < 7; ++i) { + if (fabs(value) >= v[i]) { + return snprintf(buff, size, "%g %s%s", value / v[i], p[i], unit); + } + } + return snprintf(buff, size, "%g %s%s", value / v[6], p[6], unit); +} + +//----------------------------------------------------------------------------- +// [SECTION] Plots +//----------------------------------------------------------------------------- + +void DemoLinePlots() { + IMGUI_DEMO_MARKER("Plots/Line Plots"); + static float xs1[1001], ys1[1001], zs1[1001]; + for (int i = 0; i < 1001; i++) { + xs1[i] = i * 0.001f; + ys1[i] = 0.5f + 0.5f * cosf(50 * (xs1[i] + (float)ImGui::GetTime() / 10)); + zs1[i] = 0.5f + 0.5f * sinf(50 * (xs1[i] + (float)ImGui::GetTime() / 10)); + } + static double xs2[20], ys2[20], zs2[20]; + for (int i = 0; i < 20; i++) { + xs2[i] = i * 1 / 19.0f; + ys2[i] = xs2[i] * xs2[i]; + zs2[i] = xs2[i] * ys2[i]; + } + if (ImPlot3D::BeginPlot("Line Plots")) { + ImPlot3D::SetupAxes("x", "y", "z"); + ImPlot3D::PlotLine("f(x)", xs1, ys1, zs1, 1001); + ImPlot3D::PlotLine("g(x)", xs2, ys2, zs2, 20, {ImPlot3DProp_Marker, ImPlot3DMarker_Circle, ImPlot3DProp_Flags, ImPlot3DLineFlags_Segments}); + ImPlot3D::EndPlot(); + } +} + +void DemoScatterPlots() { + IMGUI_DEMO_MARKER("Plots/Scatter Plots"); + srand(0); + static float xs1[100], ys1[100], zs1[100]; + for (int i = 0; i < 100; i++) { + xs1[i] = i * 0.01f; + ys1[i] = xs1[i] + 0.1f * ((float)rand() / (float)RAND_MAX); + zs1[i] = xs1[i] + 0.1f * ((float)rand() / (float)RAND_MAX); + } + static float xs2[50], ys2[50], zs2[50]; + for (int i = 0; i < 50; i++) { + xs2[i] = 0.25f + 0.2f * ((float)rand() / (float)RAND_MAX); + ys2[i] = 0.50f + 0.2f * ((float)rand() / (float)RAND_MAX); + zs2[i] = 0.75f + 0.2f * ((float)rand() / (float)RAND_MAX); + } + + if (ImPlot3D::BeginPlot("Scatter Plots")) { + ImPlot3D::PlotScatter("Data 1", xs1, ys1, zs1, 100); + ImPlot3DSpec spec; + spec.Marker = ImPlot3DMarker_Square; + spec.MarkerSize = 6; + spec.MarkerLineColor = ImPlot3D::GetColormapColor(1); + spec.MarkerFillColor = ImPlot3D::GetColormapColor(1); + spec.FillAlpha = 0.25f; + ImPlot3D::PlotScatter("Data 2", xs2, ys2, zs2, 50, spec); + ImPlot3D::EndPlot(); + } +} + +void DemoTrianglePlots() { + IMGUI_DEMO_MARKER("Plots/Triangle Plots"); + // Pyramid coordinates + // Apex + float ax = 0.0f, ay = 0.0f, az = 1.0f; + // Square base corners + float cx[4] = {-0.5f, 0.5f, 0.5f, -0.5f}; + float cy[4] = {-0.5f, -0.5f, 0.5f, 0.5f}; + float cz[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + + // We have 6 triangles (18 vertices) total: + // Sides: + // T1: apex, corner0, corner1 + // T2: apex, corner1, corner2 + // T3: apex, corner2, corner3 + // T4: apex, corner3, corner0 + // Base (two triangles form a square): + // T5: corner0, corner1, corner2 + // T6: corner0, corner2, corner3 + + static float xs[18], ys[18], zs[18]; + int i = 0; + + // Helper lambda to append a vertex + auto AddVertex = [&](float X, float Y, float Z) { + xs[i] = X; + ys[i] = Y; + zs[i] = Z; + i++; + }; + + // Triangle 1 + AddVertex(ax, ay, az); + AddVertex(cx[0], cy[0], cz[0]); + AddVertex(cx[1], cy[1], cz[1]); + + // Triangle 2 + AddVertex(ax, ay, az); + AddVertex(cx[1], cy[1], cz[1]); + AddVertex(cx[2], cy[2], cz[2]); + + // Triangle 3 + AddVertex(ax, ay, az); + AddVertex(cx[2], cy[2], cz[2]); + AddVertex(cx[3], cy[3], cz[3]); + + // Triangle 4 + AddVertex(ax, ay, az); + AddVertex(cx[3], cy[3], cz[3]); + AddVertex(cx[0], cy[0], cz[0]); + + // Triangle 5 (base) + AddVertex(cx[0], cy[0], cz[0]); + AddVertex(cx[1], cy[1], cz[1]); + AddVertex(cx[2], cy[2], cz[2]); + + // Triangle 6 (base) + AddVertex(cx[0], cy[0], cz[0]); + AddVertex(cx[2], cy[2], cz[2]); + AddVertex(cx[3], cy[3], cz[3]); + + // Now we have 18 vertices in xs, ys, zs forming the pyramid + + // Triangle flags + static ImPlot3DTriangleFlags flags = ImPlot3DTriangleFlags_None; + CHECKBOX_FLAG(flags, ImPlot3DTriangleFlags_NoLines); + CHECKBOX_FLAG(flags, ImPlot3DTriangleFlags_NoFill); + CHECKBOX_FLAG(flags, ImPlot3DTriangleFlags_NoMarkers); + + if (ImPlot3D::BeginPlot("Triangle Plots")) { + ImPlot3D::SetupAxesLimits(-1, 1, -1, 1, -0.5, 1.5); + + // Setup pyramid colors + ImPlot3DSpec spec; + spec.FillColor = ImPlot3D::GetColormapColor(0); + spec.LineColor = ImPlot3D::GetColormapColor(1); + spec.Marker = ImPlot3DMarker_Square; + spec.MarkerSize = 3; + spec.Flags = flags; + + // Plot pyramid + ImPlot3D::PlotTriangle("Pyramid", xs, ys, zs, 6 * 3, spec); // 6 triangles, 3 vertices each = 18 + ImPlot3D::EndPlot(); + } +} + +void DemoQuadPlots() { + IMGUI_DEMO_MARKER("Plots/Quad Plots"); + static float xs[6 * 4], ys[6 * 4], zs[6 * 4]; + + // clang-format off + // Initialize the cube vertices for +x and -x faces + // +x face + xs[0] = 1; ys[0] = -1; zs[0] = -1; + xs[1] = 1; ys[1] = 1; zs[1] = -1; + xs[2] = 1; ys[2] = 1; zs[2] = 1; + xs[3] = 1; ys[3] = -1; zs[3] = 1; + + // -x face + xs[4] = -1; ys[4] = -1; zs[4] = -1; + xs[5] = -1; ys[5] = 1; zs[5] = -1; + xs[6] = -1; ys[6] = 1; zs[6] = 1; + xs[7] = -1; ys[7] = -1; zs[7] = 1; + + // Initialize the cube vertices for +y and -y faces + // +y face + xs[8] = -1; ys[8] = 1; zs[8] = -1; + xs[9] = 1; ys[9] = 1; zs[9] = -1; + xs[10] = 1; ys[10] = 1; zs[10] = 1; + xs[11] = -1; ys[11] = 1; zs[11] = 1; + + // -y face + xs[12] = -1; ys[12] = -1; zs[12] = -1; + xs[13] = 1; ys[13] = -1; zs[13] = -1; + xs[14] = 1; ys[14] = -1; zs[14] = 1; + xs[15] = -1; ys[15] = -1; zs[15] = 1; + + // Initialize the cube vertices for +z and -z faces + // +z face + xs[16] = -1; ys[16] = -1; zs[16] = 1; + xs[17] = 1; ys[17] = -1; zs[17] = 1; + xs[18] = 1; ys[18] = 1; zs[18] = 1; + xs[19] = -1; ys[19] = 1; zs[19] = 1; + + // -z face + xs[20] = -1; ys[20] = -1; zs[20] = -1; + xs[21] = 1; ys[21] = -1; zs[21] = -1; + xs[22] = 1; ys[22] = 1; zs[22] = -1; + xs[23] = -1; ys[23] = 1; zs[23] = -1; + // clang-format on + + // Quad flags + static ImPlot3DQuadFlags flags = ImPlot3DQuadFlags_None; + CHECKBOX_FLAG(flags, ImPlot3DQuadFlags_NoLines); + CHECKBOX_FLAG(flags, ImPlot3DQuadFlags_NoFill); + CHECKBOX_FLAG(flags, ImPlot3DQuadFlags_NoMarkers); + + if (ImPlot3D::BeginPlot("Quad Plots")) { + ImPlot3D::SetupAxesLimits(-1.5, 1.5, -1.5, 1.5, -1.5, 1.5); + + ImPlot3DSpec spec; + spec.Marker = ImPlot3DMarker_Square; + spec.MarkerSize = 3; + spec.Flags = flags; + + // Render +x and -x faces + static ImVec4 colorX(0.8f, 0.2f, 0.2f, 0.8f); // Red + spec.FillColor = colorX; + spec.LineColor = colorX; + ImPlot3D::PlotQuad("X", &xs[0], &ys[0], &zs[0], 8, spec); + + // Render +y and -y faces + static ImVec4 colorY(0.2f, 0.8f, 0.2f, 0.8f); // Green + spec.FillColor = colorY; + spec.LineColor = colorY; + ImPlot3D::PlotQuad("Y", &xs[8], &ys[8], &zs[8], 8, spec); + + // Render +z and -z faces + static ImVec4 colorZ(0.2f, 0.2f, 0.8f, 0.8f); // Blue + spec.FillColor = colorZ; + spec.LineColor = colorZ; + ImPlot3D::PlotQuad("Z", &xs[16], &ys[16], &zs[16], 8, spec); + + ImPlot3D::EndPlot(); + } +} + +void DemoSurfacePlots() { + IMGUI_DEMO_MARKER("Plots/Surface Plots"); + constexpr int N = 20; + static float xs[N * N], ys[N * N], zs[N * N]; + static ImU32 custom_colors[N * N]; + static float t = 0.0f; + t += ImGui::GetIO().DeltaTime; + + // Define the range for X and Y + constexpr float min_val = -1.0f; + constexpr float max_val = 1.0f; + constexpr float step = (max_val - min_val) / (N - 1); + + // Populate the xs, ys, and zs arrays + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + int idx = i * N + j; + xs[idx] = min_val + j * step; // X values are constant along rows + ys[idx] = min_val + i * step; // Y values are constant along columns + zs[idx] = ImSin(2 * t + ImSqrt((xs[idx] * xs[idx] + ys[idx] * ys[idx]))); // z = sin(2t + sqrt(x^2 + y^2)) + // Custom per-point color: R=x, G=y, B=z (each remapped from [-1,1] to [0,1]) + custom_colors[idx] = + IM_COL32((ImU8)((xs[idx] + 1) * 0.5f * 255), (ImU8)((ys[idx] + 1) * 0.5f * 255), (ImU8)((zs[idx] + 1) * 0.5f * 255), 255); + } + } + + // Choose fill color + ImGui::Text("Fill color"); + static int selected_fill = 1; // Colormap by default + static ImVec4 solid_color = ImVec4(0.8f, 0.8f, 0.2f, 0.6f); + const char* colormaps[] = {"Viridis", "Plasma", "Hot", "Cool", "Pink", "Jet", "Twilight", "RdBu", "BrBG", "PiYG", "Spectral", "Greys"}; + static int sel_colormap = 5; // Jet by default + { + ImGui::Indent(); + + // Choose solid color + ImGui::RadioButton("Solid", &selected_fill, 0); + if (selected_fill == 0) { + ImGui::SameLine(); + ImGui::ColorEdit4("##SurfaceSolidColor", (float*)&solid_color); + } + + // Choose colormap + ImGui::RadioButton("Colormap", &selected_fill, 1); + if (selected_fill == 1) { + ImGui::SameLine(); + ImGui::Combo("##SurfaceColormap", &sel_colormap, colormaps, IM_ARRAYSIZE(colormaps)); + } + + // Custom per-point colors + ImGui::RadioButton("Custom Per-Point", &selected_fill, 2); + if (selected_fill == 2) + ImGui::SameLine(), ImGui::TextDisabled("R=x, G=y, B=z"); + + ImGui::Unindent(); + } + + // Choose range (only applies to Colormap mode) + static bool custom_range = false; + static float range_min = -1.0f; + static float range_max = 1.0f; + if (selected_fill != 1) + ImGui::BeginDisabled(); + ImGui::Checkbox("Custom range", &custom_range); + { + ImGui::Indent(); + + if (!custom_range) + ImGui::BeginDisabled(); + ImGui::SliderFloat("Range min", &range_min, -1.0f, range_max - 0.01f); + ImGui::SliderFloat("Range max", &range_max, range_min + 0.01f, 1.0f); + if (!custom_range) + ImGui::EndDisabled(); + + ImGui::Unindent(); + } + if (selected_fill != 1) + ImGui::EndDisabled(); + + // Select flags + static ImPlot3DSurfaceFlags flags = ImPlot3DSurfaceFlags_NoMarkers; + CHECKBOX_FLAG(flags, ImPlot3DSurfaceFlags_NoLines); + CHECKBOX_FLAG(flags, ImPlot3DSurfaceFlags_NoFill); + CHECKBOX_FLAG(flags, ImPlot3DSurfaceFlags_NoMarkers); + + // Begin the plot + if (selected_fill == 1) + ImPlot3D::PushColormap(colormaps[sel_colormap]); + if (ImPlot3D::BeginPlot("Surface Plots", ImVec2(-1, 0), ImPlot3DFlags_NoClip)) { + ImPlot3D::SetupAxesLimits(-1, 1, -1, 1, -1.5, 1.5); + + ImPlot3DSpec spec; + spec.FillAlpha = 0.8f; + spec.Flags = flags; + spec.Marker = ImPlot3DMarker_Square; + spec.LineColor = ImPlot3D::GetColormapColor(1); + if (selected_fill == 0) + spec.FillColor = solid_color; + else if (selected_fill == 2) + spec.FillColors = custom_colors; + + // Plot the surface + if (custom_range) + ImPlot3D::PlotSurface("Wave Surface", xs, ys, zs, N, N, (double)range_min, (double)range_max, spec); + else + ImPlot3D::PlotSurface("Wave Surface", xs, ys, zs, N, N, 0.0, 0.0, spec); + + // End the plot + ImPlot3D::EndPlot(); + } + if (selected_fill == 1) + ImPlot3D::PopColormap(); +} + +void DemoMeshPlots() { + IMGUI_DEMO_MARKER("Plots/Mesh Plots"); + static int mesh_id = 0; + ImGui::Combo("Mesh", &mesh_id, "Duck\0Sphere\0Cube\0\0"); + + // Choose line color + static ImVec4 line_color = ImVec4(0.5f, 0.5f, 0.2f, 0.6f); + ImGui::ColorEdit4("Line Color##Mesh", (float*)&line_color); + + // Choose fill color + static ImVec4 fill_color = ImVec4(0.8f, 0.8f, 0.2f, 0.6f); + ImGui::ColorEdit4("Fill Color##Mesh", (float*)&fill_color); + + // Choose marker color + static ImVec4 marker_color = ImVec4(0.5f, 0.5f, 0.2f, 0.6f); + ImGui::ColorEdit4("Marker Color##Mesh", (float*)&marker_color); + + // Mesh flags + static ImPlot3DMeshFlags flags = ImPlot3DMeshFlags_NoMarkers; + CHECKBOX_FLAG(flags, ImPlot3DMeshFlags_NoLines); + CHECKBOX_FLAG(flags, ImPlot3DMeshFlags_NoFill); + CHECKBOX_FLAG(flags, ImPlot3DMeshFlags_NoMarkers); + + if (ImPlot3D::BeginPlot("Mesh Plots")) { + ImPlot3D::SetupAxesLimits(-1, 1, -1, 1, -1, 1); + + ImPlot3DSpec spec; + spec.Flags = flags; + spec.Stride = (int)sizeof(ImPlot3DPoint); + // Set fill style + spec.FillColor = fill_color; + // Set line style + spec.LineColor = line_color; + // Set marker style + spec.Marker = ImPlot3DMarker_Square; + spec.MarkerSize = 3.0f; + spec.MarkerLineColor = marker_color; + spec.MarkerFillColor = marker_color; + + // Plot mesh + if (mesh_id == 0) + ImPlot3D::PlotMesh("Duck", &duck_vtx[0].x, &duck_vtx[0].y, &duck_vtx[0].z, duck_idx, DUCK_VTX_COUNT, DUCK_IDX_COUNT, spec); + else if (mesh_id == 1) + ImPlot3D::PlotMesh("Sphere", &sphere_vtx[0].x, &sphere_vtx[0].y, &sphere_vtx[0].z, sphere_idx, SPHERE_VTX_COUNT, SPHERE_IDX_COUNT, spec); + else if (mesh_id == 2) + ImPlot3D::PlotMesh("Cube", &cube_vtx[0].x, &cube_vtx[0].y, &cube_vtx[0].z, cube_idx, CUBE_VTX_COUNT, CUBE_IDX_COUNT, spec); + + ImPlot3D::EndPlot(); + } +} + +void DemoImagePlots() { + IMGUI_DEMO_MARKER("Plots/Image Plots"); + ImGui::BulletText("Below we are displaying the font texture, which is the only texture we have\naccess to in this demo."); + ImGui::BulletText("Use the 'ImTextureID' type as storage to pass pointers or identifiers to your\nown texture data."); + ImGui::BulletText("See ImGui Wiki page 'Image Loading and Displaying Examples'."); + + static ImVec4 tint1(1, 1, 1, 1); + static ImVec4 tint2(1, 1, 1, 1); + + static ImPlot3DPoint center1(0, 0, 1); + static ImPlot3DPoint axis_u1(1, 0, 0); + static ImPlot3DPoint axis_v1(0, 1, 0); + static ImVec2 uv0_1(0, 0), uv1_1(1, 1); + + static ImPlot3DPoint p0(-1, -1, 0); + static ImPlot3DPoint p1(1, -1, 0); + static ImPlot3DPoint p2(1, 1, 0); + static ImPlot3DPoint p3(-1, 1, 0); + static ImVec2 uv0(0, 0), uv1(1, 0), uv2(1, 1), uv3(0, 1); + + // Spacing + ImGui::Dummy(ImVec2(0, 10)); + + // Image 1 Controls + if (ImGui::TreeNodeEx("Image 1 Controls: Center + Axes")) { + float center1_f[3] = {(float)center1.x, (float)center1.y, (float)center1.z}; + if (ImGui::SliderFloat3("Center", center1_f, -2, 2, "%.1f")) { + center1 = ImPlot3DPoint(center1_f[0], center1_f[1], center1_f[2]); + } + float axis_u1_f[3] = {(float)axis_u1.x, (float)axis_u1.y, (float)axis_u1.z}; + if (ImGui::SliderFloat3("Axis U", axis_u1_f, -2, 2, "%.1f")) { + axis_u1 = ImPlot3DPoint(axis_u1_f[0], axis_u1_f[1], axis_u1_f[2]); + } + float axis_v1_f[3] = {(float)axis_v1.x, (float)axis_v1.y, (float)axis_v1.z}; + if (ImGui::SliderFloat3("Axis V", axis_v1_f, -2, 2, "%.1f")) { + axis_v1 = ImPlot3DPoint(axis_v1_f[0], axis_v1_f[1], axis_v1_f[2]); + } + ImGui::SliderFloat2("UV0", &uv0_1.x, 0, 1, "%.2f"); + ImGui::SliderFloat2("UV1", &uv1_1.x, 0, 1, "%.2f"); + ImGui::ColorEdit4("Tint", &tint1.x); + + ImGui::TreePop(); + } + + // Image 2 Controls + if (ImGui::TreeNodeEx("Image 2 Controls: Full Quad")) { + float p0_f[3] = {(float)p0.x, (float)p0.y, (float)p0.z}; + if (ImGui::SliderFloat3("P0", p0_f, -2, 2, "%.1f")) { + p0 = ImPlot3DPoint(p0_f[0], p0_f[1], p0_f[2]); + } + float p1_f[3] = {(float)p1.x, (float)p1.y, (float)p1.z}; + if (ImGui::SliderFloat3("P1", p1_f, -2, 2, "%.1f")) { + p1 = ImPlot3DPoint(p1_f[0], p1_f[1], p1_f[2]); + } + float p2_f[3] = {(float)p2.x, (float)p2.y, (float)p2.z}; + if (ImGui::SliderFloat3("P2", p2_f, -2, 2, "%.1f")) { + p2 = ImPlot3DPoint(p2_f[0], p2_f[1], p2_f[2]); + } + float p3_f[3] = {(float)p3.x, (float)p3.y, (float)p3.z}; + if (ImGui::SliderFloat3("P3", p3_f, -2, 2, "%.1f")) { + p3 = ImPlot3DPoint(p3_f[0], p3_f[1], p3_f[2]); + } + + ImGui::SliderFloat2("UV0", &uv0.x, 0, 1, "%.2f"); + ImGui::SliderFloat2("UV1", &uv1.x, 0, 1, "%.2f"); + ImGui::SliderFloat2("UV2", &uv2.x, 0, 1, "%.2f"); + ImGui::SliderFloat2("UV3", &uv3.x, 0, 1, "%.2f"); + + ImGui::ColorEdit4("Tint##2", &tint2.x); + + ImGui::TreePop(); + } + + // Plot + if (ImPlot3D::BeginPlot("Image Plot", ImVec2(-1, 0), ImPlot3DFlags_NoClip)) { +#ifdef IMGUI_HAS_TEXTURES + // We use the font atlas ImTextureRef for this demo, but in your real code when you submit + // an image that you have loaded yourself, you would normally have a ImTextureID which works + // just as well (as ImTextureRef can be constructed from ImTextureID). + ImTextureRef tex = ImGui::GetIO().Fonts->TexRef; +#else + ImTextureID tex = ImGui::GetIO().Fonts->TexID; +#endif + + ImPlot3D::PlotImage("Image 1", tex, center1, axis_u1, axis_v1, uv0_1, uv1_1, tint1); + ImPlot3D::PlotImage("Image 2", tex, p0, p1, p2, p3, uv0, uv1, uv2, uv3, tint2); + + ImPlot3D::EndPlot(); + } +} + +void DemoRealtimePlots() { + IMGUI_DEMO_MARKER("Plots/Realtime Plots"); + ImGui::BulletText("Move your mouse to change the data!"); + static ScrollingBuffer sdata1, sdata2, sdata3; + static ImPlot3DAxisFlags flags = ImPlot3DAxisFlags_NoTickLabels; + static float t = 0.0f; + static float last_t = -1.0f; + + if (ImPlot3D::BeginPlot("Scrolling Plot")) { + // Pool mouse data every 10 ms + t += ImGui::GetIO().DeltaTime; + if (t - last_t > 0.01f) { + last_t = t; + ImVec2 mouse = ImGui::GetMousePos(); + if (ImAbs(mouse.x) < 1e4f && ImAbs(mouse.y) < 1e4f) { + ImVec2 plot_center = ImPlot3D::GetFramePos(); + plot_center.x += ImPlot3D::GetFrameSize().x / 2; + plot_center.y += ImPlot3D::GetFrameSize().y / 2; + sdata1.AddPoint(t); + sdata2.AddPoint(mouse.x - plot_center.x); + sdata3.AddPoint(mouse.y - plot_center.y); + } + } + + ImPlot3D::SetupAxes("Time", "Mouse X", "Mouse Y", flags, flags, flags); + ImPlot3D::SetupAxisLimits(ImAxis3D_X, t - 10.0, t, ImPlot3DCond_Always); + ImPlot3D::SetupAxisLimits(ImAxis3D_Y, -400, 400, ImPlot3DCond_Once); + ImPlot3D::SetupAxisLimits(ImAxis3D_Z, -400, 400, ImPlot3DCond_Once); + ImPlot3D::PlotLine("Mouse", &sdata1.Data[0], &sdata2.Data[0], &sdata3.Data[0], sdata1.Data.size(), + {ImPlot3DProp_Offset, sdata1.Offset, ImPlot3DProp_Stride, sizeof(float)}); + ImPlot3D::EndPlot(); + } +} + +void DemoPlotFlags() { + IMGUI_DEMO_MARKER("Plots/Plot Flags"); + static ImPlot3DFlags flags = ImPlot3DFlags_None; + + CHECKBOX_FLAG(flags, ImPlot3DFlags_NoTitle); + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Hide plot title"); + } + + CHECKBOX_FLAG(flags, ImPlot3DFlags_NoLegend); + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Hide plot legend"); + } + + CHECKBOX_FLAG(flags, ImPlot3DFlags_NoMouseText); + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Hide mouse position in plot coordinates"); + } + + CHECKBOX_FLAG(flags, ImPlot3DFlags_NoClip); + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Disable 3D box clipping"); + } + + CHECKBOX_FLAG(flags, ImPlot3DFlags_NoMenus); + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("The user will not be able to open context menus"); + } + + CHECKBOX_FLAG(flags, ImPlot3DFlags_Equal); + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("X, Y, and Z axes will be constrained to have the same units/pixel"); + } + + CHECKBOX_FLAG(flags, ImPlot3DFlags_NoRotate); + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Lock rotation interaction"); + } + + CHECKBOX_FLAG(flags, ImPlot3DFlags_NoPan); + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Lock panning/translation interaction"); + } + + CHECKBOX_FLAG(flags, ImPlot3DFlags_NoZoom); + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Lock zooming interaction"); + } + + CHECKBOX_FLAG(flags, ImPlot3DFlags_NoInputs); + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Disable all user inputs"); + } + + if (ImPlot3D::BeginPlot("Plot Flags Demo", ImVec2(-1, 0), flags)) { + ImPlot3D::SetupAxes("X-axis", "Y-axis", "Z-axis"); + ImPlot3D::SetupAxesLimits(-10, 10, -10, 10, -5, 5); + + // Generate some sample data for demonstration + static float x[100], y[100], z[100]; + static bool first = true; + if (first) { + for (int i = 0; i < 100; i++) { + float t = i * 0.1f; + x[i] = 3.0f * cosf(t); + y[i] = 3.0f * sinf(t); + z[i] = t - 5.0f; + } + first = false; + } + + ImPlot3D::PlotLine("Helix", x, y, z, 100); + + // Add some scatter points to show equal scaling effect + float scatter_x[8] = {-10, 10, -10, 10, -10, 10, -10, 10}; + float scatter_y[8] = {-10, -10, 10, 10, -10, -10, 10, 10}; + float scatter_z[8] = {-5, -5, -5, -5, 5, 5, 5, 5}; + ImPlot3D::PlotScatter("Cube corners", scatter_x, scatter_y, scatter_z, 8); + + ImPlot3D::EndPlot(); + } +} + +void DemoOffsetAndStride() { + IMGUI_DEMO_MARKER("Plots/Offset and Stride"); + static const int k_spirals = 11; + static const int k_points_per = 50; + static const int k_size = 3 * k_points_per * k_spirals; + static double interleaved_data[k_size]; + for (int p = 0; p < k_points_per; ++p) { + for (int s = 0; s < k_spirals; ++s) { + double r = (double)s / (k_spirals - 1) * 0.2 + 0.2; + double theta = (double)p / k_points_per * 6.28; + interleaved_data[p * 3 * k_spirals + 3 * s + 0] = 0.5 + r * cos(theta); + interleaved_data[p * 3 * k_spirals + 3 * s + 1] = 0.5 + r * sin(theta); + interleaved_data[p * 3 * k_spirals + 3 * s + 2] = 0.5 + 0.5 * sin(2.0 * theta); + } + } + static int offset = 0; + ImGui::BulletText("Offsetting is useful for realtime plots (see above) and circular buffers."); + ImGui::BulletText("Striding is useful for interleaved data (e.g. audio) or plotting structs."); + ImGui::BulletText("Here, all spiral data is stored in a single interleaved buffer:"); + ImGui::BulletText("[s0.x0 s0.y0 s0.z0 ... sn.x0 sn.y0 sn.z0 s0.x1 s0.y1 s0.z1 ... sn.x1 sn.y1 sn.z1 ... sn.xm sn.ym sn.zm]"); + ImGui::BulletText("The offset value indicates which spiral point index is considered the first."); + ImGui::BulletText("Offsets can be negative and/or larger than the actual data count."); + ImGui::SliderInt("Offset", &offset, -2 * k_points_per, 2 * k_points_per); + if (ImPlot3D::BeginPlot("##strideoffset", ImVec2(-1, 0))) { + ImPlot3D::PushColormap(ImPlot3DColormap_Jet); + char buff[32]; + for (int s = 0; s < k_spirals; ++s) { + snprintf(buff, sizeof(buff), "Spiral %d", s); + ImPlot3DSpec spec; + spec.Offset = offset; + spec.Stride = 3 * k_spirals * sizeof(double); + ImPlot3D::PlotLine(buff, &interleaved_data[s * 3 + 0], &interleaved_data[s * 3 + 1], &interleaved_data[s * 3 + 2], k_points_per, spec); + } + ImPlot3D::EndPlot(); + ImPlot3D::PopColormap(); + } +} + +void DemoLegendOptions() { + IMGUI_DEMO_MARKER("Plots/Legend Options"); + static ImPlot3DLocation loc = ImPlot3DLocation_East; + ImGui::CheckboxFlags("North", (unsigned int*)&loc, ImPlot3DLocation_North); + ImGui::SameLine(); + ImGui::CheckboxFlags("South", (unsigned int*)&loc, ImPlot3DLocation_South); + ImGui::SameLine(); + ImGui::CheckboxFlags("West", (unsigned int*)&loc, ImPlot3DLocation_West); + ImGui::SameLine(); + ImGui::CheckboxFlags("East", (unsigned int*)&loc, ImPlot3DLocation_East); + + static ImPlot3DLegendFlags flags = 0; + + CHECKBOX_FLAG(flags, ImPlot3DLegendFlags_Horizontal); + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Legend entries will be displayed horizontally"); + } + + CHECKBOX_FLAG(flags, ImPlot3DLegendFlags_NoButtons); + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Legend icons will not function as hide/show buttons"); + } + + CHECKBOX_FLAG(flags, ImPlot3DLegendFlags_NoHighlightItem); + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::SetTooltip("Plot items will not be highlighted when their legend entry is hovered"); + } + + ImGui::SliderFloat2("LegendPadding", (float*)&ImPlot3D::GetStyle().LegendPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("LegendInnerPadding", (float*)&ImPlot3D::GetStyle().LegendInnerPadding, 0.0f, 10.0f, "%.0f"); + ImGui::SliderFloat2("LegendSpacing", (float*)&ImPlot3D::GetStyle().LegendSpacing, 0.0f, 5.0f, "%.0f"); + + static int num_dummy_items = 25; + ImGui::SliderInt("Num Dummy Items (Demo Scrolling)", &num_dummy_items, 0, 100); + + if (ImPlot3D::BeginPlot("Legend Options Demo", ImVec2(-1, 0))) { + ImPlot3D::SetupAxes("X-Axis", "Y-Axis", "Z-Axis"); + ImPlot3D::SetupAxesLimits(-1, 1, -1, 1, -1, 1); + ImPlot3D::SetupLegend(loc, flags); + + // Generate some 3D line data + static float t = 0; + t += ImGui::GetIO().DeltaTime * 0.5f; + + constexpr int count = 50; + static float xs1[count], ys1[count], zs1[count]; + static float xs2[count], ys2[count], zs2[count]; + static float xs3[count], ys3[count], zs3[count]; + + for (int i = 0; i < count; i++) { + float phase = i * 0.1f + t; + xs1[i] = 0.8f * cosf(phase); + ys1[i] = 0.8f * sinf(phase); + zs1[i] = 0.5f * sinf(phase * 2); + + xs2[i] = 0.6f * cosf(phase + 1.0f); + ys2[i] = 0.6f * sinf(phase + 1.0f); + zs2[i] = -0.3f * cosf(phase * 1.5f); + + xs3[i] = 0.4f * sinf(phase); + ys3[i] = 0.4f * cosf(phase); + zs3[i] = 0.7f * cosf(phase * 0.8f); + } + + ImPlot3D::PlotLine("Helix A", xs1, ys1, zs1, count); + ImPlot3D::PlotLine("Helix B##IDText", xs2, ys2, zs2, count); // Text after ## used for ID only + ImPlot3D::PlotLine("##NotListed", xs3, ys3, zs3, count); // Plotted, but not added to legend + + // Add dummy items to demonstrate legend scrolling (scroll the mouse wheel over the legend) + for (int i = 0; i < num_dummy_items; ++i) { + char label[32]; + snprintf(label, sizeof(label), "Item %03d", i); + ImPlot3D::PlotDummy(label); + } + + ImPlot3D::EndPlot(); + } +} + +void DemoMarkersAndText() { + IMGUI_DEMO_MARKER("Plots/Markers and Text"); + static float mk_size = ImPlot3D::GetStyle().MarkerSize; + static float mk_weight = ImPlot3D::GetStyle().LineWeight; + ImGui::DragFloat("Marker Size", &mk_size, 0.1f, 2.0f, 10.0f, "%.2f px"); + ImGui::DragFloat("Marker Weight", &mk_weight, 0.05f, 0.5f, 3.0f, "%.2f px"); + + if (ImPlot3D::BeginPlot("##MarkerStyles", ImVec2(-1, 0), ImPlot3DFlags_CanvasOnly)) { + + ImPlot3D::SetupAxes(nullptr, nullptr, nullptr, ImPlot3DAxisFlags_NoDecorations, ImPlot3DAxisFlags_NoDecorations, + ImPlot3DAxisFlags_NoDecorations); + ImPlot3D::SetupAxesLimits(-0.5, 1.5, -0.5, 1.5, 0, ImPlot3DMarker_COUNT + 1); + + float xs[2] = {0, 0}; + float ys[2] = {0, 0}; + float zs[2] = {ImPlot3DMarker_COUNT, ImPlot3DMarker_COUNT + 1}; + + // Filled markers + for (int m = 0; m < ImPlot3DMarker_COUNT; ++m) { + xs[1] = xs[0] + ImCos(zs[0] / float(ImPlot3DMarker_COUNT) * 2 * IM_PI) * 0.5f; + ys[1] = ys[0] + ImSin(zs[0] / float(ImPlot3DMarker_COUNT) * 2 * IM_PI) * 0.5f; + + ImGui::PushID(m); + ImPlot3D::PlotLine("##Filled", xs, ys, zs, 2, + {ImPlot3DProp_Marker, m, ImPlot3DProp_MarkerSize, mk_size, ImPlot3DProp_LineWeight, mk_weight}); + ImGui::PopID(); + zs[0]--; + zs[1]--; + } + + xs[0] = 1; + ys[0] = 1; + zs[0] = ImPlot3DMarker_COUNT; + zs[1] = zs[0] + 1; + + // Open markers + for (int m = 0; m < ImPlot3DMarker_COUNT; ++m) { + xs[1] = xs[0] + ImCos(zs[0] / float(ImPlot3DMarker_COUNT) * 2 * IM_PI) * 0.5f; + ys[1] = ys[0] - ImSin(zs[0] / float(ImPlot3DMarker_COUNT) * 2 * IM_PI) * 0.5f; + + ImGui::PushID(m); + ImPlot3D::PlotLine("##Open", xs, ys, zs, 2, + {ImPlot3DProp_Marker, m, ImPlot3DProp_MarkerSize, mk_size, ImPlot3DProp_LineWeight, mk_weight, ImPlot3DProp_FillColor, + ImVec4(0, 0, 0, 0)}); + ImGui::PopID(); + zs[0]--; + zs[1]--; + } + + ImPlot3D::PlotText("Filled Markers", 0.0, 0.0, 6.0); + ImPlot3D::PlotText("Open Markers", 1.0, 1.0, 6.0); + + ImPlot3D::PushStyleColor(ImPlot3DCol_InlayText, ImVec4(1, 0, 1, 1)); + ImPlot3D::PlotText("Rotated Text", 0.5, 0.5, 6.0, IM_PI / 4, ImVec2(0, 0)); + ImPlot3D::PopStyleColor(); + + ImPlot3D::EndPlot(); + } +} + +void DemoNaNValues() { + IMGUI_DEMO_MARKER("Plots/NaN Values"); + static bool include_nan = true; + static ImPlot3DLineFlags flags = 0; + + float data1[5] = {0.0f, 0.25f, 0.5f, 0.75f, 1.0f}; + float data2[5] = {0.0f, 0.25f, 0.5f, 0.75f, 1.0f}; + float data3[5] = {0.0f, 0.25f, 0.5f, 0.75f, 1.0f}; + + if (include_nan) + data1[2] = NAN; + + ImGui::Checkbox("Include NaN", &include_nan); + ImGui::SameLine(); + ImGui::CheckboxFlags("Skip NaN", (unsigned int*)&flags, ImPlot3DLineFlags_SkipNaN); + + if (ImPlot3D::BeginPlot("##NaNValues")) { + ImPlot3D::PlotLine("Line", data1, data2, data3, 5, {ImPlot3DProp_Flags, flags, ImPlot3DProp_Marker, ImPlot3DMarker_Square}); + ImPlot3D::EndPlot(); + } +} + +void Demo_PerIndexColors() { + IMGUI_DEMO_MARKER("Plots/Per-Index Colors"); + + // Colorful Lines + static float xs1[1001], ys1[1001], zs1[1001]; + static ImU32 colors1[1001]; + for (int i = 0; i < 1001; ++i) { + xs1[i] = i * 0.001f; + ys1[i] = 0.5f + 0.5f * sinf(50 * (xs1[i] + (float)ImGui::GetTime() / 10)); + zs1[i] = 0.5f + 0.5f * cosf(50 * (xs1[i] + (float)ImGui::GetTime() / 10)); + // Rainbow colors + float hue = (float)i / 1000.0f; + colors1[i] = ImColor::HSV(hue, 0.8f, 0.9f); + } + static float xs2[20], ys2[20], zs2[20]; + static ImU32 colors2[20]; + for (int i = 0; i < 20; ++i) { + xs2[i] = i * 1 / 19.0f; + ys2[i] = xs2[i] * xs2[i]; + zs2[i] = xs2[i] * ys2[i]; + // Colormap colors (Viridis) + float t = i / 19.0f; + ImVec4 color = ImPlot3D::SampleColormap(t, ImPlot3DColormap_Viridis); + colors2[i] = ImGui::GetColorU32(color); + } + if (ImPlot3D::BeginPlot("Colorful Lines")) { + ImPlot3D::PlotLine("f(x)", xs1, ys1, zs1, 1001, {ImPlot3DProp_LineColors, colors1}); + ImPlot3D::PlotLine("g(x)", xs2, ys2, zs2, 20, + {ImPlot3DProp_Marker, ImPlot3DMarker_Circle, ImPlot3DProp_Flags, (int)ImPlot3DLineFlags_Segments, ImPlot3DProp_LineColors, + colors2, ImPlot3DProp_MarkerFillColors, colors2, ImPlot3DProp_MarkerLineColors, colors2}); + ImPlot3D::EndPlot(); + } + + // Colorful Scatter + srand(0); + static float xs_scatter1[100], ys_scatter1[100], zs_scatter1[100]; + static ImU32 colors_scatter1_fill[100], colors_scatter1_line[100]; + static float sizes_scatter1[100]; + for (int i = 0; i < 100; ++i) { + xs_scatter1[i] = i * 0.01f; + ys_scatter1[i] = xs_scatter1[i] + 0.1f * ((float)rand() / (float)RAND_MAX); + zs_scatter1[i] = xs_scatter1[i] + 0.1f * ((float)rand() / (float)RAND_MAX); + // Rainbow hue colors + float hue = i / 99.0f; + colors_scatter1_fill[i] = ImColor::HSV(hue, 0.8f, 0.9f); + colors_scatter1_line[i] = ImColor::HSV(hue, 0.9f, 0.7f); + // Random sizes between 2 and 6 + sizes_scatter1[i] = 2.0f + 4.0f * ((float)rand() / (float)RAND_MAX); + } + static float xs_scatter2[50], ys_scatter2[50], zs_scatter2[50]; + static ImU32 colors_scatter2[50]; + static float sizes_scatter2[50]; + for (int i = 0; i < 50; ++i) { + xs_scatter2[i] = 0.25f + 0.2f * ((float)rand() / (float)RAND_MAX); + ys_scatter2[i] = 0.50f + 0.2f * ((float)rand() / (float)RAND_MAX); + zs_scatter2[i] = 0.75f + 0.2f * ((float)rand() / (float)RAND_MAX); + // Colormap colors (Viridis) + float t = i / 49.0f; + ImVec4 color = ImPlot3D::SampleColormap(t, ImPlot3DColormap_Viridis); + colors_scatter2[i] = ImGui::GetColorU32(color); + // Random sizes between 2 and 6 + sizes_scatter2[i] = 2.0f + 4.0f * ((float)rand() / (float)RAND_MAX); + } + + if (ImPlot3D::BeginPlot("Colorful Scatter")) { + ImPlot3D::PlotScatter("Data 1", xs_scatter1, ys_scatter1, zs_scatter1, 100, + {ImPlot3DProp_MarkerFillColors, colors_scatter1_fill, ImPlot3DProp_MarkerLineColors, colors_scatter1_line, + ImPlot3DProp_MarkerSizes, sizes_scatter1}); + ImPlot3D::PlotScatter("Data 2", xs_scatter2, ys_scatter2, zs_scatter2, 50, + {ImPlot3DProp_Marker, ImPlot3DMarker_Square, ImPlot3DProp_MarkerFillColors, colors_scatter2, + ImPlot3DProp_MarkerLineColors, colors_scatter2, ImPlot3DProp_MarkerSizes, sizes_scatter2, ImPlot3DProp_FillAlpha, + 0.5f}); + ImPlot3D::EndPlot(); + } + + // Colorful Triangles (pyramid with per-vertex fill colors) + static float xs_tri[18], ys_tri[18], zs_tri[18]; + static ImU32 colors_tri[18]; + { + // Apex + float ax = 0.0f, ay = 0.0f, az = 1.0f; + // Square base corners + float cx[4] = {-0.5f, 0.5f, 0.5f, -0.5f}; + float cy[4] = {-0.5f, -0.5f, 0.5f, 0.5f}; + float cz[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + int v = 0; + auto AddVertex = [&](float x, float y, float z) { + xs_tri[v] = x; + ys_tri[v] = y; + zs_tri[v] = z; + v++; + }; + AddVertex(ax, ay, az); + AddVertex(cx[0], cy[0], cz[0]); + AddVertex(cx[1], cy[1], cz[1]); + AddVertex(ax, ay, az); + AddVertex(cx[1], cy[1], cz[1]); + AddVertex(cx[2], cy[2], cz[2]); + AddVertex(ax, ay, az); + AddVertex(cx[2], cy[2], cz[2]); + AddVertex(cx[3], cy[3], cz[3]); + AddVertex(ax, ay, az); + AddVertex(cx[3], cy[3], cz[3]); + AddVertex(cx[0], cy[0], cz[0]); + AddVertex(cx[0], cy[0], cz[0]); + AddVertex(cx[1], cy[1], cz[1]); + AddVertex(cx[2], cy[2], cz[2]); + AddVertex(cx[0], cy[0], cz[0]); + AddVertex(cx[2], cy[2], cz[2]); + AddVertex(cx[3], cy[3], cz[3]); + // Hot colormap sampled by z: bottom (z=0) is cold, apex (z=1) is hot + for (int i = 0; i < 18; ++i) { + ImVec4 color = ImPlot3D::SampleColormap(0.5f * zs_tri[i], ImPlot3DColormap_Hot); + colors_tri[i] = ImGui::GetColorU32(color); + } + } + if (ImPlot3D::BeginPlot("Colorful Triangles")) { + ImPlot3D::SetupAxesLimits(-1, 1, -1, 1, -0.5, 1.5); + ImPlot3D::PlotTriangle("Pyramid", xs_tri, ys_tri, zs_tri, 18, {ImPlot3DProp_FillColors, colors_tri, ImPlot3DProp_FillAlpha, 0.8f}); + ImPlot3D::EndPlot(); + } + + // Colorful Quads (cube [0,1]^3 with per-vertex RGB colors: R=x, G=y, B=z) + static float xs_quad[24], ys_quad[24], zs_quad[24]; + static ImU32 colors_quad[24]; + { + // clang-format off + xs_quad[0]=1; ys_quad[0]=0; zs_quad[0]=0; xs_quad[1]=1; ys_quad[1]=1; zs_quad[1]=0; xs_quad[2]=1; ys_quad[2]=1; zs_quad[2]=1; xs_quad[3]=1; ys_quad[3]=0; zs_quad[3]=1; + xs_quad[4]=0; ys_quad[4]=0; zs_quad[4]=0; xs_quad[5]=0; ys_quad[5]=1; zs_quad[5]=0; xs_quad[6]=0; ys_quad[6]=1; zs_quad[6]=1; xs_quad[7]=0; ys_quad[7]=0; zs_quad[7]=1; + xs_quad[8]=0; ys_quad[8]=1; zs_quad[8]=0; xs_quad[9]=1; ys_quad[9]=1; zs_quad[9]=0; xs_quad[10]=1; ys_quad[10]=1; zs_quad[10]=1; xs_quad[11]=0; ys_quad[11]=1; zs_quad[11]=1; + xs_quad[12]=0; ys_quad[12]=0; zs_quad[12]=0; xs_quad[13]=1; ys_quad[13]=0; zs_quad[13]=0; xs_quad[14]=1; ys_quad[14]=0; zs_quad[14]=1; xs_quad[15]=0; ys_quad[15]=0; zs_quad[15]=1; + xs_quad[16]=0; ys_quad[16]=0; zs_quad[16]=1; xs_quad[17]=1; ys_quad[17]=0; zs_quad[17]=1; xs_quad[18]=1; ys_quad[18]=1; zs_quad[18]=1; xs_quad[19]=0; ys_quad[19]=1; zs_quad[19]=1; + xs_quad[20]=0; ys_quad[20]=0; zs_quad[20]=0; xs_quad[21]=1; ys_quad[21]=0; zs_quad[21]=0; xs_quad[22]=1; ys_quad[22]=1; zs_quad[22]=0; xs_quad[23]=0; ys_quad[23]=1; zs_quad[23]=0; + // clang-format on + // Color = (R=x, G=y, B=z) per vertex + for (int i = 0; i < 24; ++i) + colors_quad[i] = IM_COL32((ImU8)(xs_quad[i] * 255), (ImU8)(ys_quad[i] * 255), (ImU8)(zs_quad[i] * 255), 255); + } + if (ImPlot3D::BeginPlot("Colorful Quads")) { + ImPlot3D::SetupAxesLimits(-0.5, 1.5, -0.5, 1.5, -0.5, 1.5); + ImPlot3D::PlotQuad("Cube", xs_quad, ys_quad, zs_quad, 24, {ImPlot3DProp_FillColors, colors_quad, ImPlot3DProp_FillAlpha, 0.8f}); + ImPlot3D::EndPlot(); + } + + // Gouraud-shaded Duck (yellow duck lit by a point light with ambient) + // Per-vertex normals are computed once, then mapped to index-buffer slots so the GPU + // interpolates colors across each triangle (Gouraud shading). + static ImU32 duck_fill_colors[DUCK_IDX_COUNT]; + static bool duck_colors_built = false; + if (!duck_colors_built) { + // Accumulate area-weighted face normals into each vertex + struct Vec3 { + float x, y, z; + }; + auto sub3 = [](Vec3 a, Vec3 b) -> Vec3 { return {a.x - b.x, a.y - b.y, a.z - b.z}; }; + auto add3 = [](Vec3 a, Vec3 b) -> Vec3 { return {a.x + b.x, a.y + b.y, a.z + b.z}; }; + auto cross3 = [](Vec3 a, Vec3 b) -> Vec3 { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }; + auto dot3 = [](Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }; + auto norm3 = [&dot3](Vec3 a) -> Vec3 { + float len = sqrtf(dot3(a, a)); + return len > 1e-8f ? Vec3{a.x / len, a.y / len, a.z / len} : Vec3{0, 0, 1}; + }; + + Vec3 vtx_normals[DUCK_VTX_COUNT] = {}; + for (int i = 0; i < DUCK_IDX_COUNT; i += 3) { + unsigned int i0 = duck_idx[i], i1 = duck_idx[i + 1], i2 = duck_idx[i + 2]; + Vec3 p0 = {(float)duck_vtx[i0].x, (float)duck_vtx[i0].y, (float)duck_vtx[i0].z}; + Vec3 p1 = {(float)duck_vtx[i1].x, (float)duck_vtx[i1].y, (float)duck_vtx[i1].z}; + Vec3 p2 = {(float)duck_vtx[i2].x, (float)duck_vtx[i2].y, (float)duck_vtx[i2].z}; + Vec3 fn = cross3(sub3(p1, p0), sub3(p2, p0)); // area-weighted face normal + vtx_normals[i0] = add3(vtx_normals[i0], fn); + vtx_normals[i1] = add3(vtx_normals[i1], fn); + vtx_normals[i2] = add3(vtx_normals[i2], fn); + } + for (int v = 0; v < DUCK_VTX_COUNT; v++) + vtx_normals[v] = norm3(vtx_normals[v]); + + // Lighting: yellow duck, warm point light, soft ambient + Vec3 light_pos = {2.0f, 2.0f, 3.0f}; + Vec3 duck_col = {1.0f, 0.85f, 0.1f}; // yellow + Vec3 light_col = {1.0f, 0.95f, 0.8f}; // warm white + Vec3 ambient = {0.15f, 0.12f, 0.03f}; // dim warm ambient + + ImU32 vtx_colors[DUCK_VTX_COUNT]; + for (int v = 0; v < DUCK_VTX_COUNT; v++) { + Vec3 pos = {(float)duck_vtx[v].x, (float)duck_vtx[v].y, (float)duck_vtx[v].z}; + Vec3 to_light = norm3(sub3(light_pos, pos)); + float diff = ImMax(0.0f, dot3(vtx_normals[v], to_light)); + float r = ImMin(1.0f, ambient.x + duck_col.x * light_col.x * diff); + float g = ImMin(1.0f, ambient.y + duck_col.y * light_col.y * diff); + float b = ImMin(1.0f, ambient.z + duck_col.z * light_col.z * diff); + vtx_colors[v] = IM_COL32((ImU8)(r * 255), (ImU8)(g * 255), (ImU8)(b * 255), 255); + } + + // Map per-vertex colors to index-buffer slots for Gouraud interpolation + for (int i = 0; i < DUCK_IDX_COUNT; i++) + duck_fill_colors[i] = vtx_colors[duck_idx[i]]; + + duck_colors_built = true; + } + if (ImPlot3D::BeginPlot("Gouraud Duck")) { + ImPlot3D::SetupAxesLimits(-1, 1, -1, 1, -1, 1); + ImPlot3D::PlotMesh("Duck", &duck_vtx[0].x, &duck_vtx[0].y, &duck_vtx[0].z, duck_idx, DUCK_VTX_COUNT, DUCK_IDX_COUNT, + {ImPlot3DProp_Stride, (int)sizeof(ImPlot3DPoint), ImPlot3DProp_FillColors, duck_fill_colors, ImPlot3DProp_Flags, + (int)ImPlot3DMeshFlags_NoLines}); + ImPlot3D::EndPlot(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Axes +//----------------------------------------------------------------------------- + +void DemoBoxScale() { + IMGUI_DEMO_MARKER("Axes/Box Scale"); + constexpr int N = 100; + float xs[N], ys[N], zs[N]; + for (int i = 0; i < N; i++) { + float t = i / (float)(N - 1); + xs[i] = sinf(t * 2.0f * IM_PI); + ys[i] = cosf(t * 4.0f * IM_PI); + zs[i] = t * 2.0f - 1.0f; + } + + static float scale[3] = {1.0f, 1.0f, 1.0f}; + ImGui::SliderFloat3("Box Scale", scale, 0.1f, 2.0f, "%.2f"); + + if (ImPlot3D::BeginPlot("##BoxScale")) { + ImPlot3D::SetupBoxScale(scale[0], scale[1], scale[2]); + ImPlot3D::PlotLine("3D Curve", xs, ys, zs, N); + ImPlot3D::EndPlot(); + } +} + +void DemoBoxRotation() { + IMGUI_DEMO_MARKER("Axes/Box Rotation"); + double origin[2] = {0.0, 0.0}; + double axis[2] = {0.0, 1.0}; + + // Sliders for rotation angles + static float elevation = 45.0f; + static float azimuth = -135.0f; + static bool animate = false; + ImGui::Text("Rotation"); + bool changed = false; + if (ImGui::SliderFloat("Elevation", &elevation, -90.0f, 90.0f, "%.1f degrees")) + changed = true; + if (ImGui::SliderFloat("Azimuth", &azimuth, -180.0f, 180.0f, "%.1f degrees")) + changed = true; + ImGui::Checkbox("Animate", &animate); + + ImGui::Text("Initial Rotation"); + ImGui::SameLine(); + HelpMarker("The rotation will be reset to the initial rotation when you double right-click"); + static float init_elevation = 45.0f; + static float init_azimuth = -135.0f; + ImGui::SliderFloat("Initial Elevation", &init_elevation, -90.0f, 90.0f, "%.1f degrees"); + ImGui::SliderFloat("Initial Azimuth", &init_azimuth, -180.0f, 180.0f, "%.1f degrees"); + + if (ImPlot3D::BeginPlot("##BoxRotation")) { + ImPlot3D::SetupAxesLimits(-1, 1, -1, 1, -1, 1, ImPlot3DCond_Always); + + // Set initial rotation + ImPlot3D::SetupBoxInitialRotation(init_elevation, init_azimuth); + + // Set the rotation using the specified elevation and azimuth + if (changed) + ImPlot3D::SetupBoxRotation(elevation, azimuth, animate, ImPlot3DCond_Always); + + // Plot axis lines + ImPlot3D::PlotLine("X-Axis", axis, origin, origin, 2, {ImPlot3DProp_LineColor, ImVec4(0.8f, 0.2f, 0.2f, 1)}); + ImPlot3D::PlotLine("Y-Axis", origin, axis, origin, 2, {ImPlot3DProp_LineColor, ImVec4(0.2f, 0.8f, 0.2f, 1)}); + ImPlot3D::PlotLine("Z-Axis", origin, origin, axis, 2, {ImPlot3DProp_LineColor, ImVec4(0.2f, 0.2f, 0.8f, 1)}); + + ImPlot3D::EndPlot(); + } +} + +void Demo_LogScale() { + IMGUI_DEMO_MARKER("Axes/Log Scale"); + static double xs[1001], ys1[1001], ys2[1001], ys3[1001], zs[1001]; + for (int i = 0; i < 1001; i++) { + xs[i] = i * 0.1; + ys1[i] = sin(xs[i]) + 1; + ys2[i] = log(xs[i]); + ys3[i] = pow(10.0, xs[i]); + zs[i] = 0.0; + } + + if (ImPlot3D::BeginPlot("Log Plot 3D", ImVec2(-1, 0))) { + ImPlot3D::SetupAxisScale(ImAxis3D_X, ImPlot3DScale_Log10); + ImPlot3D::SetupAxesLimits(0.1, 100, 0, 10, -1, 1); + ImPlot3D::PlotLine("f(x) = x", xs, xs, zs, 1001); + ImPlot3D::PlotLine("f(x) = sin(x)+1", xs, ys1, zs, 1001); + ImPlot3D::PlotLine("f(x) = log(x)", xs, ys2, zs, 1001); + ImPlot3D::PlotLine("f(x) = 10^x", xs, ys3, zs, 21); + ImPlot3D::EndPlot(); + } +} + +void Demo_SymmetricLogScale() { + IMGUI_DEMO_MARKER("Axes/Symmetric Log Scale"); + static double xs[1001], ys1[1001], ys2[1001], zs[1001]; + for (int i = 0; i < 1001; i++) { + xs[i] = i * 0.1f - 50; + ys1[i] = sin(xs[i]); + ys2[i] = i * 0.002 - 1; + zs[i] = 0.0; + } + if (ImPlot3D::BeginPlot("SymLog Plot", ImVec2(-1, 0))) { + ImPlot3D::SetupAxisScale(ImAxis3D_X, ImPlot3DScale_SymLog); + ImPlot3D::PlotLine("f(x) = a*x+b", xs, ys2, zs, 1001); + ImPlot3D::PlotLine("f(x) = sin(x)", xs, ys1, zs, 1001); + ImPlot3D::EndPlot(); + } +} + +void DemoTickLabels() { + IMGUI_DEMO_MARKER("Axes/Tick Labels"); + static bool custom_fmt = true; + static bool custom_ticks = false; + static bool custom_labels = true; + ImGui::Checkbox("Show Custom Format", &custom_fmt); + ImGui::SameLine(); + ImGui::Checkbox("Show Custom Ticks", &custom_ticks); + if (custom_ticks) { + ImGui::SameLine(); + ImGui::Checkbox("Show Custom Labels", &custom_labels); + } + const double pi = 3.14; + const char* pi_str[] = {"PI"}; + static double letters_ticks[] = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0}; + static const char* letters_labels[] = {"A", "B", "C", "D", "E", "F"}; + if (ImPlot3D::BeginPlot("##Ticks")) { + ImPlot3D::SetupAxesLimits(2, 5, 0, 1, 0, 1000); + if (custom_fmt) { + ImPlot3D::SetupAxisFormat(ImAxis3D_Y, MetricFormatter, (void*)"Hz"); + ImPlot3D::SetupAxisFormat(ImAxis3D_Z, MetricFormatter, (void*)"m"); + } + if (custom_ticks) { + ImPlot3D::SetupAxisTicks(ImAxis3D_X, &pi, 1, custom_labels ? pi_str : nullptr, true); + ImPlot3D::SetupAxisTicks(ImAxis3D_Y, letters_ticks, 6, custom_labels ? letters_labels : nullptr, false); + ImPlot3D::SetupAxisTicks(ImAxis3D_Z, 0, 1000, 6, custom_labels ? letters_labels : nullptr, false); + } + ImPlot3D::EndPlot(); + } +} + +void DemoAxisConstraints() { + IMGUI_DEMO_MARKER("Axes/Axis Constraints"); + static float limit_constraints[2] = {-10, 10}; + static float zoom_constraints[2] = {1, 20}; + static ImPlot3DAxisFlags flags; + ImGui::DragFloat2("Limits Constraints", limit_constraints, 0.01f); + ImGui::DragFloat2("Zoom Constraints", zoom_constraints, 0.01f); + CHECKBOX_FLAG(flags, ImPlot3DAxisFlags_PanStretch); + if (ImPlot3D::BeginPlot("##AxisConstraints", ImVec2(-1, 0))) { + ImPlot3D::SetupAxes("X", "Y", "Z", flags, flags, flags); + ImPlot3D::SetupAxesLimits(-1, 1, -1, 1, -1, 1); + ImPlot3D::SetupAxisLimitsConstraints(ImAxis3D_X, (double)limit_constraints[0], (double)limit_constraints[1]); + ImPlot3D::SetupAxisLimitsConstraints(ImAxis3D_Y, (double)limit_constraints[0], (double)limit_constraints[1]); + ImPlot3D::SetupAxisLimitsConstraints(ImAxis3D_Z, (double)limit_constraints[0], (double)limit_constraints[1]); + ImPlot3D::SetupAxisZoomConstraints(ImAxis3D_X, (double)zoom_constraints[0], (double)zoom_constraints[1]); + ImPlot3D::SetupAxisZoomConstraints(ImAxis3D_Y, (double)zoom_constraints[0], (double)zoom_constraints[1]); + ImPlot3D::SetupAxisZoomConstraints(ImAxis3D_Z, (double)zoom_constraints[0], (double)zoom_constraints[1]); + ImPlot3D::EndPlot(); + } +} + +void DemoEqualAxes() { + IMGUI_DEMO_MARKER("Axes/Equal Axes"); + ImGui::BulletText("Equal constraint applies to all three axes (X, Y, Z)"); + ImGui::BulletText("When enabled, the axes maintain the same units/pixel ratio"); + + static double circle_xs[360], circle_ys[360], circle_zs[360]; + static double helix_xs[360], helix_ys[360], helix_zs[360]; + float square_xs[] = {-0.5f, 0.5f, 0.5f, -0.5f, -0.5f}; + float square_ys[] = {-0.5f, -0.5f, 0.5f, 0.5f, -0.5f}; + float square_zs[] = {-0.5f, -0.5f, -0.5f, -0.5f, -0.5f}; + static bool initialized = false; + if (!initialized) { + for (int i = 0; i < 360; ++i) { + double angle = i * 2 * IM_PI / 359.0; + // Circle in XY plane at Z=0 + circle_xs[i] = cos(angle); + circle_ys[i] = sin(angle); + circle_zs[i] = 0; + // Helix + helix_xs[i] = 0.5 * cos(angle); + helix_ys[i] = 0.5 * sin(angle); + helix_zs[i] = (double)i / 359.0 * 2.0 - 1.0; + } + initialized = true; + } + + static ImPlot3DFlags flags = ImPlot3DFlags_Equal; + CHECKBOX_FLAG(flags, ImPlot3DFlags_Equal); + + if (ImPlot3D::BeginPlot("##EqualAxes", ImVec2(-1, 0), flags)) { + ImPlot3D::SetupAxes("X-Axis", "Y-Axis", "Z-Axis"); + ImPlot3D::PlotLine("Circle", circle_xs, circle_ys, circle_zs, 360); + ImPlot3D::PlotLine("Helix", helix_xs, helix_ys, helix_zs, 360); + ImPlot3D::PlotLine("Square", square_xs, square_ys, square_zs, 5); + ImPlot3D::EndPlot(); + } +} + +void DemoAutoFittingData() { + IMGUI_DEMO_MARKER("Axes/Auto-Fitting Data"); + ImGui::BulletText("Axes can be configured to auto-fit to data extents."); + ImGui::BulletText("Try panning and zooming to see the axes adjust."); + ImGui::BulletText("Disable AutoFit on an axis to fix its range."); + + static ImPlot3DAxisFlags xflags = ImPlot3DAxisFlags_None; + static ImPlot3DAxisFlags yflags = ImPlot3DAxisFlags_None; + static ImPlot3DAxisFlags zflags = ImPlot3DAxisFlags_AutoFit; + + ImGui::TextUnformatted("X: "); + ImGui::SameLine(); + ImGui::CheckboxFlags("ImPlot3DAxisFlags_AutoFit##X", (unsigned int*)&xflags, ImPlot3DAxisFlags_AutoFit); + + ImGui::TextUnformatted("Y: "); + ImGui::SameLine(); + ImGui::CheckboxFlags("ImPlot3DAxisFlags_AutoFit##Y", (unsigned int*)&yflags, ImPlot3DAxisFlags_AutoFit); + + ImGui::TextUnformatted("Z: "); + ImGui::SameLine(); + ImGui::CheckboxFlags("ImPlot3DAxisFlags_AutoFit##Z", (unsigned int*)&zflags, ImPlot3DAxisFlags_AutoFit); + + static double data_x[101], data_y[101], data_z[101]; + static bool initialized = false; + if (!initialized) { + srand(0); + for (int i = 0; i < 101; ++i) { + data_x[i] = i * 0.1; + data_y[i] = i * 0.1; + data_z[i] = 1 + sin(i / 10.0); + } + initialized = true; + } + + if (ImPlot3D::BeginPlot("##AutoFitting")) { + ImPlot3D::SetupAxes("X-Axis", "Y-Axis", "Z-Axis", xflags, yflags, zflags); + ImPlot3D::PlotLine("Wave", data_x, data_y, data_z, 101); + ImPlot3D::EndPlot(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Tools +//----------------------------------------------------------------------------- + +void DemoMousePicking() { + IMGUI_DEMO_MARKER("Tools/Mouse Picking"); + static ImVector points; + static ImVector rays; + + ImGui::BulletText("Click anywhere in the plot to place points/rays."); + + static int selected_plane = ImPlane3D_XY; + ImGui::RadioButton("XY-Plane", &selected_plane, ImPlane3D_XY); + ImGui::SameLine(); + ImGui::RadioButton("XZ-Plane", &selected_plane, ImPlane3D_XZ); + ImGui::SameLine(); + ImGui::RadioButton("YZ-Plane", &selected_plane, ImPlane3D_YZ); + + static bool mask_plane = true; + ImGui::Checkbox("Mask Plane", &mask_plane); + if (ImGui::Button("Clear")) { + points.clear(); + rays.clear(); + } + + if (ImPlot3D::BeginPlot("Mouse Picking", ImVec2(-1, 0), ImPlot3DFlags_NoClip)) { + ImPlot3D::SetupAxes("X-Axis", "Y-Axis", "Z-Axis"); + ImPlot3D::SetupAxesLimits(-1, 1, -1, 1, -1, 1); + + // Get mouse position and convert to ray + ImVec2 mouse_pos = ImGui::GetMousePos(); + ImPlot3DRay ray = ImPlot3D::PixelsToPlotRay(mouse_pos); + + // Convert to selected plane + ImPlane3D plane = (ImPlane3D)selected_plane; + ImPlot3DPoint point = ImPlot3D::PixelsToPlotPlane(mouse_pos, plane, mask_plane); + + // Show intersection point + if (ImGui::IsItemHovered() && !point.IsNaN()) { + ImPlot3DSpec spec; + spec.Marker = ImPlot3DMarker_Circle; + spec.MarkerSize = 5; + spec.FillColor = ImVec4(1, 1, 0, 1); + ImPlot3D::PlotScatter("##Intersection", &point.x, &point.y, &point.z, 1, spec); + } + + // Add point/ray on click + if (ImGui::IsItemHovered() && ImGui::IsMouseClicked(0) && !point.IsNaN()) { + points.push_back(point); + rays.push_back(ray); + } + + // Draw all placed points + if (!points.empty()) { + // Plot points + ImPlot3DSpec spec; + spec.Marker = ImPlot3DMarker_Circle; + spec.MarkerSize = 3; + spec.Stride = sizeof(ImPlot3DPoint); + ImPlot3D::PlotScatter("Placed Points", &points[0].x, &points[0].y, &points[0].z, (int)points.Size, spec); + } + + // Draw all placed rays + if (!rays.empty()) { + ImVector ray_points; + ray_points.reserve(rays.Size * 2); + for (int i = 0; i < rays.Size; i++) { + ImPlot3DPoint p1 = points[i]; + ImPlot3DPoint p2 = points[i] - rays[i].Direction; // Ray from added point to the camera + ray_points.push_back(p1); + ray_points.push_back(p2); + } + ImPlot3DSpec spec; + spec.Flags = ImPlot3DLineFlags_Segments; + spec.Offset = 0; + spec.Stride = sizeof(ImPlot3DPoint); + ImPlot3D::PlotLine("Placed Rays", &ray_points[0].x, &ray_points[0].y, &ray_points[0].z, (int)rays.Size * 2, spec); + } + + ImPlot3D::EndPlot(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Custom +//----------------------------------------------------------------------------- + +void DemoCustomStyles() { + IMGUI_DEMO_MARKER("Custom/Custom Styles"); + ImPlot3D::PushColormap(ImPlot3DColormap_Deep); + // normally you wouldn't change the entire style each frame + ImPlot3DStyle backup = ImPlot3D::GetStyle(); + MyImPlot3D::StyleSeaborn(); + if (ImPlot3D::BeginPlot("Seaborn Style")) { + ImPlot3D::SetupAxes("X-axis", "Y-axis", "Z-axis"); + ImPlot3D::SetupAxesLimits(-0.5, 9.5, -0.5, 0.5, 0, 10); + unsigned int xs[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + unsigned int ys[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + unsigned int lin[10] = {8, 8, 9, 7, 8, 8, 8, 9, 7, 8}; + unsigned int dot[10] = {7, 6, 6, 7, 8, 5, 6, 5, 8, 7}; + ImPlot3D::NextColormapColor(); // Skip blue + ImPlot3D::PlotLine("Line", xs, ys, lin, 10); + ImPlot3D::NextColormapColor(); // Skip green + ImPlot3D::PlotScatter("Scatter", xs, ys, dot, 10); + ImPlot3D::EndPlot(); + } + ImPlot3D::GetStyle() = backup; + ImPlot3D::PopColormap(); +} + +void DemoCustomRendering() { + IMGUI_DEMO_MARKER("Custom/Custom Rendering"); + if (ImPlot3D::BeginPlot("##CustomRend")) { + ImPlot3D::SetupAxesLimits(-0.1, 1.1, -0.1, 1.1, -0.1, 1.1); + + // Draw circle + ImVec2 cntr = ImPlot3D::PlotToPixels(ImPlot3DPoint(0.5, 0.5, 0.5)); + ImPlot3D::GetPlotDrawList()->AddCircleFilled(cntr, 20, IM_COL32(255, 255, 0, 255), 20); + + // Draw box + ImPlot3DPoint corners[8] = { + ImPlot3DPoint(0, 0, 0), ImPlot3DPoint(1, 0, 0), ImPlot3DPoint(1, 1, 0), ImPlot3DPoint(0, 1, 0), + ImPlot3DPoint(0, 0, 1), ImPlot3DPoint(1, 0, 1), ImPlot3DPoint(1, 1, 1), ImPlot3DPoint(0, 1, 1), + }; + ImVec2 corners_px[8]; + for (int i = 0; i < 8; i++) + corners_px[i] = ImPlot3D::PlotToPixels(corners[i]); + + ImU32 col = IM_COL32(128, 0, 255, 255); + for (int i = 0; i < 4; i++) { + ImPlot3D::GetPlotDrawList()->AddLine(corners_px[i], corners_px[(i + 1) % 4], col); + ImPlot3D::GetPlotDrawList()->AddLine(corners_px[i + 4], corners_px[(i + 1) % 4 + 4], col); + ImPlot3D::GetPlotDrawList()->AddLine(corners_px[i], corners_px[i + 4], col); + } + ImPlot3D::EndPlot(); + } +} + +void DemoCustomOverlay() { + IMGUI_DEMO_MARKER("Custom/Custom Overlay"); + ImGui::BulletText("Demonstrates custom 2D overlays using GetPlotRectPos/GetPlotRectSize."); + ImGui::BulletText("Shows mouse tooltip, line to closest point, and orientation gizmo."); + + // Generate some 3D scatter data + static float xs[50], ys[50], zs[50]; + static bool initialized = false; + if (!initialized) { + srand(0); + for (int i = 0; i < 50; i++) { + xs[i] = (float)rand() / (float)RAND_MAX; + ys[i] = (float)rand() / (float)RAND_MAX; + zs[i] = (float)rand() / (float)RAND_MAX; + } + initialized = true; + } + + if (ImPlot3D::BeginPlot("##CustomOverlay", ImVec2(-1, 0))) { + ImPlot3D::SetupAxes("X-Axis", "Y-Axis", "Z-Axis"); + ImPlot3D::SetupAxesLimits(0, 1, 0, 1, 0, 1); + ImPlot3D::PlotScatter("Data", xs, ys, zs, 50); + + ImDrawList* draw_list = ImPlot3D::GetPlotDrawList(); + ImVec2 mouse_pos = ImGui::GetMousePos(); + ImVec2 plot_pos = ImPlot3D::GetPlotRectPos(); + ImVec2 plot_size = ImPlot3D::GetPlotRectSize(); + + // Check if mouse is over plot + bool is_hovered = ImGui::IsItemHovered(); + + if (is_hovered) { + // Find closest point to mouse in screen space + int closest_idx = -1; + float min_dist_sq = 1e10f; // Large value instead of FLT_MAX + ImVec2 closest_px; + + for (int i = 0; i < 50; i++) { + ImVec2 point_px = ImPlot3D::PlotToPixels(xs[i], ys[i], zs[i]); + float dx = point_px.x - mouse_pos.x; + float dy = point_px.y - mouse_pos.y; + float dist_sq = dx * dx + dy * dy; + if (dist_sq < min_dist_sq) { + min_dist_sq = dist_sq; + closest_idx = i; + closest_px = point_px; + } + } + + // Draw line to closest point + if (closest_idx >= 0) { + draw_list->AddLine(mouse_pos, closest_px, IM_COL32(255, 255, 0, 255), 2.0f); + + // Draw tooltip + ImGui::BeginTooltip(); + ImGui::Text("Mouse: (%.1f, %.1f)", mouse_pos.x, mouse_pos.y); + ImGui::Text("Closest Point #%d", closest_idx); + ImGui::Text("Position: (%.3f, %.3f, %.3f)", xs[closest_idx], ys[closest_idx], zs[closest_idx]); + ImGui::Text("Distance: %.1f px", ImSqrt(min_dist_sq)); + ImGui::EndTooltip(); + } + } + + // Draw orientation gizmo in bottom-right corner + ImPlot3DContext& gp = *GImPlot3D; + ImPlot3DPlot* plot = gp.CurrentPlot; + if (plot) { + ImVec2 gizmo_center = ImVec2(plot_pos.x + plot_size.x - 50, plot_pos.y + plot_size.y - 50); + float gizmo_size = 30.0f; + + // Get rotation quaternion + ImPlot3DQuat rot = plot->Rotation; + + // Define axis directions in plot space + ImPlot3DPoint axes[3] = { + ImPlot3DPoint(1, 0, 0), // X-axis (red) + ImPlot3DPoint(0, 1, 0), // Y-axis (green) + ImPlot3DPoint(0, 0, 1) // Z-axis (blue) + }; + + ImU32 colors[3] = { + IM_COL32(200, 50, 50, 255), // Red + IM_COL32(50, 200, 50, 255), // Green + IM_COL32(50, 50, 200, 255) // Blue + }; + + const char* labels[3] = {"X", "Y", "Z"}; + + // Draw gizmo background circle + draw_list->AddCircleFilled(gizmo_center, gizmo_size + 5, IM_COL32(0, 0, 0, 100)); + + // Draw each axis + for (int i = 0; i < 3; i++) { + // Rotate axis by quaternion + ImPlot3DPoint rotated = rot * axes[i]; + + // Project to 2D gizmo space (simple orthographic projection) + ImVec2 axis_end = ImVec2(gizmo_center.x + float(rotated.x) * gizmo_size, + gizmo_center.y - float(rotated.y) * gizmo_size // Flip Y for screen coords + ); + + // Draw line + draw_list->AddLine(gizmo_center, axis_end, colors[i], 2.0f); + + // Draw circle at end + draw_list->AddCircleFilled(axis_end, 4.0f, colors[i]); + + // Draw label + ImVec2 label_pos = ImVec2(axis_end.x + 8, axis_end.y - 8); + draw_list->AddText(label_pos, colors[i], labels[i]); + } + } + + ImPlot3D::EndPlot(); + } +} + +void DemoCustomPerPointStyle() { + IMGUI_DEMO_MARKER("Custom/Custom Per-Point Style"); + ImGui::BulletText("Demonstrates per-point coloring using colormap sampling."); + ImGui::BulletText("A different color is sampled for each point."); + ImGui::BulletText("All points share the same label for a single legend entry."); + + static float marker_size = 4.0f; + static ImPlot3DColormap cmap = ImPlot3DColormap_Viridis; + + ImGui::SliderFloat("Marker Size", &marker_size, 2.0f, 10.0f); + if (ImGui::BeginCombo("Colormap", ImPlot3D::GetColormapName(cmap))) { + ImPlot3DContext& gp = *GImPlot3D; + for (int i = 0; i < ImPlot3D::GetColormapCount(); i++) { + // Only show continuous colormaps + if (!gp.ColormapData.IsQual(i)) { + if (ImGui::Selectable(ImPlot3D::GetColormapName(i), cmap == i)) + cmap = i; + } + } + ImGui::EndCombo(); + } + + // Generate three stacked toruses with different color patterns + static float torus_data[3][400][4]; // 3 toruses, 400 points each, XYZT per point + static bool initialized = false; + if (!initialized) { + const float R = 0.6f; // Major radius + const float r = 0.2f; // Minor radius + const int u_samples = 20; + const int v_samples = 20; + + for (int torus = 0; torus < 3; torus++) { + float z_offset = (2 - torus) * 0.6f; + int idx = 0; + + for (int i = 0; i < u_samples; i++) { + float u = (float)i / u_samples * 2.0f * IM_PI; + for (int j = 0; j < v_samples; j++) { + float v = (float)j / v_samples * 2.0f * IM_PI; + + // Parametric torus equations + float x = (R + r * ImCos(v)) * ImCos(u); + float y = (R + r * ImCos(v)) * ImSin(u); + float z = r * ImSin(v) + z_offset; + + // Different color pattern for each torus + float t; + if (torus == 0) { + // Color by height (Z coordinate) + // Normalize Z to [0, 1] range for this torus + t = (z - (z_offset - r)) / (2.0f * r); + } else if (torus == 1) { + // Color by radial distance from tube center + // V parameter directly gives us position around tube + // Map from [-r, +r] to [0, 1] + t = (ImCos(v) + 1.0f) / 2.0f; + } else { + // Angular pattern: varies smoothly around the major circle + // Creates wave-like color pattern + t = (ImCos(u) + 1.0f) / 2.0f; // Maps [-1, 1] to [0, 1] + } + + torus_data[torus][idx][0] = x; + torus_data[torus][idx][1] = y; + torus_data[torus][idx][2] = z; + torus_data[torus][idx][3] = t; + idx++; + } + } + } + initialized = true; + } + + // Precompute per-point colors and flat XYZ arrays for each torus + static float xs[3][400], ys[3][400], zs[3][400]; + ImU32 point_colors[3][400]; + for (int torus = 0; torus < 3; torus++) { + for (int i = 0; i < 400; i++) { + xs[torus][i] = torus_data[torus][i][0]; + ys[torus][i] = torus_data[torus][i][1]; + zs[torus][i] = torus_data[torus][i][2]; + point_colors[torus][i] = ImGui::ColorConvertFloat4ToU32(ImPlot3D::SampleColormap(torus_data[torus][i][3], cmap)); + } + } + + if (ImPlot3D::BeginPlot("##PerPointStyle", ImVec2(-1, 0))) { + ImPlot3D::SetupAxes("X", "Y", "Z"); + ImPlot3D::SetupAxesLimits(-1, 1, -1, 1, -0.5, 1.5); + + const char* labels[3] = {"Height-colored", "Radial-colored", "Angular-colored"}; + const ImVec4 legend_colors[3] = { + ImVec4(1.0f, 0.0f, 0.0f, 1.0f), // Red + ImVec4(0.0f, 1.0f, 0.0f, 1.0f), // Green + ImVec4(0.0f, 0.0f, 1.0f, 1.0f) // Blue + }; + + ImPlot3DSpec spec; + spec.Marker = ImPlot3DMarker_Circle; + spec.MarkerSize = marker_size; + + for (int torus = 0; torus < 3; torus++) { + spec.MarkerFillColors = point_colors[torus]; + spec.MarkerLineColors = point_colors[torus]; + ImPlot3D::PlotScatter(labels[torus], xs[torus], ys[torus], zs[torus], 400, spec); + // Override legend color with PlotDummy + spec.MarkerFillColors = nullptr; + spec.MarkerLineColors = nullptr; + spec.MarkerFillColor = legend_colors[torus]; + spec.MarkerLineColor = legend_colors[torus]; + ImPlot3D::PlotDummy(labels[torus], spec); + } + + ImPlot3D::EndPlot(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Config +//----------------------------------------------------------------------------- + +void DemoConfig() { + IMGUI_DEMO_MARKER("Config"); + ImGui::ShowFontSelector("Font"); + ImGui::ShowStyleSelector("ImGui Style"); + ImPlot3D::ShowStyleSelector("ImPlot3D Style"); + ImPlot3D::ShowColormapSelector("ImPlot3D Colormap"); + ImGui::Separator(); + + // Preview plot with 3D spirals + if (ImPlot3D::BeginPlot("Preview", ImVec2(-1, 0))) { + // Generate 10 spirals at different heights + static float xs[10][50], ys[10][50], zs[10][50]; + static bool initialized = false; + if (!initialized) { + for (int i = 0; i < 10; ++i) { + for (int j = 0; j < 50; ++j) { + float t = j / 49.0f; + float angle = t * 4.0f * IM_PI; + float radius = 0.3f + i * 0.05f; + xs[i][j] = radius * ImCos(angle); + ys[i][j] = radius * ImSin(angle); + zs[i][j] = i / 9.0f; + } + } + initialized = true; + } + + for (int i = 0; i < 10; ++i) { + ImGui::PushID(i); + ImPlot3D::PlotLine("##Spiral", xs[i], ys[i], zs[i], 50); + ImGui::PopID(); + } + + ImPlot3D::EndPlot(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Demo Window +//----------------------------------------------------------------------------- + +void DemoHelp() { + IMGUI_DEMO_MARKER("Help"); + ImGui::SeparatorText("ABOUT THIS DEMO:"); + ImGui::BulletText("The other tabs are demonstrating many aspects of the library."); + + ImGui::SeparatorText("PROGRAMMER GUIDE:"); + ImGui::BulletText("See the ShowDemoWindow() code in implot3d_demo.cpp. <- you are here!"); + ImGui::BulletText("See comments in implot3d_demo.cpp."); + ImGui::BulletText("See example application in example/ folder."); + + ImGui::SeparatorText("USER GUIDE:"); + ImGui::BulletText("Translation"); + { + ImGui::Indent(); + ImGui::BulletText("Left-click drag to translate."); + ImGui::BulletText("If over axis, only that axis will translate."); + ImGui::BulletText("If over plane, only that plane will translate."); + ImGui::BulletText("If outside plot area, translate in the view plane."); + ImGui::Unindent(); + } + + ImGui::BulletText("Zoom"); + { + ImGui::Indent(); + ImGui::BulletText("Scroll or middle-click drag to zoom."); + ImGui::BulletText("If over axis, only that axis will zoom."); + ImGui::BulletText("If over plane, only that plane will zoom."); + ImGui::BulletText("If outside plot area, zoom the entire plot."); + ImGui::Unindent(); + } + + ImGui::BulletText("Rotation"); + { + ImGui::Indent(); + ImGui::BulletText("Right-click drag to rotate."); + ImGui::BulletText("To reset rotation, double right-click outside plot area."); + ImGui::BulletText("To rotate to plane, double right-click when over the plane."); + ImGui::Unindent(); + } + + ImGui::BulletText("Fit data"); + { + ImGui::Indent(); + ImGui::BulletText("Double left-click to fit."); + ImGui::BulletText("If over axis, fit data to axis."); + ImGui::BulletText("If over plane, fit data to plane."); + ImGui::BulletText("If outside plot area, fit data to plot."); + ImGui::Unindent(); + } + + ImGui::BulletText("Context Menus"); + { + ImGui::Indent(); + ImGui::BulletText("Right-click outside plot area to show full context menu."); + ImGui::BulletText("Right-click over legend to show legend context menu."); + ImGui::BulletText("Right-click over axis to show axis context menu."); + ImGui::BulletText("Right-click over plane to show plane context menu."); + ImGui::Unindent(); + } + + ImGui::BulletText("Click legend label icons to show/hide plot items."); +} + +void DemoHeader(const char* label, void (*demo)()) { + if (ImGui::TreeNodeEx(label)) { + demo(); + ImGui::TreePop(); + } +} + +void ShowAllDemos() { + ImGui::Text("ImPlot3D says olá! (%s) (%d)", IMPLOT3D_VERSION, IMPLOT3D_VERSION_NUM); + ImGui::Spacing(); + if (ImGui::BeginTabBar("ImPlot3DDemoTabs")) { + if (ImGui::BeginTabItem("Plots")) { + // Plot Types + ImGui::SeparatorText("Plot Types"); + DemoHeader("Line Plots", DemoLinePlots); + DemoHeader("Scatter Plots", DemoScatterPlots); + DemoHeader("Triangle Plots", DemoTrianglePlots); + DemoHeader("Quad Plots", DemoQuadPlots); + DemoHeader("Surface Plots", DemoSurfacePlots); + DemoHeader("Mesh Plots", DemoMeshPlots); + DemoHeader("Realtime Plots", DemoRealtimePlots); + DemoHeader("Image Plots", DemoImagePlots); + + // Plot Options + ImGui::SeparatorText("Plot Options"); + DemoHeader("Plot Flags", DemoPlotFlags); + DemoHeader("Offset and Stride", DemoOffsetAndStride); + DemoHeader("Legend Options", DemoLegendOptions); + DemoHeader("Markers and Text", DemoMarkersAndText); + DemoHeader("NaN Values", DemoNaNValues); + DemoHeader("Per-Index Colors", Demo_PerIndexColors); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Axes")) { + DemoHeader("Box Scale", DemoBoxScale); + DemoHeader("Box Rotation", DemoBoxRotation); + DemoHeader("Log Scale", Demo_LogScale); + DemoHeader("Symmetric Log Scale", Demo_SymmetricLogScale); + DemoHeader("Tick Labels", DemoTickLabels); + DemoHeader("Axis Constraints", DemoAxisConstraints); + DemoHeader("Equal Axes", DemoEqualAxes); + DemoHeader("Auto-Fitting Data", DemoAutoFittingData); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Tools")) { + DemoHeader("Mouse Picking", DemoMousePicking); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Custom")) { + DemoHeader("Custom Styles", DemoCustomStyles); + DemoHeader("Custom Rendering", DemoCustomRendering); + DemoHeader("Custom Overlay", DemoCustomOverlay); + DemoHeader("Custom Per-Point Style", DemoCustomPerPointStyle); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Config")) { + DemoConfig(); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Help")) { + DemoHelp(); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } +} + +void ShowDemoWindow(bool* p_open) { + static bool show_implot3d_metrics = false; + static bool show_implot3d_style_editor = false; + static bool show_implot3d_about = false; + static bool show_imgui_metrics = false; + static bool show_imgui_style_editor = false; + static bool show_imgui_demo = false; + + if (show_implot3d_metrics) + ImPlot3D::ShowMetricsWindow(&show_implot3d_metrics); + if (show_implot3d_style_editor) { + ImGui::Begin("Style Editor (ImPlot3D)", &show_implot3d_style_editor); + ImPlot3D::ShowStyleEditor(); + ImGui::End(); + } + if (show_implot3d_about) + ImPlot3D::ShowAboutWindow(&show_implot3d_about); + if (show_imgui_style_editor) { + ImGui::Begin("Style Editor (ImGui)", &show_imgui_style_editor); + ImGui::ShowStyleEditor(); + ImGui::End(); + } + if (show_imgui_metrics) + ImGui::ShowMetricsWindow(&show_imgui_metrics); + if (show_imgui_demo) + ImGui::ShowDemoWindow(&show_imgui_demo); + + ImGui::SetNextWindowPos(ImVec2(100, 100), ImGuiCond_FirstUseEver); + ImGui::SetNextWindowSize(ImVec2(600, 750), ImGuiCond_FirstUseEver); + ImGui::Begin("ImPlot3D Demo", p_open, ImGuiWindowFlags_MenuBar); + if (ImGui::BeginMenuBar()) { + if (ImGui::BeginMenu("Tools")) { + ImGui::MenuItem("Metrics", nullptr, &show_implot3d_metrics); + ImGui::MenuItem("Style Editor", nullptr, &show_implot3d_style_editor); + ImGui::MenuItem("About ImPlot3D", nullptr, &show_implot3d_about); + ImGui::Separator(); + ImGui::MenuItem("ImGui Metrics", nullptr, &show_imgui_metrics); + ImGui::MenuItem("ImGui Style Editor", nullptr, &show_imgui_style_editor); + ImGui::MenuItem("ImGui Demo", nullptr, &show_imgui_demo); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + ShowAllDemos(); + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Style Editor +//----------------------------------------------------------------------------- + +bool ColormapButton(const char* label, const ImVec2& size_arg, ImPlot3DColormap cmap) { + ImGuiContext& G = *GImGui; + const ImGuiStyle& style = G.Style; + ImGuiWindow* Window = G.CurrentWindow; + if (Window->SkipItems) + return false; + ImPlot3DContext& gp = *GImPlot3D; + cmap = cmap == IMPLOT3D_AUTO ? gp.Style.Colormap : cmap; + IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!"); + const ImU32* keys = gp.ColormapData.GetKeys(cmap); + const int count = gp.ColormapData.GetKeyCount(cmap); + const bool qual = gp.ColormapData.IsQual(cmap); + const ImVec2 pos = ImGui::GetCurrentWindow()->DC.CursorPos; + const ImVec2 label_size = ImGui::CalcTextSize(label, nullptr, true); + ImVec2 size = ImGui::CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); + const ImRect rect = ImRect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); + RenderColorBar(keys, count, *ImGui::GetWindowDrawList(), rect, false, false, !qual); + const ImU32 text = CalcTextColor(gp.ColormapData.LerpTable(cmap, G.Style.ButtonTextAlign.x)); + ImGui::PushStyleColor(ImGuiCol_Button, IM_COL32_BLACK_TRANS); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(1, 1, 1, 0.1f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(1, 1, 1, 0.2f)); + ImGui::PushStyleColor(ImGuiCol_Text, text); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0); + const bool pressed = ImGui::Button(label, size); + ImGui::PopStyleColor(4); + ImGui::PopStyleVar(1); + return pressed; +} + +void ShowStyleEditor(ImPlot3DStyle* ref) { + ImPlot3DContext& gp = *GImPlot3D; + + // Handle style internal storage + ImPlot3DStyle& style = GetStyle(); + static ImPlot3DStyle ref_saved_style; + static bool init = true; + if (init && ref == nullptr) + ref_saved_style = style; + init = false; + if (ref == nullptr) + ref = &ref_saved_style; + + // Handle flash style color + static float flash_color_time = 0.5f; + static ImPlot3DCol flash_color_idx = ImPlot3DCol_COUNT; + static ImVec4 flash_color_backup = ImVec4(0, 0, 0, 0); + if (flash_color_idx != ImPlot3DCol_COUNT) { + // Flash color + ImVec4& color = style.Colors[flash_color_idx]; + ImGui::ColorConvertHSVtoRGB(ImCos(flash_color_time * 6.0f) * 0.5f + 0.5f, 0.5f, 0.5f, color.x, color.y, color.z); + color.w = 1.0f; + + // Decrease timer until zero + if ((flash_color_time -= ImGui::GetIO().DeltaTime) <= 0.0f) { + // When timer reaches zero, restore the backup color + style.Colors[flash_color_idx] = flash_color_backup; + flash_color_idx = ImPlot3DCol_COUNT; + flash_color_time = 0.5f; + } + } + + // Style selector + if (ImPlot3D::ShowStyleSelector("Colors##Selector")) + ref_saved_style = style; + + // Save/Revert button + if (ImGui::Button("Save Ref")) + *ref = ref_saved_style = style; + ImGui::SameLine(); + if (ImGui::Button("Revert Ref")) + style = *ref; + ImGui::SameLine(); + HelpMarker("Save/Revert in local non-persistent storage. Default Colors definition are not affected. " + "Use \"Export\" below to save them somewhere."); + + ImGui::Separator(); + + if (ImGui::BeginTabBar("##Tabs", ImGuiTabBarFlags_None)) { + if (ImGui::BeginTabItem("Variables")) { + ImGui::Text("Item Styling"); + ImGui::SliderFloat("LineWeight", &style.LineWeight, 0.0f, 5.0f, "%.1f"); + ImGui::SliderFloat("MarkerSize", &style.MarkerSize, 2.0f, 10.0f, "%.1f"); + ImGui::SliderFloat("FillAlpha", &style.FillAlpha, 0.0f, 1.0f, "%.2f"); + ImGui::Text("Plot Styling"); + ImGui::SliderFloat2("PlotDefaultSize", (float*)&style.PlotDefaultSize, 0.0f, 1000, "%.0f"); + ImGui::SliderFloat2("PlotMinSize", (float*)&style.PlotMinSize, 0.0f, 300, "%.0f"); + ImGui::SliderFloat2("PlotPadding", (float*)&style.PlotPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("LabelPadding", (float*)&style.LabelPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("ViewScaleFactor", (float*)&style.ViewScaleFactor, 0.1f, 2.0f, "%.2f"); + ImGui::Text("Legend Styling"); + ImGui::SliderFloat2("LegendPadding", (float*)&style.LegendPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("LegendInnerPadding", (float*)&style.LegendInnerPadding, 0.0f, 10.0f, "%.0f"); + ImGui::SliderFloat2("LegendSpacing", (float*)&style.LegendSpacing, 0.0f, 5.0f, "%.0f"); + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem("Colors")) { + static int output_dest = 0; + static bool output_only_modified = true; + if (ImGui::Button("Export")) { + if (output_dest == 0) + ImGui::LogToClipboard(); + else + ImGui::LogToTTY(); + ImGui::LogText("ImVec4* colors = ImPlot3D::GetStyle().Colors;\n"); + for (int i = 0; i < ImPlot3DCol_COUNT; i++) { + const ImVec4& col = style.Colors[i]; + const char* name = ImPlot3D::GetStyleColorName(i); + if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0) + ImGui::LogText("colors[ImPlot3DCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);\n", name, 15 - (int)strlen(name), "", col.x, + col.y, col.z, col.w); + } + ImGui::LogFinish(); + } + ImGui::SameLine(); + ImGui::SetNextItemWidth(120); + ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); + ImGui::SameLine(); + ImGui::Checkbox("Only Modified Colors", &output_only_modified); + + static ImGuiTextFilter filter; + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 16); + filter.Draw("Filter colors"); + + static ImGuiColorEditFlags alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; +#if IMGUI_VERSION_NUM < 19173 + if (ImGui::RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_None)) + alpha_flags = ImGuiColorEditFlags_None; + ImGui::SameLine(); + if (ImGui::RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_AlphaPreview)) + alpha_flags = ImGuiColorEditFlags_AlphaPreview; + ImGui::SameLine(); + if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) + alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; + ImGui::SameLine(); +#else + if (ImGui::RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_AlphaOpaque)) + alpha_flags = ImGuiColorEditFlags_AlphaOpaque; + ImGui::SameLine(); + if (ImGui::RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_None)) + alpha_flags = ImGuiColorEditFlags_None; + ImGui::SameLine(); + if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) + alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; + ImGui::SameLine(); +#endif + HelpMarker("In the color list:\n" + "Left-click on color square to open color picker,\n" + "Right-click to open edit options menu."); + + ImGui::Separator(); + + for (int i = 0; i < ImPlot3DCol_COUNT; i++) { + const char* name = ImPlot3D::GetStyleColorName(i); + if (!filter.PassFilter(name)) + continue; + ImGui::PushID(i); + + // Flash color + if (ImGui::Button("?")) { + if (flash_color_idx != ImPlot3DCol_COUNT) + style.Colors[flash_color_idx] = flash_color_backup; + flash_color_time = 0.5f; + flash_color_idx = (ImPlot3DCol)i; + flash_color_backup = style.Colors[i]; + } + ImGui::SetItemTooltip("Flash given color to identify places where it is used."); + ImGui::SameLine(); + + // Handle auto color selection + const bool is_auto = IsColorAuto(style.Colors[i]); + if (is_auto) + ImGui::BeginDisabled(); + if (ImGui::Button("Auto")) + style.Colors[i] = IMPLOT3D_AUTO_COL; + if (is_auto) + ImGui::EndDisabled(); + + // Color selection + ImGui::SameLine(); + if (ImGui::ColorEdit4("##Color", (float*)&style.Colors[i], ImGuiColorEditFlags_NoInputs | alpha_flags)) { + if (style.Colors[i].w == -1) + style.Colors[i].w = 1; + } + + // Save/Revert buttons if color changed + if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0) { + ImGui::SameLine(); + if (ImGui::Button("Save")) + ref->Colors[i] = style.Colors[i]; + ImGui::SameLine(); + if (ImGui::Button("Revert")) + style.Colors[i] = ref->Colors[i]; + } + ImGui::SameLine(); + ImGui::TextUnformatted(name); + ImGui::PopID(); + } + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem("Colormaps")) { + static int output_dest = 0; + if (ImGui::Button("Export", ImVec2(75, 0))) { + if (output_dest == 0) + ImGui::LogToClipboard(); + else + ImGui::LogToTTY(); + int size = GetColormapSize(); + const char* name = GetColormapName(gp.Style.Colormap); + ImGui::LogText("static const ImU32 %s_Data[%d] = {\n", name, size); + for (int i = 0; i < size; i++) { + ImU32 col = GetColormapColorU32(i, gp.Style.Colormap); + ImGui::LogText(" %u%s\n", col, i == size - 1 ? "" : ","); + } + ImGui::LogText("};\nImPlotColormap %s = ImPlot::AddColormap(\"%s\", %s_Data, %d);", name, name, name, size); + ImGui::LogFinish(); + } + ImGui::SameLine(); + ImGui::SetNextItemWidth(120); + ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); + ImGui::SameLine(); + static bool edit = false; + ImGui::Checkbox("Edit Mode", &edit); + + // built-in/added + ImGui::Separator(); + for (int i = 0; i < gp.ColormapData.Count; i++) { + ImGui::PushID(i); + int size = gp.ColormapData.GetKeyCount(i); + bool selected = i == gp.Style.Colormap; + + const char* name = GetColormapName(i); + if (!selected) + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.25f); + if (ImGui::Button(name, ImVec2(100, 0))) { + gp.Style.Colormap = i; + BustItemCache(); + } + if (!selected) + ImGui::PopStyleVar(); + ImGui::SameLine(); + ImGui::BeginGroup(); + if (edit) { + for (int c = 0; c < size; ++c) { + ImGui::PushID(c); + ImVec4 col4 = ImGui::ColorConvertU32ToFloat4(gp.ColormapData.GetKeyColor(i, c)); + if (ImGui::ColorEdit4("", &col4.x, ImGuiColorEditFlags_NoInputs)) { + ImU32 col32 = ImGui::ColorConvertFloat4ToU32(col4); + gp.ColormapData.SetKeyColor(i, c, col32); + BustItemCache(); + } + if ((c + 1) % 12 != 0 && c != size - 1) + ImGui::SameLine(); + ImGui::PopID(); + } + } else { + if (ColormapButton("##", ImVec2(-1, 0), i)) + edit = true; + } + ImGui::EndGroup(); + ImGui::PopID(); + } + + static ImVector custom; + if (custom.Size == 0) { + custom.push_back(ImVec4(1, 0, 0, 1)); + custom.push_back(ImVec4(0, 1, 0, 1)); + custom.push_back(ImVec4(0, 0, 1, 1)); + } + ImGui::Separator(); + ImGui::BeginGroup(); + static char name[16] = "MyColormap"; + + if (ImGui::Button("+", ImVec2((100 - ImGui::GetStyle().ItemSpacing.x) / 2, 0))) + custom.push_back(ImVec4(0, 0, 0, 1)); + ImGui::SameLine(); + if (ImGui::Button("-", ImVec2((100 - ImGui::GetStyle().ItemSpacing.x) / 2, 0)) && custom.Size > 2) + custom.pop_back(); + ImGui::SetNextItemWidth(100); + ImGui::InputText("##Name", name, 16, ImGuiInputTextFlags_CharsNoBlank); + static bool qual = true; + ImGui::Checkbox("Qualitative", &qual); + if (ImGui::Button("Add", ImVec2(100, 0)) && gp.ColormapData.GetIndex(name) == -1) + AddColormap(name, custom.Data, custom.Size, qual); + + ImGui::EndGroup(); + ImGui::SameLine(); + ImGui::BeginGroup(); + for (int c = 0; c < custom.Size; ++c) { + ImGui::PushID(c); + if (ImGui::ColorEdit4("##Col1", &custom[c].x, ImGuiColorEditFlags_NoInputs)) { + } + if ((c + 1) % 12 != 0) + ImGui::SameLine(); + ImGui::PopID(); + } + ImGui::EndGroup(); + + ImGui::EndTabItem(); + } + + ImGui::EndTabBar(); + } +} + +void ShowAboutWindow(bool* p_open) { + if (!ImGui::Begin("About ImPlot3D", p_open, ImGuiWindowFlags_AlwaysAutoResize)) { + ImGui::End(); + return; + } + + ImGui::Text("ImPlot3D %s (%d)", IMPLOT3D_VERSION, IMPLOT3D_VERSION_NUM); + + ImGui::TextLinkOpenURL("Homepage", "https://github.com/brenocq/implot3d"); + ImGui::SameLine(); + ImGui::TextLinkOpenURL("Q&A", "https://github.com/brenocq/implot3d/discussions/categories/q-a"); + ImGui::SameLine(); + ImGui::TextLinkOpenURL("Releases", "https://github.com/brenocq/implot3d/releases"); + ImGui::SameLine(); + ImGui::TextLinkOpenURL("Sponsors", "https://github.com/sponsors/brenocq"); + + ImGui::Separator(); + ImGui::Text("(c) 2024-2025 Breno Cunha Queiroz"); + ImGui::Text("Developed by Breno Cunha Queiroz and all ImPlot3D contributors."); + ImGui::Text("ImPlot3D is licensed under the MIT License."); + ImGui::Text("If your company uses ImPlot3D, please consider sponsoring the project."); + + static bool show_config_info = false; + ImGui::Checkbox("Config/Build Information", &show_config_info); + if (show_config_info) { + bool copy_to_clipboard = ImGui::Button("Copy to clipboard"); + ImVec2 child_size = ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18); + ImGui::BeginChild(ImGui::GetID("cfg_infos"), child_size, ImGuiChildFlags_FrameStyle); + if (copy_to_clipboard) { + ImGui::LogToClipboard(); + ImGui::LogText("```cpp\n"); + } + + ImGui::Text("ImPlot3D %s (%d)", IMPLOT3D_VERSION, IMPLOT3D_VERSION_NUM); + ImGui::Separator(); + ImGui::Text("sizeof(size_t): %d, sizeof(ImPlot3DPoint): %d", (int)sizeof(size_t), (int)sizeof(ImPlot3DPoint)); + +#ifdef IMPLOT3D_DISABLE_OBSOLETE_FUNCTIONS + ImGui::Text("define: IMPLOT3D_DISABLE_OBSOLETE_FUNCTIONS"); +#endif + + ImGui::Text("define: __cplusplus=%d", (int)__cplusplus); +#ifdef _WIN32 + ImGui::Text("define: _WIN32"); +#endif +#ifdef _WIN64 + ImGui::Text("define: _WIN64"); +#endif +#ifdef __linux__ + ImGui::Text("define: __linux__"); +#endif +#ifdef __APPLE__ + ImGui::Text("define: __APPLE__"); +#endif +#ifdef _MSC_VER + ImGui::Text("define: _MSC_VER=%d", _MSC_VER); +#endif +#ifdef __MINGW32__ + ImGui::Text("define: __MINGW32__"); +#endif +#ifdef __MINGW64__ + ImGui::Text("define: __MINGW64__"); +#endif +#ifdef __GNUC__ + ImGui::Text("define: __GNUC__=%d", (int)__GNUC__); +#endif +#ifdef __clang_version__ + ImGui::Text("define: __clang_version__=%s", __clang_version__); +#endif + + if (copy_to_clipboard) { + ImGui::LogText("```\n"); + ImGui::LogFinish(); + } + ImGui::EndChild(); + } + + ImGui::End(); +} + +} // namespace ImPlot3D + +//----------------------------------------------------------------------------- +// [SECTION] User Namespace Implementation +//----------------------------------------------------------------------------- + +namespace MyImPlot3D { + +void StyleSeaborn() { + + ImPlot3DStyle& style = ImPlot3D::GetStyle(); + + ImVec4* colors = style.Colors; + colors[ImPlot3DCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImPlot3DCol_PlotBg] = ImVec4(0.92f, 0.92f, 0.95f, 1.00f); + colors[ImPlot3DCol_PlotBorder] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImPlot3DCol_LegendBg] = ImVec4(0.92f, 0.92f, 0.95f, 1.00f); + colors[ImPlot3DCol_LegendBorder] = ImVec4(0.80f, 0.81f, 0.85f, 1.00f); + colors[ImPlot3DCol_LegendText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlot3DCol_TitleText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlot3DCol_InlayText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlot3DCol_AxisText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImPlot3DCol_AxisGrid] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + + style.LineWeight = 1.5; + style.Marker = ImPlot3DMarker_None; + style.MarkerSize = 4; + style.FillAlpha = 1.0f; + style.PlotPadding = ImVec2(12, 12); + style.LabelPadding = ImVec2(5, 5); + style.LegendPadding = ImVec2(5, 5); + style.PlotMinSize = ImVec2(300, 225); +} + +} // namespace MyImPlot3D diff --git a/tools/upstream/implot3d_internal.h b/tools/upstream/implot3d_internal.h new file mode 100644 index 0000000..8665e4e --- /dev/null +++ b/tools/upstream/implot3d_internal.h @@ -0,0 +1,942 @@ +// SPDX-License-Identifier: MIT +// SPDX-FileCopyrightText: 2024-2026 Breno Cunha Queiroz + +// ImPlot3D v0.5 WIP + +// Acknowledgments: +// ImPlot3D is heavily inspired by ImPlot +// (https://github.com/epezent/implot) by Evan Pezent, +// and follows a similar code style and structure to +// maintain consistency with ImPlot's API. + +// Table of Contents: +// [SECTION] Constants +// [SECTION] Generic Helpers +// [SECTION] Internal Enumerations +// [SECTION] Forward Declarations +// [SECTION] Callbacks +// [SECTION] Structs +// [SECTION] Context Pointer +// [SECTION] Context Utils +// [SECTION] Style Utils +// [SECTION] Item Utils +// [SECTION] Plot Utils +// [SECTION] Setup Utils +// [SECTION] Formatter +// [SECTION] Locator + +#pragma once + +#ifndef IMPLOT3D_VERSION +#include "implot3d.h" +#endif + +#ifndef IMGUI_DISABLE +#include "imgui_internal.h" + +//----------------------------------------------------------------------------- +// [SECTION] Constants +//----------------------------------------------------------------------------- + +// Default label format for axis labels +#define IMPLOT3D_LABEL_FORMAT "%g" +// Max character size for tick labels +#define IMPLOT3D_LABEL_MAX_SIZE 32 + +//----------------------------------------------------------------------------- +// [SECTION] Generic Helpers +//----------------------------------------------------------------------------- + +namespace ImPlot3D { + +// Computes the common (base-10) logarithm +static inline double ImLog10(double x) { return log10(x); } +// Computes the hyperbolic sine +static inline double ImSinh(double x) { return sinh(x); } +// Computes the inverse hyperbolic sine +static inline double ImAsinh(double x) { return asinh(x); } + +// Returns true if flag is set +template static inline bool ImHasFlag(TSet set, TFlag flag) { return (set & flag) == flag; } +// Flips a flag in a flagset +template static inline void ImFlipFlag(TSet& set, TFlag flag) { ImHasFlag(set, flag) ? set &= ~flag : set |= flag; } +template static inline T ImRemap01(T x, T x0, T x1) { return (x1 - x0) ? ((x - x0) / (x1 - x0)) : 0; } +// Returns always positive modulo (assumes r != 0) +static inline int ImPosMod(int l, int r) { return (l % r + r) % r; } +// Returns true if val is NAN +static inline bool ImNan(double val) { return isnan(val); } +// Returns true if val is NAN or INFINITY +static inline bool ImNanOrInf(double val) { return !(val >= -DBL_MAX && val <= DBL_MAX) || ImNan(val); } +// Turns NANs to 0s +static inline double ImConstrainNan(double val) { return ImNan(val) ? 0 : val; } +// Turns infinity to floating point maximums +// Clamped to half DBL_MAX to prevent overflow in size calculations (Max - Min) +static inline double ImConstrainInf(double val) { + const double max_val = DBL_MAX * 0.5; + return val >= max_val ? max_val : val <= -max_val ? -max_val : val; +} +// True if two numbers are approximately equal using units in the last place. +static inline bool ImAlmostEqual(double v1, double v2, int ulp = 2) { + return ImAbs(v1 - v2) < DBL_EPSILON * ImAbs(v1 + v2) * ulp || ImAbs(v1 - v2) < DBL_MIN; +} +// Set alpha channel of 32-bit color from float in range [0.0 1.0] +static inline ImU32 ImAlphaU32(ImU32 col, float alpha) { return col & ~((ImU32)((1.0f - alpha) * 255) << IM_COL32_A_SHIFT); } +// Mix color a and b by factor s in [0 256] +static inline ImU32 ImMixU32(ImU32 a, ImU32 b, ImU32 s) { +#ifdef IMPLOT3D_MIX64 + const ImU32 af = 256 - s; + const ImU32 bf = s; + const ImU64 al = (a & 0x00ff00ff) | (((ImU64)(a & 0xff00ff00)) << 24); + const ImU64 bl = (b & 0x00ff00ff) | (((ImU64)(b & 0xff00ff00)) << 24); + const ImU64 mix = (al * af + bl * bf); + return ((mix >> 32) & 0xff00ff00) | ((mix & 0xff00ff00) >> 8); +#else + const ImU32 af = 256 - s; + const ImU32 bf = s; + const ImU32 al = (a & 0x00ff00ff); + const ImU32 ah = (a & 0xff00ff00) >> 8; + const ImU32 bl = (b & 0x00ff00ff); + const ImU32 bh = (b & 0xff00ff00) >> 8; + const ImU32 ml = (al * af + bl * bf); + const ImU32 mh = (ah * af + bh * bf); + return (mh & 0xff00ff00) | ((ml & 0xff00ff00) >> 8); +#endif +} + +// Fills a buffer with n samples linear interpolated from vmin to vmax +template void FillRange(ImVector& buffer, int n, T vmin, T vmax) { + buffer.resize(n); + T step = (vmax - vmin) / (n - 1); + for (int i = 0; i < n; ++i) { + buffer[i] = vmin + i * step; + } +} + +} // namespace ImPlot3D + +//----------------------------------------------------------------------------- +// [SECTION] Internal Enumerations +//----------------------------------------------------------------------------- + +enum ImPlot3DMarkerInternal_ { + ImPlot3DMarker_Invalid = -3, +}; + +//----------------------------------------------------------------------------- +// [SECTION] Forward Declarations +//----------------------------------------------------------------------------- + +struct ImPlot3DTicker; + +//------------------------------------------------------------------------------ +// [SECTION] Callbacks +//------------------------------------------------------------------------------ + +typedef void (*ImPlot3DLocator)(ImPlot3DTicker& ticker, const ImPlot3DRange& range, float pixels, ImPlot3DFormatter formatter, void* formatter_data); + +//----------------------------------------------------------------------------- +// [SECTION] Structs +//----------------------------------------------------------------------------- + +struct ImDrawList3D { + // [Internal] Define which texture should be used when rendering triangles. + struct ImTextureBufferItem { + ImTextureRef TexRef; + unsigned int VtxIdx; + }; + + ImVector IdxBuffer; // Index buffer + ImVector VtxBuffer; // Vertex buffer + ImVector ZBuffer; // Z buffer. Depth value for each triangle + unsigned int _VtxCurrentIdx; // [Internal] current vertex index + ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + double* _ZWritePtr; // [Internal] point within ZBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImDrawListFlags _Flags; // [Internal] draw list flags + ImVector _TextureBuffer; // [Internal] buffer for SetTexture/ResetTexture + ImDrawListSharedData* _SharedData; // [Internal] shared draw list data + + ImDrawList3D() { + _Flags = ImDrawListFlags_None; + _SharedData = nullptr; + ResetBuffers(); + } + + void PrimReserve(int idx_count, int vtx_count); + void PrimUnreserve(int idx_count, int vtx_count); + + void SetTexture(ImTextureRef tex_ref); + void ResetTexture(); + + void SortedMoveToImGuiDrawList(); + + void ResetBuffers() { + IdxBuffer.clear(); + VtxBuffer.clear(); + ZBuffer.clear(); + _VtxCurrentIdx = 0; + _VtxWritePtr = VtxBuffer.Data; + _IdxWritePtr = IdxBuffer.Data; + _ZWritePtr = ZBuffer.Data; + _TextureBuffer.clear(); + ResetTexture(); + } + + constexpr static unsigned int MaxIdx() { return sizeof(ImDrawIdx) == 2 ? 65535 : 4294967295; } +}; + +struct ImPlot3DNextItemData { + ImPlot3DSpec Spec; + bool RenderLine; + bool RenderFill; + bool RenderMarkerLine; + bool RenderMarkerFill; + bool IsAutoFill; + bool IsAutoLine; + bool Hidden; + + ImPlot3DNextItemData() { Reset(); } + + void Reset() { + Spec = ImPlot3DSpec(); + RenderLine = false; + RenderFill = false; + RenderMarkerLine = true; + RenderMarkerFill = true; + IsAutoFill = true; + IsAutoLine = true; + Hidden = false; + } +}; + +// Colormap data storage +struct ImPlot3DColormapData { + ImVector Keys; + ImVector KeyCounts; + ImVector KeyOffsets; + ImVector Tables; + ImVector TableSizes; + ImVector TableOffsets; + ImGuiTextBuffer Text; + ImVector TextOffsets; + ImVector Quals; + ImGuiStorage Map; + int Count; + + ImPlot3DColormapData() { Count = 0; } + + int Append(const char* name, const ImU32* keys, int count, bool qual) { + if (GetIndex(name) != -1) + return -1; + KeyOffsets.push_back(Keys.size()); + KeyCounts.push_back(count); + Keys.reserve(Keys.size() + count); + for (int i = 0; i < count; ++i) + Keys.push_back(keys[i]); + TextOffsets.push_back(Text.size()); + Text.append(name, name + strlen(name) + 1); + Quals.push_back(qual); + ImGuiID id = ImHashStr(name); + int idx = Count++; + Map.SetInt(id, idx); + _AppendTable(idx); + return idx; + } + + void _AppendTable(ImPlot3DColormap cmap) { + int key_count = GetKeyCount(cmap); + const ImU32* keys = GetKeys(cmap); + int off = Tables.size(); + TableOffsets.push_back(off); + if (IsQual(cmap)) { + Tables.reserve(key_count); + for (int i = 0; i < key_count; ++i) + Tables.push_back(keys[i]); + TableSizes.push_back(key_count); + } else { + int max_size = 255 * (key_count - 1) + 1; + Tables.reserve(off + max_size); + // ImU32 last = keys[0]; + // Tables.push_back(last); + // int n = 1; + for (int i = 0; i < key_count - 1; ++i) { + for (int s = 0; s < 255; ++s) { + ImU32 a = keys[i]; + ImU32 b = keys[i + 1]; + ImU32 c = ImPlot3D::ImMixU32(a, b, (ImU32)s); + // if (c != last) { + Tables.push_back(c); + // last = c; + // n++; + // } + } + } + ImU32 c = keys[key_count - 1]; + // if (c != last) { + Tables.push_back(c); + // n++; + // } + // TableSizes.push_back(n); + TableSizes.push_back(max_size); + } + } + + void RebuildTables() { + Tables.resize(0); + TableSizes.resize(0); + TableOffsets.resize(0); + for (int i = 0; i < Count; ++i) + _AppendTable(i); + } + + inline bool IsQual(ImPlot3DColormap cmap) const { return Quals[cmap]; } + inline const char* GetName(ImPlot3DColormap cmap) const { return cmap < Count ? Text.Buf.Data + TextOffsets[cmap] : nullptr; } + inline ImPlot3DColormap GetIndex(const char* name) const { + ImGuiID key = ImHashStr(name); + return Map.GetInt(key, -1); + } + + inline const ImU32* GetKeys(ImPlot3DColormap cmap) const { return &Keys[KeyOffsets[cmap]]; } + inline int GetKeyCount(ImPlot3DColormap cmap) const { return KeyCounts[cmap]; } + inline ImU32 GetKeyColor(ImPlot3DColormap cmap, int idx) const { return Keys[KeyOffsets[cmap] + idx]; } + inline void SetKeyColor(ImPlot3DColormap cmap, int idx, ImU32 value) { + Keys[KeyOffsets[cmap] + idx] = value; + RebuildTables(); + } + + inline const ImU32* GetTable(ImPlot3DColormap cmap) const { return &Tables[TableOffsets[cmap]]; } + inline int GetTableSize(ImPlot3DColormap cmap) const { return TableSizes[cmap]; } + inline ImU32 GetTableColor(ImPlot3DColormap cmap, int idx) const { return Tables[TableOffsets[cmap] + idx]; } + + inline ImU32 LerpTable(ImPlot3DColormap cmap, float t) const { + int off = TableOffsets[cmap]; + int siz = TableSizes[cmap]; + int idx = Quals[cmap] ? ImClamp((int)(siz * t), 0, siz - 1) : (int)((siz - 1) * t + 0.5f); + return Tables[off + idx]; + } +}; + +// State information for plot items +struct ImPlot3DItem { + ImGuiID ID; + ImU32 Color; + ImPlot3DMarker Marker; + int NameOffset; + bool Show; + bool LegendHovered; + bool SeenThisFrame; + + ImPlot3DItem() { + ID = 0; + Color = IM_COL32_WHITE; + Marker = ImPlot3DMarker_None; + NameOffset = -1; + Show = true; + LegendHovered = false; + SeenThisFrame = false; + } + ~ImPlot3DItem() { ID = 0; } +}; + +// Holds legend state +struct ImPlot3DLegend { + ImPlot3DLegendFlags Flags; + ImPlot3DLegendFlags PreviousFlags; + ImPlot3DLocation Location; + ImPlot3DLocation PreviousLocation; + ImVec2 Scroll; + ImVector Indices; + ImGuiTextBuffer Labels; + ImRect Rect; + ImRect RectClamped; + bool Hovered; + bool Held; + + ImPlot3DLegend() { + PreviousFlags = Flags = ImPlot3DLegendFlags_None; + Hovered = Held = false; + PreviousLocation = Location = ImPlot3DLocation_NorthWest; + Scroll = ImVec2(0, 0); + } + + void Reset() { + Indices.shrink(0); + Labels.Buf.shrink(0); + } +}; + +// Holds items +struct ImPlot3DItemGroup { + ImGuiID ID; + ImPool ItemPool; + ImPlot3DLegend Legend; + int ColormapIdx; + ImPlot3DMarker MarkerIdx; + + ImPlot3DItemGroup() { + ID = 0; + ColormapIdx = 0; + MarkerIdx = 0; + } + + int GetItemCount() const { return ItemPool.GetBufSize(); } + ImGuiID GetItemID(const char* label_id) { return ImGui::GetID(label_id); } + ImPlot3DItem* GetItem(ImGuiID id) { return ItemPool.GetByKey(id); } + ImPlot3DItem* GetItem(const char* label_id) { return GetItem(GetItemID(label_id)); } + ImPlot3DItem* GetOrAddItem(ImGuiID id) { return ItemPool.GetOrAddByKey(id); } + ImPlot3DItem* GetItemByIndex(int i) { return ItemPool.GetByIndex(i); } + int GetItemIndex(ImPlot3DItem* item) { return ItemPool.GetIndex(item); } + int GetLegendCount() const { return Legend.Indices.size(); } + ImPlot3DItem* GetLegendItem(int i) { return ItemPool.GetByIndex(Legend.Indices[i]); } + const char* GetLegendLabel(int i) { return Legend.Labels.Buf.Data + GetLegendItem(i)->NameOffset; } + void Reset() { + ItemPool.Clear(); + Legend.Reset(); + ColormapIdx = 0; + MarkerIdx = 0; + } +}; + +// Tick mark info +struct ImPlot3DTick { + double PlotPos; + bool Major; + bool ShowLabel; + ImVec2 LabelSize; + int TextOffset; + int Idx; + + ImPlot3DTick(double value, bool major, bool show_label) { + PlotPos = value; + Major = major; + ShowLabel = show_label; + TextOffset = -1; + } +}; + +// Collection of ticks +struct ImPlot3DTicker { + ImVector Ticks; + ImGuiTextBuffer TextBuffer; + + ImPlot3DTicker() { Reset(); } + + ImPlot3DTick& AddTick(double value, bool major, bool show_label, const char* label) { + ImPlot3DTick tick(value, major, show_label); + if (show_label && label != nullptr) { + tick.TextOffset = TextBuffer.size(); + TextBuffer.append(label, label + strlen(label) + 1); + tick.LabelSize = ImGui::CalcTextSize(TextBuffer.Buf.Data + tick.TextOffset); + } + return AddTick(tick); + } + + ImPlot3DTick& AddTick(double value, bool major, bool show_label, ImPlot3DFormatter formatter, void* data) { + ImPlot3DTick tick(value, major, show_label); + if (show_label && formatter != nullptr) { + char buff[IMPLOT3D_LABEL_MAX_SIZE]; + tick.TextOffset = TextBuffer.size(); + formatter(tick.PlotPos, buff, sizeof(buff), data); + TextBuffer.append(buff, buff + strlen(buff) + 1); + tick.LabelSize = ImGui::CalcTextSize(TextBuffer.Buf.Data + tick.TextOffset); + } + return AddTick(tick); + } + + inline ImPlot3DTick& AddTick(ImPlot3DTick tick) { + tick.Idx = Ticks.size(); + Ticks.push_back(tick); + return Ticks.back(); + } + + const char* GetText(int idx) const { return TextBuffer.Buf.Data + Ticks[idx].TextOffset; } + + const char* GetText(const ImPlot3DTick& tick) const { return GetText(tick.Idx); } + + void Reset() { + Ticks.shrink(0); + TextBuffer.Buf.shrink(0); + } + + int TickCount() const { return Ticks.Size; } +}; + +// Holds axis information +struct ImPlot3DAxis { + // Flags + ImPlot3DAxisFlags Flags; + ImPlot3DAxisFlags PreviousFlags; + // Range + ImPlot3DRange Range; + ImPlot3DCond RangeCond; + double NDCScale; + ImPlot3DScale Scale; + // Label + ImGuiTextBuffer Label; + // Ticks + ImPlot3DTicker Ticker; + ImPlot3DFormatter Formatter; + void* FormatterData; + ImPlot3DLocator Locator; + bool ShowDefaultTicks; + // Scale + ImPlot3DTransform TransformForward; // Custom axis forward transform + ImPlot3DTransform TransformInverse; // Custom axis inverse transform + void* TransformData; // Custom transform data set by the user + ImPlot3DRange ScaledRange; // Cached scaled range values + // Fit data + bool FitThisFrame; + ImPlot3DRange FitExtents; + // Constraints + ImPlot3DRange ConstraintRange; + ImPlot3DRange ConstraintZoom; + // User input + bool Hovered; + bool Held; + // Cached colors + ImU32 ColorBg; + ImU32 ColorHov; + ImU32 ColorAct; + + // Constructor + ImPlot3DAxis() { + PreviousFlags = Flags = ImPlot3DAxisFlags_None; + // Range + Range.Min = 0.0; + Range.Max = 1.0; + RangeCond = ImPlot3DCond_None; + // Scale + NDCScale = 1.0; + Scale = ImPlot3DScale_Linear; + TransformForward = TransformInverse = nullptr; + TransformData = nullptr; + // Ticks + Formatter = nullptr; + FormatterData = nullptr; + Locator = nullptr; + ShowDefaultTicks = true; + // Fit data + FitThisFrame = true; + FitExtents = ImPlot3DRange(HUGE_VAL, -HUGE_VAL); + // Constraints + ConstraintRange = ImPlot3DRange(-INFINITY, INFINITY); + ConstraintZoom = ImPlot3DRange(DBL_MIN, INFINITY); + // User input + Hovered = false; + Held = false; + // Cached colors + ColorBg = ColorHov = ColorAct = IM_COL32_BLACK_TRANS; + } + + inline void Reset() { + RangeCond = ImPlot3DCond_None; + // Scale + Scale = ImPlot3DScale_Linear; + TransformForward = TransformInverse = nullptr; + TransformData = nullptr; + // Ticks + Ticker.Reset(); + Formatter = nullptr; + FormatterData = nullptr; + Locator = nullptr; + ShowDefaultTicks = true; + // Fit data + FitExtents = ImPlot3DRange(HUGE_VAL, -HUGE_VAL); + // Constraints + ConstraintRange = ImPlot3DRange(-INFINITY, INFINITY); + ConstraintZoom = ImPlot3DRange(DBL_MIN, INFINITY); + } + + inline void SetRange(double v1, double v2) { + v1 = ImPlot3D::ImConstrainNan(ImPlot3D::ImConstrainInf(v1)); + v2 = ImPlot3D::ImConstrainNan(ImPlot3D::ImConstrainInf(v2)); + Range.Min = ImMin(v1, v2); + Range.Max = ImMax(v1, v2); + Constrain(); + UpdateTransformCache(); + } + + inline bool SetMin(double _min, bool force = false) { + if (!force && IsLockedMin()) + return false; + _min = ImPlot3D::ImConstrainNan(ImPlot3D::ImConstrainInf(_min)); + + // Constraints + if (_min < ConstraintRange.Min) + _min = ConstraintRange.Min; + double zoom = Range.Max - _min; + if (zoom < ConstraintZoom.Min) + _min = Range.Max - ConstraintZoom.Min; + if (zoom > ConstraintZoom.Max) + _min = Range.Max - ConstraintZoom.Max; + + // Ensure min is less than max + if (_min >= Range.Max) + return false; + + Range.Min = _min; + UpdateTransformCache(); + return true; + } + + inline bool SetMax(double _max, bool force = false) { + if (!force && IsLockedMax()) + return false; + _max = ImPlot3D::ImConstrainNan(ImPlot3D::ImConstrainInf(_max)); + + // Constraints + if (_max > ConstraintRange.Max) + _max = ConstraintRange.Max; + double zoom = _max - Range.Min; + if (zoom < ConstraintZoom.Min) + _max = Range.Min + ConstraintZoom.Min; + if (zoom > ConstraintZoom.Max) + _max = Range.Min + ConstraintZoom.Max; + + // Ensure max is greater than min + if (_max <= Range.Min) + return false; + + Range.Max = _max; + UpdateTransformCache(); + return true; + } + + inline void Constrain() { + Range.Min = ImPlot3D::ImConstrainNan(ImPlot3D::ImConstrainInf(Range.Min)); + Range.Max = ImPlot3D::ImConstrainNan(ImPlot3D::ImConstrainInf(Range.Max)); + if (Range.Min < ConstraintRange.Min) + Range.Min = ConstraintRange.Min; + if (Range.Max > ConstraintRange.Max) + Range.Max = ConstraintRange.Max; + double zoom = Range.Size(); + if (zoom < ConstraintZoom.Min) { + double delta = (ConstraintZoom.Min - zoom) * 0.5; + Range.Min -= delta; + Range.Max += delta; + } + if (zoom > ConstraintZoom.Max) { + double delta = (zoom - ConstraintZoom.Max) * 0.5; + Range.Min += delta; + Range.Max -= delta; + } + if (Range.Max <= Range.Min) + Range.Max = Range.Min + DBL_EPSILON; + } + + inline void UpdateTransformCache() { + if (TransformForward != nullptr) { + ScaledRange.Min = TransformForward(Range.Min, TransformData); + ScaledRange.Max = TransformForward(Range.Max, TransformData); + } else { + ScaledRange.Min = Range.Min; + ScaledRange.Max = Range.Max; + } + } + + inline double PlotToNDC(double plt) const { + if (TransformForward != nullptr) { + double s = TransformForward(plt, TransformData); + return (s - ScaledRange.Min) / (ScaledRange.Max - ScaledRange.Min); + } + return (plt - Range.Min) / (Range.Max - Range.Min); + } + + inline double NDCToPlot(double t) const { + if (TransformInverse != nullptr) { + double s = t * (ScaledRange.Max - ScaledRange.Min) + ScaledRange.Min; + return TransformInverse(s, TransformData); + } + return Range.Min + t * (Range.Max - Range.Min); + } + + inline bool IsRangeLocked() const { return RangeCond == ImPlot3DCond_Always; } + inline bool IsLockedMin() const { return IsRangeLocked() || ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_LockMin); } + inline bool IsLockedMax() const { return IsRangeLocked() || ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_LockMax); } + inline bool IsLocked() const { return IsLockedMin() && IsLockedMax(); } + inline bool IsInputLockedMin() const { return IsLockedMin() || IsAutoFitting(); } + inline bool IsInputLockedMax() const { return IsLockedMax() || IsAutoFitting(); } + inline bool IsInputLocked() const { return IsLocked() || IsAutoFitting(); } + + inline bool IsPanLocked(bool increasing) { + if (ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_PanStretch)) { + return IsInputLocked(); + } else { + if (IsLockedMin() || IsLockedMax() || IsAutoFitting()) + return false; + if (increasing) + return Range.Max == ConstraintRange.Max; + else + return Range.Min == ConstraintRange.Min; + } + } + + inline void SetLabel(const char* label) { + Label.Buf.shrink(0); + if (label && ImGui::FindRenderedTextEnd(label, nullptr) != label) + Label.append(label, label + strlen(label) + 1); + } + + inline const char* GetLabel() const { return Label.Buf.Data; } + + inline double NDCSize() const { + // By default, the axis span from NDC -0.5 to 0.5, so size is 1.0 + // If NDCScale is applied, the size is scaled accordingly + return NDCScale; + } + + inline void SetAspect(double units_per_ndc_unit) { + double new_size = units_per_ndc_unit * NDCSize(); + double delta = (new_size - Range.Size()) * 0.5; + if (IsLocked()) + return; + else if (IsLockedMin() && !IsLockedMax()) + SetRange(Range.Min, Range.Max + 2 * delta); + else if (!IsLockedMin() && IsLockedMax()) + SetRange(Range.Min - 2 * delta, Range.Max); + else + SetRange(Range.Min - delta, Range.Max + delta); + } + + double GetAspect() const { return Range.Size() / NDCSize(); } + + bool HasLabel() const; + bool HasGridLines() const; + bool HasTickLabels() const; + bool HasTickMarks() const; + bool IsAutoFitting() const; + void ExtendFit(double value); + void ApplyFit(); +}; + +// Holds plot state information that must persist after EndPlot +struct ImPlot3DPlot { + ImGuiID ID; + ImPlot3DFlags Flags; + ImPlot3DFlags PreviousFlags; + ImGuiTextBuffer Title; + bool JustCreated; + bool Initialized; + // Bounding rectangles + ImRect FrameRect; // Outermost bounding rectangle that encapsulates whole the plot/title/padding/etc + ImRect CanvasRect; // Frame rectangle reduced by padding + ImRect PlotRect; // Bounding rectangle for the actual plot area + // Rotation & axes & box + ImPlot3DQuat InitialRotation; // Initial rotation quaternion + ImPlot3DQuat Rotation; // Current rotation quaternion + ImPlot3DCond RotationCond; + ImPlot3DAxis Axes[3]; // X, Y, Z axes + // Animation + float AnimationTime; // Remaining animation time + ImPlot3DQuat RotationAnimationEnd; // End rotation for animation + // User input + bool SetupLocked; + bool Hovered; + bool Held; + int HeldEdgeIdx; // Index of the edge being held + int HeldPlaneIdx; // Index of the plane being held + ImPlot3DPoint DragRotationAxis; // Axis of rotation for the duration of a drag + // Fit data + bool FitThisFrame; + // Items + ImPlot3DItemGroup Items; + // 3D draw list + ImDrawList3D DrawList; + // Misc + bool ContextClick; // True if context button was clicked (to distinguish from double click) + bool OpenContextThisFrame; + + ImPlot3DPlot() { + PreviousFlags = Flags = ImPlot3DFlags_None; + JustCreated = true; + Initialized = false; + InitialRotation = ImPlot3DQuat(-0.513269, -0.212596, -0.318184, 0.76819); + Rotation = ImPlot3DQuat(0.0, 0.0, 0.0, 1.0); + RotationCond = ImPlot3DCond_None; + for (int i = 0; i < 3; i++) + Axes[i] = ImPlot3DAxis(); + AnimationTime = 0.0f; + RotationAnimationEnd = Rotation; + SetupLocked = false; + Hovered = Held = false; + HeldEdgeIdx = -1; + HeldPlaneIdx = -1; + DragRotationAxis = ImPlot3DPoint(0.0, 0.0, 0.0); + FitThisFrame = true; + ContextClick = false; + OpenContextThisFrame = false; + } + + inline void SetTitle(const char* title) { + Title.Buf.shrink(0); + if (title && ImGui::FindRenderedTextEnd(title, nullptr) != title) + Title.append(title, title + strlen(title) + 1); + } + inline bool HasTitle() const { return !Title.empty() && !ImPlot3D::ImHasFlag(Flags, ImPlot3DFlags_NoTitle); } + inline const char* GetTitle() const { return Title.Buf.Data; } + inline bool IsRotationLocked() const { return RotationCond == ImPlot3DCond_Always; } + + // Extends the fit range of all three axes to include the provided point + void ExtendFit(const ImPlot3DPoint& point); + + // Returns the minimum of the range in all three dimensions + ImPlot3DPoint RangeMin() const; + + // Returns the maximum of the range in all three dimensions + ImPlot3DPoint RangeMax() const; + + // Returns the point at the center of the range in all three dimensions + ImPlot3DPoint RangeCenter() const; + + // Sets the range of all three axes + void SetRange(const ImPlot3DPoint& min, const ImPlot3DPoint& max); + + // Returns the scale of the plot view (constant to convert from NDC coordinates to pixels coordinates) + float GetViewScale() const; + + // Returns the scale of the plot box in each dimension + ImPlot3DPoint GetBoxScale() const; + + // Applies equal aspect ratio constraint using the specified axis as reference. + // Other axes are adjusted to match the reference axis's aspect ratio (units per NDC unit). + void ApplyEqualAspect(ImAxis3D ref_axis); +}; + +struct ImPlot3DContext { + ImPool Plots; + ImPlot3DPlot* CurrentPlot; + ImPlot3DItemGroup* CurrentItems; + ImPlot3DItem* CurrentItem; + ImPlot3DNextItemData NextItemData; + ImPlot3DStyle Style; + ImVector ColorModifiers; + ImVector StyleModifiers; + ImVector ColormapModifiers; + ImPlot3DColormapData ColormapData; +}; + +//----------------------------------------------------------------------------- +// [SECTION] Context Pointer +//----------------------------------------------------------------------------- + +namespace ImPlot3D { + +#ifndef GImPlot3D +extern IMPLOT3D_API ImPlot3DContext* GImPlot3D; // Current context pointer +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Context Utils +//----------------------------------------------------------------------------- + +IMPLOT3D_API void InitializeContext(ImPlot3DContext* ctx); // Initialize ImPlot3DContext +IMPLOT3D_API void ResetContext(ImPlot3DContext* ctx); // Reset ImPlot3DContext + +//----------------------------------------------------------------------------- +// [SECTION] Style Utils +//----------------------------------------------------------------------------- + +IMPLOT3D_API bool IsColorAuto(const ImVec4& col); +IMPLOT3D_API bool IsColorAuto(ImPlot3DCol idx); +IMPLOT3D_API ImVec4 GetAutoColor(ImPlot3DCol idx); +IMPLOT3D_API const char* GetStyleColorName(ImPlot3DCol idx); + +// Returns white or black text given background color +static inline ImU32 CalcTextColor(const ImVec4& bg) { + return (bg.x * 0.299f + bg.y * 0.587f + bg.z * 0.114f) > 0.5f ? IM_COL32_BLACK : IM_COL32_WHITE; +} +static inline ImU32 CalcTextColor(ImU32 bg) { return CalcTextColor(ImGui::ColorConvertU32ToFloat4(bg)); } + +// Get styling data for next item (call between BeginItem/EndItem) +IMPLOT3D_API const ImPlot3DNextItemData& GetItemData(); + +// Returns a color from the Color map given an index >= 0 (modulo will be performed) +IMPLOT3D_API ImU32 GetColormapColorU32(int idx, ImPlot3DColormap cmap); + +// Returns the next unused colormap color and advances the colormap. Can be used to skip colors if desired +IMPLOT3D_API ImU32 NextColormapColorU32(); + +// Render a colormap bar +IMPLOT3D_API void RenderColorBar(const ImU32* colors, int size, ImDrawList& DrawList, const ImRect& bounds, bool vert, bool reversed, + bool continuous); + +//----------------------------------------------------------------------------- +// [SECTION] Item Utils +//----------------------------------------------------------------------------- + +// Begins a new item. Returns false if the item should not be plotted +IMPLOT3D_API bool BeginItem(const char* label_id, const ImPlot3DSpec& spec = ImPlot3DSpec(), const ImVec4& item_col = IMPLOT3D_AUTO_COL, + ImPlot3DMarker item_mkr = ImPlot3DMarker_Invalid); +IMPLOT3D_API void EndItem(); + +// Register or get an existing item from the current plot +IMPLOT3D_API ImPlot3DItem* RegisterOrGetItem(const char* label_id, ImPlot3DItemFlags flags, bool* just_created = nullptr); + +// Gets the current item from ImPlot3DContext +IMPLOT3D_API ImPlot3DItem* GetCurrentItem(); + +// Busts the cache for every item for every plot in the current context +IMPLOT3D_API void BustItemCache(); + +// TODO move to another place +IMPLOT3D_API void AddTextRotated(ImDrawList* draw_list, ImVec2 pos, float angle, ImU32 col, const char* text_begin, const char* text_end = nullptr); + +//----------------------------------------------------------------------------- +// [SECTION] Plot Utils +//----------------------------------------------------------------------------- + +// Gets the current plot from ImPlot3DContext +IMPLOT3D_API ImPlot3DPlot* GetCurrentPlot(); + +// Busts the cache for every plot in the current context +IMPLOT3D_API void BustPlotCache(); + +IMPLOT3D_API ImVec2 GetFramePos(); // Get the current frame position (top-left) in pixels +IMPLOT3D_API ImVec2 GetFrameSize(); // Get the current frame size in pixels + +// Convert a position in the current plot's coordinate system to the current plot's normalized device coordinate system (NDC) +// When the cube's aspect ratio is [1,1,1], the NDC ranges from [-0.5, 0.5] along each axis +IMPLOT3D_API ImPlot3DPoint PlotToNDC(const ImPlot3DPoint& point); +IMPLOT3D_API ImPlot3DPoint NDCToPlot(const ImPlot3DPoint& point); +// Convert a position in the current plot's NDC to pixels +IMPLOT3D_API ImVec2 NDCToPixels(const ImPlot3DPoint& point); +// Convert a pixel coordinate to a ray in the NDC +IMPLOT3D_API ImPlot3DRay PixelsToNDCRay(const ImVec2& pix); +// Convert a ray in the NDC to a ray in the current plot's coordinate system +IMPLOT3D_API ImPlot3DRay NDCRayToPlotRay(const ImPlot3DRay& ray); + +//----------------------------------------------------------------------------- +// [SECTION] Setup Utils +//----------------------------------------------------------------------------- + +IMPLOT3D_API void SetupLock(); + +//----------------------------------------------------------------------------- +// [SECTION] Transforms +//----------------------------------------------------------------------------- + +static inline double TransformForward_Log10(double v, void*) { return ImLog10(v <= 0.0 ? DBL_MIN : v); } + +static inline double TransformInverse_Log10(double v, void*) { return ImPow(10, v); } + +static inline double TransformForward_SymLog(double v, void*) { return 2.0 * ImAsinh(v / 2.0); } + +static inline double TransformInverse_SymLog(double v, void*) { return 2.0 * ImSinh(v / 2.0); } + +//----------------------------------------------------------------------------- +// [SECTION] Formatter +//----------------------------------------------------------------------------- + +int Formatter_Default(double value, char* buff, int size, void* data); + +//------------------------------------------------------------------------------ +// [SECTION] Locator +//------------------------------------------------------------------------------ + +void Locator_Default(ImPlot3DTicker& ticker, const ImPlot3DRange& range, float pixels, ImPlot3DFormatter formatter, void* formatter_data); +void Locator_Log10(ImPlot3DTicker& ticker, const ImPlot3DRange& range, float pixels, ImPlot3DFormatter formatter, void* formatter_data); +void Locator_SymLog(ImPlot3DTicker& ticker, const ImPlot3DRange& range, float pixels, ImPlot3DFormatter formatter, void* formatter_data); + +} // namespace ImPlot3D + +#endif // #ifndef IMGUI_DISABLE diff --git a/tools/upstream/implot3d_items.cpp b/tools/upstream/implot3d_items.cpp new file mode 100644 index 0000000..19d2e68 --- /dev/null +++ b/tools/upstream/implot3d_items.cpp @@ -0,0 +1,1651 @@ +// SPDX-License-Identifier: MIT +// SPDX-FileCopyrightText: 2024-2026 Breno Cunha Queiroz + +// ImPlot3D v0.5 WIP + +// Acknowledgments: +// ImPlot3D is heavily inspired by ImPlot +// (https://github.com/epezent/implot) by Evan Pezent, +// and follows a similar code style and structure to +// maintain consistency with ImPlot's API. + +// Table of Contents: +// [SECTION] Includes +// [SECTION] Macros & Defines +// [SECTION] Template instantiation utility +// [SECTION] Item Utils +// [SECTION] Draw Utils +// [SECTION] Renderers +// [SECTION] Indexers +// [SECTION] Getters +// [SECTION] RenderPrimitives +// [SECTION] Markers +// [SECTION] PlotScatter +// [SECTION] PlotLine +// [SECTION] PlotTriangle +// [SECTION] PlotQuad +// [SECTION] PlotSurface +// [SECTION] PlotMesh +// [SECTION] PlotImage +// [SECTION] PlotText + +//----------------------------------------------------------------------------- +// [SECTION] Includes +//----------------------------------------------------------------------------- + +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif + +#include "implot3d.h" +#include "implot3d_internal.h" + +#ifndef IMGUI_DISABLE + +//----------------------------------------------------------------------------- +// [SECTION] Macros & Defines +//----------------------------------------------------------------------------- + +#define SQRT_1_2 0.70710678118f +#define SQRT_3_2 0.86602540378f + +// clang-format off +#ifndef IMPLOT3D_NO_FORCE_INLINE + #ifdef _MSC_VER + #define IMPLOT3D_INLINE __forceinline + #elif defined(__GNUC__) + #define IMPLOT3D_INLINE inline __attribute__((__always_inline__)) + #elif defined(__CLANG__) + #if __has_attribute(__always_inline__) + #define IMPLOT3D_INLINE inline __attribute__((__always_inline__)) + #else + #define IMPLOT3D_INLINE inline + #endif + #else + #define IMPLOT3D_INLINE inline + #endif +#else + #define IMPLOT3D_INLINE inline +#endif +// clang-format on + +#define IMPLOT3D_NORMALIZE2F(VX, VY) \ + do { \ + float d2 = VX * VX + VY * VY; \ + if (d2 > 0.0f) { \ + float inv_len = ImRsqrt(d2); \ + VX *= inv_len; \ + VY *= inv_len; \ + } \ + } while (0) + +IMPLOT3D_INLINE void GetLineRenderProps(const ImDrawList3D& draw_list_3d, float& half_weight, ImVec2& tex_uv0, ImVec2& tex_uv1) { + const bool aa = ImPlot3D::ImHasFlag(draw_list_3d._Flags, ImDrawListFlags_AntiAliasedLines) && + ImPlot3D::ImHasFlag(draw_list_3d._Flags, ImDrawListFlags_AntiAliasedLinesUseTex); + if (aa) { + ImVec4 tex_uvs = draw_list_3d._SharedData->TexUvLines[(int)(half_weight * 2)]; + tex_uv0 = ImVec2(tex_uvs.x, tex_uvs.y); + tex_uv1 = ImVec2(tex_uvs.z, tex_uvs.w); + half_weight += 1; + } else { + tex_uv0 = tex_uv1 = draw_list_3d._SharedData->TexUvWhitePixel; + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Template instantiation utility +//----------------------------------------------------------------------------- + +// By default, templates are instantiated for `float`, `double`, and for the following integer types, which are defined in imgui.h: +// signed char ImS8; // 8-bit signed integer +// unsigned char ImU8; // 8-bit unsigned integer +// signed short ImS16; // 16-bit signed integer +// unsigned short ImU16; // 16-bit unsigned integer +// signed int ImS32; // 32-bit signed integer == int +// unsigned int ImU32; // 32-bit unsigned integer +// signed long long ImS64; // 64-bit signed integer +// unsigned long long ImU64; // 64-bit unsigned integer +// (note: this list does *not* include `long`, `unsigned long` and `long double`) +// +// You can customize the supported types by defining IMPLOT3D_CUSTOM_NUMERIC_TYPES at compile time to define your own type list. +// As an example, you could use the compile time define given by the line below in order to support only float and double. +// -DIMPLOT3D_CUSTOM_NUMERIC_TYPES="(float)(double)" +// In order to support all known C++ types, use: +// -DIMPLOT3D_CUSTOM_NUMERIC_TYPES="(signed char)(unsigned char)(signed short)(unsigned short)(signed int)(unsigned int)(signed long)(unsigned +// long)(signed long long)(unsigned long long)(float)(double)(long double)" + +#ifdef IMPLOT3D_CUSTOM_NUMERIC_TYPES +#define IMPLOT3D_NUMERIC_TYPES IMPLOT3D_CUSTOM_NUMERIC_TYPES +#else +#define IMPLOT3D_NUMERIC_TYPES (ImS8)(ImU8)(ImS16)(ImU16)(ImS32)(ImU32)(ImS64)(ImU64)(float)(double) +#endif + +// CALL_INSTANTIATE_FOR_NUMERIC_TYPES will duplicate the template instantiation code `INSTANTIATE_MACRO(T)` on supported types. +#define _CAT(x, y) _CAT_(x, y) +#define _CAT_(x, y) x##y +#define _INSTANTIATE_FOR_NUMERIC_TYPES(chain) _CAT(_INSTANTIATE_FOR_NUMERIC_TYPES_1 chain, _END) +#define _INSTANTIATE_FOR_NUMERIC_TYPES_1(T) INSTANTIATE_MACRO(T) _INSTANTIATE_FOR_NUMERIC_TYPES_2 +#define _INSTANTIATE_FOR_NUMERIC_TYPES_2(T) INSTANTIATE_MACRO(T) _INSTANTIATE_FOR_NUMERIC_TYPES_1 +#define _INSTANTIATE_FOR_NUMERIC_TYPES_1_END +#define _INSTANTIATE_FOR_NUMERIC_TYPES_2_END +#define CALL_INSTANTIATE_FOR_NUMERIC_TYPES() _INSTANTIATE_FOR_NUMERIC_TYPES(IMPLOT3D_NUMERIC_TYPES) + +//----------------------------------------------------------------------------- +// [SECTION] Item Utils +//----------------------------------------------------------------------------- +namespace ImPlot3D { + +static const float ITEM_HIGHLIGHT_LINE_SCALE = 2.0f; +static const float ITEM_HIGHLIGHT_MARK_SCALE = 1.25f; + +template int Stride(const ImPlot3DSpec& spec) { return spec.Stride == IMPLOT3D_AUTO ? sizeof(T) : spec.Stride; } + +bool BeginItem(const char* label_id, const ImPlot3DSpec& spec, const ImVec4& item_col, ImPlot3DMarker item_mkr) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PlotX() needs to be called between BeginPlot() and EndPlot()!"); + + // Lock setup + SetupLock(); + + // Override next data with spec + ImPlot3DStyle& style = gp.Style; + ImPlot3DNextItemData& n = gp.NextItemData; + ImPlot3DSpec& s = n.Spec; + s = spec; + + // Register item + bool just_created; + ImPlot3DItem* item = RegisterOrGetItem(label_id, spec.Flags, &just_created); + // Set current item + gp.CurrentItem = item; + + // Set/override item color + if (!IsColorAuto(item_col)) { + item->Color = ImGui::ColorConvertFloat4ToU32(item_col); + } else if (just_created) { + item->Color = NextColormapColorU32(); + } + + // Set/override item marker + if (item_mkr != ImPlot3DMarker_Invalid) { + if (item_mkr != ImPlot3DMarker_Auto) { + item->Marker = item_mkr; + } else if (just_created && item_mkr == ImPlot3DMarker_Auto) { + item->Marker = NextMarker(); + } else if (item_mkr == ImPlot3DMarker_Auto && item->Marker == ImPlot3DMarker_None) { + item->Marker = NextMarker(); + } + } + + // Set next item color + ImVec4 item_color = ImGui::ColorConvertU32ToFloat4(item->Color); + n.IsAutoLine = IsColorAuto(s.LineColor); + n.IsAutoFill = IsColorAuto(s.FillColor); + s.LineColor = IsColorAuto(s.LineColor) ? item_color : s.LineColor; + s.FillColor = IsColorAuto(s.FillColor) ? item_color : s.FillColor; + s.MarkerLineColor = IsColorAuto(s.MarkerLineColor) ? s.LineColor : s.MarkerLineColor; + s.MarkerFillColor = IsColorAuto(s.MarkerFillColor) ? s.LineColor : s.MarkerFillColor; + + // Set size & weight + s.LineWeight = s.LineWeight < 0.0f ? style.LineWeight : s.LineWeight; + s.Marker = s.Marker < 0 ? style.Marker : s.Marker; + s.MarkerSize = s.MarkerSize < 0.0f ? style.MarkerSize : s.MarkerSize; + s.FillAlpha = s.FillAlpha < 0 ? gp.Style.FillAlpha : s.FillAlpha; + + // Apply alpha modifiers + s.FillColor.w *= s.FillAlpha; + s.MarkerFillColor.w *= s.FillAlpha; + + // Set render flags + n.RenderLine = s.LineColor.w > 0 && s.LineWeight > 0; + n.RenderFill = s.FillColor.w > 0; + n.RenderMarkerLine = s.LineColor.w > 0 && s.LineWeight > 0; + n.RenderMarkerFill = s.FillColor.w > 0; + + // Don't render if item is hidden + if (!item->Show) { + EndItem(); + return false; + } else { + // Legend hover highlight + if (item->LegendHovered) { + if (!ImHasFlag(gp.CurrentItems->Legend.Flags, ImPlot3DLegendFlags_NoHighlightItem)) { + s.LineWeight *= ITEM_HIGHLIGHT_LINE_SCALE; + s.MarkerSize *= ITEM_HIGHLIGHT_MARK_SCALE; + } + } + } + + return true; +} + +template bool BeginItemEx(const char* label_id, const _Getter& getter, const ImPlot3DSpec& spec, + const ImVec4& item_col = IMPLOT3D_AUTO_COL, ImPlot3DMarker item_mkr = ImPlot3DMarker_Invalid) { + if (BeginItem(label_id, spec, item_col, item_mkr)) { + ImPlot3DContext& gp = *GImPlot3D; + ImPlot3DPlot& plot = *gp.CurrentPlot; + if (plot.FitThisFrame && !ImHasFlag(spec.Flags, ImPlot3DItemFlags_NoFit)) { + for (int i = 0; i < getter.Count; i++) + plot.ExtendFit(getter(i)); + } + return true; + } + return false; +} + +void EndItem() { + ImPlot3DContext& gp = *GImPlot3D; + gp.NextItemData.Reset(); + gp.CurrentItem = nullptr; +} + +ImPlot3DItem* RegisterOrGetItem(const char* label_id, ImPlot3DItemFlags flags, bool* just_created) { + ImPlot3DContext& gp = *GImPlot3D; + ImPlot3DItemGroup& Items = *gp.CurrentItems; + ImGuiID id = Items.GetItemID(label_id); + if (just_created != nullptr) + *just_created = Items.GetItem(id) == nullptr; + ImPlot3DItem* item = Items.GetOrAddItem(id); + + // Avoid re-adding the same item to the legend (the legend is reset every frame) + if (item->SeenThisFrame) + return item; + item->SeenThisFrame = true; + + // Add item to the legend + int idx = Items.GetItemIndex(item); + item->ID = id; + if (!ImHasFlag(flags, ImPlot3DItemFlags_NoLegend) && ImGui::FindRenderedTextEnd(label_id, nullptr) != label_id) { + Items.Legend.Indices.push_back(idx); + item->NameOffset = Items.Legend.Labels.size(); + Items.Legend.Labels.append(label_id, label_id + strlen(label_id) + 1); + } + return item; +} + +ImPlot3DItem* GetCurrentItem() { + ImPlot3DContext& gp = *GImPlot3D; + return gp.CurrentItem; +} + +void BustItemCache() { + ImPlot3DContext& gp = *GImPlot3D; + for (int p = 0; p < gp.Plots.GetBufSize(); ++p) { + ImPlot3DPlot& plot = *gp.Plots.GetByIndex(p); + plot.Items.Reset(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Draw Utils +//----------------------------------------------------------------------------- + +IMPLOT3D_INLINE void PrimLine(ImDrawList3D& draw_list_3d, const ImVec2& P1, const ImVec2& P2, float half_weight, ImU32 col, const ImVec2& tex_uv0, + const ImVec2& tex_uv1, double z) { + float dx = P2.x - P1.x; + float dy = P2.y - P1.y; + IMPLOT3D_NORMALIZE2F(dx, dy); + dx *= half_weight; + dy *= half_weight; + draw_list_3d._VtxWritePtr[0].pos.x = P1.x + dy; + draw_list_3d._VtxWritePtr[0].pos.y = P1.y - dx; + draw_list_3d._VtxWritePtr[0].uv = tex_uv0; + draw_list_3d._VtxWritePtr[0].col = col; + draw_list_3d._VtxWritePtr[1].pos.x = P2.x + dy; + draw_list_3d._VtxWritePtr[1].pos.y = P2.y - dx; + draw_list_3d._VtxWritePtr[1].uv = tex_uv0; + draw_list_3d._VtxWritePtr[1].col = col; + draw_list_3d._VtxWritePtr[2].pos.x = P2.x - dy; + draw_list_3d._VtxWritePtr[2].pos.y = P2.y + dx; + draw_list_3d._VtxWritePtr[2].uv = tex_uv1; + draw_list_3d._VtxWritePtr[2].col = col; + draw_list_3d._VtxWritePtr[3].pos.x = P1.x - dy; + draw_list_3d._VtxWritePtr[3].pos.y = P1.y + dx; + draw_list_3d._VtxWritePtr[3].uv = tex_uv1; + draw_list_3d._VtxWritePtr[3].col = col; + draw_list_3d._VtxWritePtr += 4; + draw_list_3d._IdxWritePtr[0] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx); + draw_list_3d._IdxWritePtr[1] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 1); + draw_list_3d._IdxWritePtr[2] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 2); + draw_list_3d._IdxWritePtr[3] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx); + draw_list_3d._IdxWritePtr[4] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 2); + draw_list_3d._IdxWritePtr[5] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 3); + draw_list_3d._IdxWritePtr += 6; + draw_list_3d._VtxCurrentIdx += 4; + draw_list_3d._ZWritePtr[0] = z; + draw_list_3d._ZWritePtr[1] = z; + draw_list_3d._ZWritePtr += 2; +} + +//----------------------------------------------------------------------------- +// [SECTION] Renderers +//----------------------------------------------------------------------------- + +double GetPointDepth(ImPlot3DPoint p) { + ImPlot3DContext& gp = *GImPlot3D; + ImPlot3DPlot& plot = *gp.CurrentPlot; + + // Adjust for inverted axes before rotation + if (ImHasFlag(plot.Axes[0].Flags, ImPlot3DAxisFlags_Invert)) + p.x = -p.x; + if (ImHasFlag(plot.Axes[1].Flags, ImPlot3DAxisFlags_Invert)) + p.y = -p.y; + if (ImHasFlag(plot.Axes[2].Flags, ImPlot3DAxisFlags_Invert)) + p.z = -p.z; + + ImPlot3DPoint p_rot = plot.Rotation * p; + return p_rot.z; +} + +struct RendererBase { + RendererBase(int prims, int idx_consumed, int vtx_consumed) : Prims(prims), IdxConsumed(idx_consumed), VtxConsumed(vtx_consumed) {} + const unsigned int Prims; // Number of primitives to render + const unsigned int IdxConsumed; // Number of indices consumed per primitive + const unsigned int VtxConsumed; // Number of vertices consumed per primitive +}; + +template struct RendererMarkersFill : RendererBase { + RendererMarkersFill(const _Getter& getter, const _GetterColor& col_getter, const _GetterSize& size_getter, const ImVec2* marker, int count) + : RendererBase(getter.Count, (count - 2) * 3, count), Getter(getter), ColGetter(col_getter), SizeGetter(size_getter), Marker(marker), + Count(count) {} + + void Init(ImDrawList3D& draw_list_3d) const { UV = draw_list_3d._SharedData->TexUvWhitePixel; } + + IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { + ImPlot3DPoint p_plot = Getter(prim); + if (!cull_box.Contains(p_plot)) + return false; + ImVec2 p = PlotToPixels(p_plot); + ImU32 col = ColGetter(prim); + float size = SizeGetter(prim); + // 3 vertices per triangle + for (int i = 0; i < Count; i++) { + draw_list_3d._VtxWritePtr[0].pos.x = p.x + Marker[i].x * size; + draw_list_3d._VtxWritePtr[0].pos.y = p.y + Marker[i].y * size; + draw_list_3d._VtxWritePtr[0].uv = UV; + draw_list_3d._VtxWritePtr[0].col = col; + draw_list_3d._VtxWritePtr++; + } + // 3 indices per triangle + for (int i = 2; i < Count; i++) { + // Indices + draw_list_3d._IdxWritePtr[0] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx); + draw_list_3d._IdxWritePtr[1] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + i - 1); + draw_list_3d._IdxWritePtr[2] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + i); + draw_list_3d._IdxWritePtr += 3; + // Z + draw_list_3d._ZWritePtr[0] = GetPointDepth(p_plot); + draw_list_3d._ZWritePtr++; + } + // Update vertex count + draw_list_3d._VtxCurrentIdx += (ImDrawIdx)Count; + return true; + } + const _Getter& Getter; + const _GetterColor ColGetter; + const _GetterSize SizeGetter; + const ImVec2* Marker; + const int Count; + mutable ImVec2 UV; +}; + +template struct RendererMarkersLine : RendererBase { + RendererMarkersLine(const _Getter& getter, const _GetterColor& col_getter, const _GetterSize& size_getter, const ImVec2* marker, int count, + float weight) + : RendererBase(getter.Count, count / 2 * 6, count / 2 * 4), Getter(getter), ColGetter(col_getter), SizeGetter(size_getter), Marker(marker), + Count(count), HalfWeight(ImMax(1.0f, weight) * 0.5f) {} + + void Init(ImDrawList3D& draw_list_3d) const { GetLineRenderProps(draw_list_3d, HalfWeight, UV0, UV1); } + + IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { + ImPlot3DPoint p_plot = Getter(prim); + if (!cull_box.Contains(p_plot)) + return false; + ImVec2 p = PlotToPixels(p_plot); + ImU32 col = ColGetter(prim); + float size = SizeGetter(prim); + for (int i = 0; i < Count; i = i + 2) { + ImVec2 p1(p.x + Marker[i].x * size, p.y + Marker[i].y * size); + ImVec2 p2(p.x + Marker[i + 1].x * size, p.y + Marker[i + 1].y * size); + PrimLine(draw_list_3d, p1, p2, HalfWeight, col, UV0, UV1, GetPointDepth(p_plot)); + } + return true; + } + + const _Getter& Getter; + const _GetterColor ColGetter; + const _GetterSize SizeGetter; + const ImVec2* Marker; + const int Count; + mutable float HalfWeight; + mutable ImVec2 UV0; + mutable ImVec2 UV1; +}; + +template struct RendererLineStrip : RendererBase { + RendererLineStrip(const _Getter& getter, const _GetterColor& col_getter, float weight) + : RendererBase(getter.Count - 1, 6, 4), Getter(getter), ColGetter(col_getter), HalfWeight(ImMax(1.0f, weight) * 0.5f) { + // Initialize the first point in plot coordinates + P1_plot = Getter(0); + } + + void Init(ImDrawList3D& draw_list_3d) const { GetLineRenderProps(draw_list_3d, HalfWeight, UV0, UV1); } + + IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { + ImPlot3DPoint P2_plot = Getter(prim + 1); + + // Clip the line segment to the culling box using Liang-Barsky algorithm + ImPlot3DPoint P1_clipped, P2_clipped; + bool visible = cull_box.ClipLineSegment(P1_plot, P2_plot, P1_clipped, P2_clipped); + + if (visible) { + // Convert clipped points to pixel coordinates + ImVec2 P1_screen = PlotToPixels(P1_clipped); + ImVec2 P2_screen = PlotToPixels(P2_clipped); + // Render the line segment + PrimLine(draw_list_3d, P1_screen, P2_screen, HalfWeight, ColGetter(prim), UV0, UV1, GetPointDepth((P1_plot + P2_plot) * 0.5)); + } + + // Update for next segment + P1_plot = P2_plot; + + return visible; + } + + const _Getter& Getter; + const _GetterColor ColGetter; + mutable float HalfWeight; + mutable ImPlot3DPoint P1_plot; + mutable ImVec2 UV0; + mutable ImVec2 UV1; +}; + +template struct RendererLineStripSkip : RendererBase { + RendererLineStripSkip(const _Getter& getter, const _GetterColor& col_getter, float weight) + : RendererBase(getter.Count - 1, 6, 4), Getter(getter), ColGetter(col_getter), HalfWeight(ImMax(1.0f, weight) * 0.5f) { + // Initialize the first point in plot coordinates + P1_plot = Getter(0); + } + + void Init(ImDrawList3D& draw_list_3d) const { GetLineRenderProps(draw_list_3d, HalfWeight, UV0, UV1); } + + IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { + // Get the next point in plot coordinates + ImPlot3DPoint P2_plot = Getter(prim + 1); + bool visible = false; + + // Check for NaNs in P1_plot and P2_plot + if (!ImNan(P1_plot.x) && !ImNan(P1_plot.y) && !ImNan(P1_plot.z) && !ImNan(P2_plot.x) && !ImNan(P2_plot.y) && !ImNan(P2_plot.z)) { + + // Clip the line segment to the culling box + ImPlot3DPoint P1_clipped, P2_clipped; + visible = cull_box.ClipLineSegment(P1_plot, P2_plot, P1_clipped, P2_clipped); + + if (visible) { + // Convert clipped points to pixel coordinates + ImVec2 P1_screen = PlotToPixels(P1_clipped); + ImVec2 P2_screen = PlotToPixels(P2_clipped); + // Render the line segment + PrimLine(draw_list_3d, P1_screen, P2_screen, HalfWeight, ColGetter(prim), UV0, UV1, GetPointDepth((P1_plot + P2_plot) * 0.5)); + } + } + + // Update P1_plot if P2_plot is valid + if (!ImNan(P2_plot.x) && !ImNan(P2_plot.y) && !ImNan(P2_plot.z)) + P1_plot = P2_plot; + + return visible; + } + + const _Getter& Getter; + const _GetterColor ColGetter; + mutable float HalfWeight; + mutable ImPlot3DPoint P1_plot; + mutable ImVec2 UV0; + mutable ImVec2 UV1; +}; + +template struct RendererLineSegments : RendererBase { + RendererLineSegments(const _Getter& getter, const _GetterColor& col_getter, float weight) + : RendererBase(getter.Count / 2, 6, 4), Getter(getter), ColGetter(col_getter), HalfWeight(ImMax(1.0f, weight) * 0.5f) {} + + void Init(ImDrawList3D& draw_list_3d) const { GetLineRenderProps(draw_list_3d, HalfWeight, UV0, UV1); } + + IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { + // Get the segment's endpoints in plot coordinates + ImPlot3DPoint P1_plot = Getter(prim * 2 + 0); + ImPlot3DPoint P2_plot = Getter(prim * 2 + 1); + + // Check for NaNs in P1_plot and P2_plot + if (!ImNan(P1_plot.x) && !ImNan(P1_plot.y) && !ImNan(P1_plot.z) && !ImNan(P2_plot.x) && !ImNan(P2_plot.y) && !ImNan(P2_plot.z)) { + + // Clip the line segment to the culling box + ImPlot3DPoint P1_clipped, P2_clipped; + bool visible = cull_box.ClipLineSegment(P1_plot, P2_plot, P1_clipped, P2_clipped); + + if (visible) { + // Convert clipped points to pixel coordinates + ImVec2 P1_screen = PlotToPixels(P1_clipped); + ImVec2 P2_screen = PlotToPixels(P2_clipped); + // Render the line segment + PrimLine(draw_list_3d, P1_screen, P2_screen, HalfWeight, ColGetter(prim), UV0, UV1, GetPointDepth((P1_plot + P2_plot) * 0.5)); + } + return visible; + } + + return false; + } + + const _Getter& Getter; + const _GetterColor ColGetter; + mutable float HalfWeight; + mutable ImVec2 UV0; + mutable ImVec2 UV1; +}; + +template struct RendererTriangleFill : RendererBase { + RendererTriangleFill(const _Getter& getter, const _GetterColor& col_getter) + : RendererBase(getter.Count / 3, 3, 3), Getter(getter), ColGetter(col_getter) {} + + void Init(ImDrawList3D& draw_list_3d) const { UV = draw_list_3d._SharedData->TexUvWhitePixel; } + + IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { + ImPlot3DPoint p_plot[3]; + p_plot[0] = Getter(3 * prim); + p_plot[1] = Getter(3 * prim + 1); + p_plot[2] = Getter(3 * prim + 2); + + // Check if the triangle is outside the culling box + if (!cull_box.Contains(p_plot[0]) && !cull_box.Contains(p_plot[1]) && !cull_box.Contains(p_plot[2])) + return false; + + // Project the triangle vertices to screen space + ImVec2 p[3]; + p[0] = PlotToPixels(p_plot[0]); + p[1] = PlotToPixels(p_plot[1]); + p[2] = PlotToPixels(p_plot[2]); + + // 3 vertices per triangle + draw_list_3d._VtxWritePtr[0].pos.x = p[0].x; + draw_list_3d._VtxWritePtr[0].pos.y = p[0].y; + draw_list_3d._VtxWritePtr[0].uv = UV; + draw_list_3d._VtxWritePtr[0].col = ColGetter(3 * prim); + draw_list_3d._VtxWritePtr[1].pos.x = p[1].x; + draw_list_3d._VtxWritePtr[1].pos.y = p[1].y; + draw_list_3d._VtxWritePtr[1].uv = UV; + draw_list_3d._VtxWritePtr[1].col = ColGetter(3 * prim + 1); + draw_list_3d._VtxWritePtr[2].pos.x = p[2].x; + draw_list_3d._VtxWritePtr[2].pos.y = p[2].y; + draw_list_3d._VtxWritePtr[2].uv = UV; + draw_list_3d._VtxWritePtr[2].col = ColGetter(3 * prim + 2); + draw_list_3d._VtxWritePtr += 3; + + // 3 indices per triangle + draw_list_3d._IdxWritePtr[0] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx); + draw_list_3d._IdxWritePtr[1] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 1); + draw_list_3d._IdxWritePtr[2] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 2); + draw_list_3d._IdxWritePtr += 3; + // 1 Z per vertex + draw_list_3d._ZWritePtr[0] = GetPointDepth((p_plot[0] + p_plot[1] + p_plot[2]) / 3); + draw_list_3d._ZWritePtr++; + + // Update vertex count + draw_list_3d._VtxCurrentIdx += 3; + + return true; + } + + const _Getter& Getter; + const _GetterColor ColGetter; + mutable ImVec2 UV; +}; + +template struct RendererQuadFill : RendererBase { + RendererQuadFill(const _Getter& getter, const _GetterColor& col_getter) + : RendererBase(getter.Count / 4, 6, 4), Getter(getter), ColGetter(col_getter) {} + + void Init(ImDrawList3D& draw_list_3d) const { UV = draw_list_3d._SharedData->TexUvWhitePixel; } + + IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { + ImPlot3DPoint p_plot[4]; + p_plot[0] = Getter(4 * prim); + p_plot[1] = Getter(4 * prim + 1); + p_plot[2] = Getter(4 * prim + 2); + p_plot[3] = Getter(4 * prim + 3); + + // Check if the quad is outside the culling box + if (!cull_box.Contains(p_plot[0]) && !cull_box.Contains(p_plot[1]) && !cull_box.Contains(p_plot[2]) && !cull_box.Contains(p_plot[3])) + return false; + + // Project the quad vertices to screen space + ImVec2 p[4]; + p[0] = PlotToPixels(p_plot[0]); + p[1] = PlotToPixels(p_plot[1]); + p[2] = PlotToPixels(p_plot[2]); + p[3] = PlotToPixels(p_plot[3]); + + // Add vertices for two triangles + draw_list_3d._VtxWritePtr[0].pos.x = p[0].x; + draw_list_3d._VtxWritePtr[0].pos.y = p[0].y; + draw_list_3d._VtxWritePtr[0].uv = UV; + draw_list_3d._VtxWritePtr[0].col = ColGetter(4 * prim); + + draw_list_3d._VtxWritePtr[1].pos.x = p[1].x; + draw_list_3d._VtxWritePtr[1].pos.y = p[1].y; + draw_list_3d._VtxWritePtr[1].uv = UV; + draw_list_3d._VtxWritePtr[1].col = ColGetter(4 * prim + 1); + + draw_list_3d._VtxWritePtr[2].pos.x = p[2].x; + draw_list_3d._VtxWritePtr[2].pos.y = p[2].y; + draw_list_3d._VtxWritePtr[2].uv = UV; + draw_list_3d._VtxWritePtr[2].col = ColGetter(4 * prim + 2); + + draw_list_3d._VtxWritePtr[3].pos.x = p[3].x; + draw_list_3d._VtxWritePtr[3].pos.y = p[3].y; + draw_list_3d._VtxWritePtr[3].uv = UV; + draw_list_3d._VtxWritePtr[3].col = ColGetter(4 * prim + 3); + + draw_list_3d._VtxWritePtr += 4; + + // Add indices for two triangles + draw_list_3d._IdxWritePtr[0] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx); + draw_list_3d._IdxWritePtr[1] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 1); + draw_list_3d._IdxWritePtr[2] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 2); + + draw_list_3d._IdxWritePtr[3] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx); + draw_list_3d._IdxWritePtr[4] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 2); + draw_list_3d._IdxWritePtr[5] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 3); + + draw_list_3d._IdxWritePtr += 6; + + // Add depth value for the quad + double z = GetPointDepth((p_plot[0] + p_plot[1] + p_plot[2] + p_plot[3]) / 4.0); + draw_list_3d._ZWritePtr[0] = z; + draw_list_3d._ZWritePtr[1] = z; + draw_list_3d._ZWritePtr += 2; + + // Update vertex count + draw_list_3d._VtxCurrentIdx += 4; + + return true; + } + + const _Getter& Getter; + const _GetterColor ColGetter; + mutable ImVec2 UV; +}; + +template struct RendererQuadImage : RendererBase { + RendererQuadImage(const _Getter& getter, ImTextureRef tex_ref, const ImVec2& uv0, const ImVec2& uv1, const ImVec2& uv2, const ImVec2& uv3, + ImU32 col) + : RendererBase(getter.Count / 4, 6, 4), Getter(getter), TexRef(tex_ref), UV0(uv0), UV1(uv1), UV2(uv2), UV3(uv3), Col(col) {} + + void Init(ImDrawList3D& /*draw_list_3d*/) const {} + + IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { + ImPlot3DPoint p_plot[4]; + p_plot[0] = Getter(4 * prim); + p_plot[1] = Getter(4 * prim + 1); + p_plot[2] = Getter(4 * prim + 2); + p_plot[3] = Getter(4 * prim + 3); + + // Check if the quad is outside the culling box + if (!cull_box.Contains(p_plot[0]) && !cull_box.Contains(p_plot[1]) && !cull_box.Contains(p_plot[2]) && !cull_box.Contains(p_plot[3])) + return false; + + // Set texture ID to be used when rendering this quad + draw_list_3d.SetTexture(TexRef); + + // Project the quad vertices to screen space + ImVec2 p[4]; + p[0] = PlotToPixels(p_plot[0]); + p[1] = PlotToPixels(p_plot[1]); + p[2] = PlotToPixels(p_plot[2]); + p[3] = PlotToPixels(p_plot[3]); + + // Add vertices for two triangles + draw_list_3d._VtxWritePtr[0].pos.x = p[0].x; + draw_list_3d._VtxWritePtr[0].pos.y = p[0].y; + draw_list_3d._VtxWritePtr[0].uv = UV0; + draw_list_3d._VtxWritePtr[0].col = Col; + + draw_list_3d._VtxWritePtr[1].pos.x = p[1].x; + draw_list_3d._VtxWritePtr[1].pos.y = p[1].y; + draw_list_3d._VtxWritePtr[1].uv = UV1; + draw_list_3d._VtxWritePtr[1].col = Col; + + draw_list_3d._VtxWritePtr[2].pos.x = p[2].x; + draw_list_3d._VtxWritePtr[2].pos.y = p[2].y; + draw_list_3d._VtxWritePtr[2].uv = UV2; + draw_list_3d._VtxWritePtr[2].col = Col; + + draw_list_3d._VtxWritePtr[3].pos.x = p[3].x; + draw_list_3d._VtxWritePtr[3].pos.y = p[3].y; + draw_list_3d._VtxWritePtr[3].uv = UV3; + draw_list_3d._VtxWritePtr[3].col = Col; + + draw_list_3d._VtxWritePtr += 4; + + // Add indices for two triangles + draw_list_3d._IdxWritePtr[0] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx); + draw_list_3d._IdxWritePtr[1] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 1); + draw_list_3d._IdxWritePtr[2] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 2); + + draw_list_3d._IdxWritePtr[3] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx); + draw_list_3d._IdxWritePtr[4] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 2); + draw_list_3d._IdxWritePtr[5] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 3); + + draw_list_3d._IdxWritePtr += 6; + + // Add depth value for the quad + double z = GetPointDepth((p_plot[0] + p_plot[1] + p_plot[2] + p_plot[3]) / 4.0); + draw_list_3d._ZWritePtr[0] = z; + draw_list_3d._ZWritePtr[1] = z; + draw_list_3d._ZWritePtr += 2; + + // Update vertex count + draw_list_3d._VtxCurrentIdx += 4; + + // Reset texture ID + draw_list_3d.ResetTexture(); + + return true; + } + + const _Getter& Getter; + const ImTextureRef TexRef; + const ImVec2 UV0, UV1, UV2, UV3; + const ImU32 Col; +}; + +template struct RendererSurfaceFill : RendererBase { + RendererSurfaceFill(const _Getter& getter, int x_count, int y_count, ImU32 col, double scale_min, double scale_max) + : RendererBase((x_count - 1) * (y_count - 1), 6, 4), Getter(getter), Min(0.), Max(0.), XCount(x_count), YCount(y_count), Col(col), + ScaleMin(scale_min), ScaleMax(scale_max) {} + + void Init(ImDrawList3D& draw_list_3d) const { + UV = draw_list_3d._SharedData->TexUvWhitePixel; + + // Compute min and max values for the colormap (if not solid fill) + const ImPlot3DNextItemData& n = GetItemData(); + if (n.IsAutoFill) { + Min = DBL_MAX; + Max = -DBL_MAX; + for (int i = 0; i < Getter.Count; i++) { + double z = Getter(i).z; + Min = ImMin(Min, z); + Max = ImMax(Max, z); + } + } + } + + IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { + int x = prim % (XCount - 1); + int y = prim / (XCount - 1); + + ImPlot3DPoint p_plot[4]; + p_plot[0] = Getter(x + y * XCount); + p_plot[1] = Getter(x + 1 + y * XCount); + p_plot[2] = Getter(x + 1 + (y + 1) * XCount); + p_plot[3] = Getter(x + (y + 1) * XCount); + + // Check if the quad is outside the culling box + if (!cull_box.Contains(p_plot[0]) && !cull_box.Contains(p_plot[1]) && !cull_box.Contains(p_plot[2]) && !cull_box.Contains(p_plot[3])) + return false; + + // Compute colors + ImU32 cols[4] = {Col, Col, Col, Col}; + const ImPlot3DNextItemData& n = GetItemData(); + const int vtx_idx[4] = {x + y * XCount, x + 1 + y * XCount, x + 1 + (y + 1) * XCount, x + (y + 1) * XCount}; + if (n.Spec.FillColors != nullptr) { + float alpha = n.Spec.FillAlpha; + for (int i = 0; i < 4; i++) { + ImU32 c = n.Spec.FillColors[vtx_idx[i]]; + ImVec4 cv = ImGui::ColorConvertU32ToFloat4(c); + cv.w *= alpha; + cols[i] = ImGui::ColorConvertFloat4ToU32(cv); + } + } else if (n.IsAutoFill) { + float alpha = GImPlot3D->NextItemData.Spec.FillAlpha; + double min = Min; + double max = Max; + if (ScaleMin != 0.0 || ScaleMax != 0.0) { + min = ScaleMin; + max = ScaleMax; + } + for (int i = 0; i < 4; i++) { + ImVec4 col = SampleColormap((float)ImClamp(ImRemap01(p_plot[i].z, min, max), 0.0, 1.0)); + col.w *= alpha; + cols[i] = ImGui::ColorConvertFloat4ToU32(col); + } + } + + // Project the quad vertices to screen space + ImVec2 p[4]; + p[0] = PlotToPixels(p_plot[0]); + p[1] = PlotToPixels(p_plot[1]); + p[2] = PlotToPixels(p_plot[2]); + p[3] = PlotToPixels(p_plot[3]); + + // Add vertices for two triangles + draw_list_3d._VtxWritePtr[0].pos.x = p[0].x; + draw_list_3d._VtxWritePtr[0].pos.y = p[0].y; + draw_list_3d._VtxWritePtr[0].uv = UV; + draw_list_3d._VtxWritePtr[0].col = cols[0]; + + draw_list_3d._VtxWritePtr[1].pos.x = p[1].x; + draw_list_3d._VtxWritePtr[1].pos.y = p[1].y; + draw_list_3d._VtxWritePtr[1].uv = UV; + draw_list_3d._VtxWritePtr[1].col = cols[1]; + + draw_list_3d._VtxWritePtr[2].pos.x = p[2].x; + draw_list_3d._VtxWritePtr[2].pos.y = p[2].y; + draw_list_3d._VtxWritePtr[2].uv = UV; + draw_list_3d._VtxWritePtr[2].col = cols[2]; + + draw_list_3d._VtxWritePtr[3].pos.x = p[3].x; + draw_list_3d._VtxWritePtr[3].pos.y = p[3].y; + draw_list_3d._VtxWritePtr[3].uv = UV; + draw_list_3d._VtxWritePtr[3].col = cols[3]; + + draw_list_3d._VtxWritePtr += 4; + + // Add indices for two triangles + draw_list_3d._IdxWritePtr[0] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx); + draw_list_3d._IdxWritePtr[1] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 1); + draw_list_3d._IdxWritePtr[2] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 2); + + draw_list_3d._IdxWritePtr[3] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx); + draw_list_3d._IdxWritePtr[4] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 2); + draw_list_3d._IdxWritePtr[5] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 3); + + draw_list_3d._IdxWritePtr += 6; + + // Add depth values for the two triangles + draw_list_3d._ZWritePtr[0] = GetPointDepth((p_plot[0] + p_plot[1] + p_plot[2]) / 3.0); + draw_list_3d._ZWritePtr[1] = GetPointDepth((p_plot[0] + p_plot[2] + p_plot[3]) / 3.0); + draw_list_3d._ZWritePtr += 2; + + // Update vertex count + draw_list_3d._VtxCurrentIdx += 4; + + return true; + } + + const _Getter& Getter; + mutable ImVec2 UV; + mutable double Min; // Minimum value for the colormap + mutable double Max; // Maximum value for the colormap + const int XCount; + const int YCount; + const ImU32 Col; + const double ScaleMin; + const double ScaleMax; +}; + +//----------------------------------------------------------------------------- +// [SECTION] Indexers +//----------------------------------------------------------------------------- + +template IMPLOT3D_INLINE T IndexData(const T* data, int idx, int count, int offset, int stride) { + const int s = ((offset == 0) << 0) | ((stride == sizeof(T)) << 1); + switch (s) { + case 3: return data[idx]; + case 2: return data[(offset + idx) % count]; + case 1: return *(const T*)(const void*)((const unsigned char*)data + (size_t)((idx)) * stride); + case 0: return *(const T*)(const void*)((const unsigned char*)data + (size_t)((offset + idx) % count) * stride); + default: return T(0); + } +} + +template struct IndexerIdx { + IndexerIdx(const T* data, int count, int offset = 0, int stride = sizeof(T)) + : Data(data), Count(count), Offset(count ? ImPosMod(offset, count) : 0), Stride(stride) {} + template IMPLOT3D_INLINE double operator()(I idx) const { return (double)IndexData(Data, idx, Count, Offset, Stride); } + const T* Data; + int Count; + int Offset; + int Stride; +}; + +//----------------------------------------------------------------------------- +// [SECTION] Getters +//----------------------------------------------------------------------------- + +template struct GetterXYZ { + GetterXYZ(_IndexerX x, _IndexerY y, _IndexerZ z, int count) : IndexerX(x), IndexerY(y), IndexerZ(z), Count(count) {} + template IMPLOT3D_INLINE ImPlot3DPoint operator()(I idx) const { return ImPlot3DPoint(IndexerX(idx), IndexerY(idx), IndexerZ(idx)); } + const _IndexerX IndexerX; + const _IndexerY IndexerY; + const _IndexerZ IndexerZ; + const int Count; +}; + +template struct GetterLoop { + GetterLoop(_Getter getter) : Getter(getter), Count(getter.Count + 1) {} + template IMPLOT3D_INLINE ImPlot3DPoint operator()(I idx) const { + idx = idx % (Count - 1); + return Getter(idx); + } + const _Getter Getter; + const int Count; +}; + +template struct GetterTriangleLines { + GetterTriangleLines(_Getter getter) : Getter(getter), Count(getter.Count * 2) {} + template IMPLOT3D_INLINE ImPlot3DPoint operator()(I idx) const { + idx = ((idx % 6 + 1) / 2) % 3 + idx / 6 * 3; + return Getter(idx); + } + const _Getter Getter; + const int Count; +}; + +template struct GetterQuadLines { + GetterQuadLines(_Getter getter) : Getter(getter), Count(getter.Count * 2) {} + template IMPLOT3D_INLINE ImPlot3DPoint operator()(I idx) const { + idx = ((idx % 8 + 1) / 2) % 4 + idx / 8 * 4; + return Getter(idx); + } + const _Getter Getter; + const int Count; +}; + +template struct GetterSurfaceLines { + GetterSurfaceLines(_Getter getter, int x_count, int y_count) : Getter(getter), XCount(x_count), YCount(y_count) { + int horizontal_segments = (XCount - 1) * YCount; + int vertical_segments = (YCount - 1) * XCount; + int segments = horizontal_segments + vertical_segments; + Count = segments * 2; // Each segment has 2 endpoints + } + + template IMPLOT3D_INLINE ImPlot3DPoint operator()(I idx) const { + // idx is an endpoint index + int endpoint_i = (int)(idx % 2); + int segment_i = (int)(idx / 2); + + int horizontal_segments = (XCount - 1) * YCount; + + int px, py; + if (segment_i < horizontal_segments) { + // Horizontal segment + int row = segment_i / (XCount - 1); + int col = segment_i % (XCount - 1); + // Endpoint 0 is (col, row), endpoint 1 is (col+1, row) + px = endpoint_i == 0 ? col : col + 1; + py = row; + } else { + // Vertical segment + int seg_v = segment_i - horizontal_segments; + int col = seg_v / (YCount - 1); + int row = seg_v % (YCount - 1); + // Endpoint 0 is (col, row), endpoint 1 is (col, row+1) + px = col; + py = row + endpoint_i; + } + + return Getter(py * XCount + px); + } + + const _Getter Getter; + int Count; + const int XCount; + const int YCount; +}; + +struct Getter3DPoints { + Getter3DPoints(const ImPlot3DPoint* points, int count) : Points(points), Count(count) {} + template IMPLOT3D_INLINE ImPlot3DPoint operator()(I idx) const { return Points[idx]; } + const ImPlot3DPoint* Points; + const int Count; +}; + +template struct GetterMeshTriangles { + GetterMeshTriangles(TGX gx, TGY gy, TGZ gz, const unsigned int* idx, int idx_count) + : Gx(gx), Gy(gy), Gz(gz), Idx(idx), TriCount(idx_count / 3), Count(idx_count) {} + + template IMPLOT3D_INLINE ImPlot3DPoint operator()(I i) const { + unsigned int vi = Idx[i]; + return ImPlot3DPoint(Gx(vi), Gy(vi), Gz(vi)); + } + + TGX Gx; + TGY Gy; + TGZ Gz; + const unsigned int* Idx; + int TriCount; + int Count; +}; + +//----------------------------------------------------------------------------- +// [SECTION] Color and Size Getters +//----------------------------------------------------------------------------- + +struct GetterConstColor { + GetterConstColor(ImU32 col) : Col(col) {} + IMPLOT3D_INLINE ImU32 operator()(int) const { return Col; } + ImU32 Col; +}; + +struct GetterIdxColor { + GetterIdxColor(const ImU32* data, int count, float alpha = 1.0f) : Data(data), Count(count), Alpha(alpha) {} + IMPLOT3D_INLINE ImU32 operator()(int idx) const { + ImU32 col = Data[idx]; + if (Alpha < 1.0f) { + ImVec4 c = ImGui::ColorConvertU32ToFloat4(col); + c.w *= Alpha; + col = ImGui::ColorConvertFloat4ToU32(c); + } + return col; + } + const ImU32* Data; + const int Count; + const float Alpha; +}; + +struct GetterConstSize { + GetterConstSize(float size) : Size(size) {} + IMPLOT3D_INLINE float operator()(int) const { return Size; } + float Size; +}; + +struct GetterIdxSize { + GetterIdxSize(const float* data, int count) : Data(data), Count(count) {} + IMPLOT3D_INLINE float operator()(int idx) const { return Data[idx]; } + const float* Data; + const int Count; +}; + +//----------------------------------------------------------------------------- +// [SECTION] RenderPrimitives +//----------------------------------------------------------------------------- + +/// Renders primitive shapes (pre-built renderer variant) +template void RenderPrimitivesEx(const _Renderer& renderer) { + ImPlot3DPlot& plot = *GetCurrentPlot(); + ImDrawList3D& draw_list_3d = plot.DrawList; + ImPlot3DBox cull_box; + if (ImHasFlag(plot.Flags, ImPlot3DFlags_NoClip)) { + cull_box.Min = ImPlot3DPoint(-HUGE_VAL, -HUGE_VAL, -HUGE_VAL); + cull_box.Max = ImPlot3DPoint(HUGE_VAL, HUGE_VAL, HUGE_VAL); + } else { + cull_box.Min = plot.RangeMin(); + cull_box.Max = plot.RangeMax(); + } + + // Find how many can be reserved up to end of current draw command's limit + unsigned int prims_to_render = ImMin(renderer.Prims, (ImDrawList3D::MaxIdx() - draw_list_3d._VtxCurrentIdx) / renderer.VtxConsumed); + + // Reserve vertices and indices to render the primitives + draw_list_3d.PrimReserve(prims_to_render * renderer.IdxConsumed, prims_to_render * renderer.VtxConsumed); + + // Initialize renderer + renderer.Init(draw_list_3d); + + // Render primitives + int num_culled = 0; + for (unsigned int i = 0; i < prims_to_render; i++) + if (!renderer.Render(draw_list_3d, cull_box, i)) + num_culled++; + // Unreserve unused vertices and indices + draw_list_3d.PrimUnreserve(num_culled * renderer.IdxConsumed, num_culled * renderer.VtxConsumed); +} + +/// Renders primitive shapes (single-template-param renderer convenience wrapper) +template