implot3d.cpp 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011
  1. //--------------------------------------------------
  2. // ImPlot3D v0.1
  3. // implot3d.cpp
  4. // Date: 2024-11-16
  5. // Author: Breno Cunha Queiroz (brenocq.com)
  6. //
  7. // Acknowledgments:
  8. // ImPlot3D is heavily inspired by ImPlot
  9. // (https://github.com/epezent/implot) by Evan Pezent,
  10. // and follows a similar code style and structure to
  11. // maintain consistency with ImPlot's API.
  12. //--------------------------------------------------
  13. // Table of Contents:
  14. // [SECTION] Includes
  15. // [SECTION] Macros
  16. // [SECTION] Context
  17. // [SECTION] Text Utils
  18. // [SECTION] Legend Utils
  19. // [SECTION] Mouse Position Utils
  20. // [SECTION] Plot Box Utils
  21. // [SECTION] Formatter
  22. // [SECTION] Locator
  23. // [SECTION] Context Menus
  24. // [SECTION] Begin/End Plot
  25. // [SECTION] Setup
  26. // [SECTION] Plot Utils
  27. // [SECTION] Setup Utils
  28. // [SECTION] Miscellaneous
  29. // [SECTION] Styles
  30. // [SECTION] Colormaps
  31. // [SECTION] Context Utils
  32. // [SECTION] Style Utils
  33. // [SECTION] ImPlot3DPoint
  34. // [SECTION] ImPlot3DBox
  35. // [SECTION] ImPlot3DRange
  36. // [SECTION] ImPlot3DQuat
  37. // [SECTION] ImDrawList3D
  38. // [SECTION] ImPlot3DAxis
  39. // [SECTION] ImPlot3DPlot
  40. // [SECTION] ImPlot3DStyle
  41. //-----------------------------------------------------------------------------
  42. // [SECTION] Includes
  43. //-----------------------------------------------------------------------------
  44. #ifndef IMGUI_DEFINE_MATH_OPERATORS
  45. #define IMGUI_DEFINE_MATH_OPERATORS
  46. #endif
  47. #include "implot3d.h"
  48. #include "implot3d_internal.h"
  49. #ifndef IMGUI_DISABLE
  50. //-----------------------------------------------------------------------------
  51. // [SECTION] Macros
  52. //-----------------------------------------------------------------------------
  53. #define IMPLOT3D_CHECK_CTX() IM_ASSERT_USER_ERROR(GImPlot3D != nullptr, "No current context. Did you call ImPlot3D::CreateContext() or ImPlot3D::SetCurrentContext()?")
  54. #define IMPLOT3D_CHECK_PLOT() IM_ASSERT_USER_ERROR(GImPlot3D->CurrentPlot != nullptr, "No active plot. Did you call ImPlot3D::BeginPlot()?")
  55. //-----------------------------------------------------------------------------
  56. // [SECTION] Context
  57. //-----------------------------------------------------------------------------
  58. namespace ImPlot3D {
  59. // Global ImPlot3D context
  60. #ifndef GImPlot3D
  61. ImPlot3DContext* GImPlot3D = nullptr;
  62. #endif
  63. static ImPlot3DQuat init_rotation = ImPlot3DQuat(-0.513269, -0.212596, -0.318184, 0.76819);
  64. ImPlot3DContext* CreateContext() {
  65. ImPlot3DContext* ctx = IM_NEW(ImPlot3DContext)();
  66. if (GImPlot3D == nullptr)
  67. SetCurrentContext(ctx);
  68. InitializeContext(ctx);
  69. return ctx;
  70. }
  71. void DestroyContext(ImPlot3DContext* ctx) {
  72. if (ctx == nullptr)
  73. ctx = GImPlot3D;
  74. if (GImPlot3D == ctx)
  75. SetCurrentContext(nullptr);
  76. IM_DELETE(ctx);
  77. }
  78. ImPlot3DContext* GetCurrentContext() { return GImPlot3D; }
  79. void SetCurrentContext(ImPlot3DContext* ctx) { GImPlot3D = ctx; }
  80. //-----------------------------------------------------------------------------
  81. // [SECTION] Text Utils
  82. //-----------------------------------------------------------------------------
  83. void AddTextRotated(ImDrawList* draw_list, ImVec2 pos, float angle, ImU32 col, const char* text_begin, const char* text_end) {
  84. if (!text_end)
  85. text_end = text_begin + strlen(text_begin);
  86. ImGuiContext& g = *GImGui;
  87. ImFont* font = g.Font;
  88. // Align to be pixel perfect
  89. pos.x = IM_FLOOR(pos.x);
  90. pos.y = IM_FLOOR(pos.y);
  91. const float scale = g.FontSize / font->FontSize;
  92. // Measure the size of the text in unrotated coordinates
  93. ImVec2 text_size = font->CalcTextSizeA(g.FontSize, FLT_MAX, 0.0f, text_begin, text_end, nullptr);
  94. // Precompute sine and cosine of the angle (note: angle should be positive for rotation in ImGui)
  95. float cos_a = cosf(-angle);
  96. float sin_a = sinf(-angle);
  97. const char* s = text_begin;
  98. int chars_total = (int)(text_end - s);
  99. int chars_rendered = 0;
  100. const int vtx_count_max = chars_total * 4;
  101. const int idx_count_max = chars_total * 6;
  102. draw_list->PrimReserve(idx_count_max, vtx_count_max);
  103. // Adjust pen position to center the text
  104. ImVec2 pen = ImVec2(-text_size.x * 0.5f, -text_size.y * 0.5f);
  105. while (s < text_end) {
  106. unsigned int c = (unsigned int)*s;
  107. if (c < 0x80) {
  108. s += 1;
  109. } else {
  110. s += ImTextCharFromUtf8(&c, s, text_end);
  111. if (c == 0) // Malformed UTF-8?
  112. break;
  113. }
  114. const ImFontGlyph* glyph = font->FindGlyph((ImWchar)c);
  115. if (glyph == nullptr) {
  116. continue;
  117. }
  118. // Glyph dimensions and positions
  119. ImVec2 glyph_offset = ImVec2(glyph->X0, glyph->Y0) * scale;
  120. ImVec2 glyph_size = ImVec2(glyph->X1 - glyph->X0, glyph->Y1 - glyph->Y0) * scale;
  121. // Corners of the glyph quad in unrotated space
  122. ImVec2 corners[4];
  123. corners[0] = pen + glyph_offset;
  124. corners[1] = pen + glyph_offset + ImVec2(glyph_size.x, 0);
  125. corners[2] = pen + glyph_offset + glyph_size;
  126. corners[3] = pen + glyph_offset + ImVec2(0, glyph_size.y);
  127. // Rotate and translate the corners
  128. for (int i = 0; i < 4; i++) {
  129. float x = corners[i].x;
  130. float y = corners[i].y;
  131. corners[i].x = x * cos_a - y * sin_a + pos.x;
  132. corners[i].y = x * sin_a + y * cos_a + pos.y;
  133. }
  134. // Texture coordinates
  135. ImVec2 uv0 = ImVec2(glyph->U0, glyph->V0);
  136. ImVec2 uv1 = ImVec2(glyph->U1, glyph->V1);
  137. // Render the glyph quad
  138. draw_list->PrimQuadUV(corners[0], corners[1], corners[2], corners[3],
  139. uv0, ImVec2(glyph->U1, glyph->V0),
  140. uv1, ImVec2(glyph->U0, glyph->V1),
  141. col);
  142. // Advance the pen position
  143. pen.x += glyph->AdvanceX * scale;
  144. chars_rendered++;
  145. }
  146. // Return unused vertices
  147. int chars_skipped = chars_total - chars_rendered;
  148. draw_list->PrimUnreserve(chars_skipped * 6, chars_skipped * 4);
  149. }
  150. void AddTextCentered(ImDrawList* draw_list, ImVec2 top_center, ImU32 col, const char* text_begin) {
  151. const char* text_end = ImGui::FindRenderedTextEnd(text_begin);
  152. ImVec2 text_size = ImGui::CalcTextSize(text_begin, text_end, true);
  153. draw_list->AddText(ImVec2(top_center.x - text_size.x * 0.5f, top_center.y), col, text_begin, text_end);
  154. }
  155. //-----------------------------------------------------------------------------
  156. // [SECTION] Legend Utils
  157. //-----------------------------------------------------------------------------
  158. ImVec2 GetLocationPos(const ImRect& outer_rect, const ImVec2& inner_size, ImPlot3DLocation loc, const ImVec2& pad) {
  159. ImVec2 pos;
  160. // Legend x coordinate
  161. if (ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_West) && !ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_East))
  162. pos.x = outer_rect.Min.x + pad.x;
  163. else if (!ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_West) && ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_East))
  164. pos.x = outer_rect.Max.x - pad.x - inner_size.x;
  165. else
  166. pos.x = outer_rect.GetCenter().x - inner_size.x * 0.5f;
  167. // Legend y coordinate
  168. if (ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_North) && !ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_South))
  169. pos.y = outer_rect.Min.y + pad.y;
  170. else if (!ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_North) && ImPlot3D::ImHasFlag(loc, ImPlot3DLocation_South))
  171. pos.y = outer_rect.Max.y - pad.y - inner_size.y;
  172. else
  173. pos.y = outer_rect.GetCenter().y - inner_size.y * 0.5f;
  174. pos.x = IM_ROUND(pos.x);
  175. pos.y = IM_ROUND(pos.y);
  176. return pos;
  177. }
  178. ImVec2 CalcLegendSize(ImPlot3DItemGroup& items, const ImVec2& pad, const ImVec2& spacing, bool vertical) {
  179. const int nItems = items.GetLegendCount();
  180. const float txt_ht = ImGui::GetTextLineHeight();
  181. const float icon_size = txt_ht;
  182. // Get label max width
  183. float max_label_width = 0;
  184. float sum_label_width = 0;
  185. for (int i = 0; i < nItems; i++) {
  186. const char* label = items.GetLegendLabel(i);
  187. const float label_width = ImGui::CalcTextSize(label, nullptr, true).x;
  188. max_label_width = label_width > max_label_width ? label_width : max_label_width;
  189. sum_label_width += label_width;
  190. }
  191. // Compute legend size
  192. 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);
  193. return legend_size;
  194. }
  195. void ShowLegendEntries(ImPlot3DItemGroup& items, const ImRect& legend_bb, bool hovered, const ImVec2& pad, const ImVec2& spacing, bool vertical, ImDrawList& draw_list) {
  196. const float txt_ht = ImGui::GetTextLineHeight();
  197. const float icon_size = txt_ht;
  198. const float icon_shrink = 2;
  199. ImU32 col_txt = GetStyleColorU32(ImPlot3DCol_LegendText);
  200. ImU32 col_txt_dis = ImAlphaU32(col_txt, 0.25f);
  201. float sum_label_width = 0;
  202. const int num_items = items.GetLegendCount();
  203. if (num_items == 0)
  204. return;
  205. ImPlot3DContext& gp = *GImPlot3D;
  206. // Render legend items
  207. for (int i = 0; i < num_items; i++) {
  208. const int idx = i;
  209. ImPlot3DItem* item = items.GetLegendItem(idx);
  210. const char* label = items.GetLegendLabel(idx);
  211. const float label_width = ImGui::CalcTextSize(label, nullptr, true).x;
  212. 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);
  213. sum_label_width += label_width;
  214. ImRect icon_bb;
  215. icon_bb.Min = top_left + ImVec2(icon_shrink, icon_shrink);
  216. icon_bb.Max = top_left + ImVec2(icon_size - icon_shrink, icon_size - icon_shrink);
  217. ImRect label_bb;
  218. label_bb.Min = top_left;
  219. label_bb.Max = top_left + ImVec2(label_width + icon_size, icon_size);
  220. ImU32 col_txt_hl;
  221. ImU32 col_item = ImAlphaU32(item->Color, 1);
  222. ImRect button_bb(icon_bb.Min, label_bb.Max);
  223. ImGui::KeepAliveID(item->ID);
  224. bool item_hov = false;
  225. bool item_hld = false;
  226. bool item_clk = ImPlot3D::ImHasFlag(items.Legend.Flags, ImPlot3DLegendFlags_NoButtons)
  227. ? false
  228. : ImGui::ButtonBehavior(button_bb, item->ID, &item_hov, &item_hld);
  229. if (item_clk)
  230. item->Show = !item->Show;
  231. const bool hovering = item_hov && !ImPlot3D::ImHasFlag(items.Legend.Flags, ImPlot3DLegendFlags_NoHighlightItem);
  232. if (hovering) {
  233. item->LegendHovered = true;
  234. col_txt_hl = ImPlot3D::ImMixU32(col_txt, col_item, 64);
  235. } else {
  236. item->LegendHovered = false;
  237. col_txt_hl = ImGui::GetColorU32(col_txt);
  238. }
  239. ImU32 col_icon;
  240. if (item_hld)
  241. col_icon = item->Show ? ImAlphaU32(col_item, 0.5f) : ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.5f);
  242. else if (item_hov)
  243. col_icon = item->Show ? ImAlphaU32(col_item, 0.75f) : ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.75f);
  244. else
  245. col_icon = item->Show ? col_item : col_txt_dis;
  246. draw_list.AddRectFilled(icon_bb.Min, icon_bb.Max, col_icon);
  247. const char* text_display_end = ImGui::FindRenderedTextEnd(label, nullptr);
  248. if (label != text_display_end)
  249. draw_list.AddText(top_left + ImVec2(icon_size, 0), item->Show ? col_txt_hl : col_txt_dis, label, text_display_end);
  250. }
  251. }
  252. void RenderLegend() {
  253. ImPlot3DContext& gp = *GImPlot3D;
  254. ImPlot3DPlot& plot = *gp.CurrentPlot;
  255. if (ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_NoLegend) || plot.Items.GetLegendCount() == 0)
  256. return;
  257. ImGuiContext& g = *GImGui;
  258. ImGuiWindow* window = g.CurrentWindow;
  259. ImDrawList* draw_list = window->DrawList;
  260. const ImGuiIO& IO = ImGui::GetIO();
  261. ImPlot3DLegend& legend = plot.Items.Legend;
  262. const bool legend_horz = ImPlot3D::ImHasFlag(legend.Flags, ImPlot3DLegendFlags_Horizontal);
  263. const ImVec2 legend_size = CalcLegendSize(plot.Items, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !legend_horz);
  264. const ImVec2 legend_pos = GetLocationPos(plot.PlotRect,
  265. legend_size,
  266. legend.Location,
  267. gp.Style.LegendPadding);
  268. legend.Rect = ImRect(legend_pos, legend_pos + legend_size);
  269. // Test hover
  270. legend.Hovered = legend.Rect.Contains(IO.MousePos);
  271. // Render background
  272. ImU32 col_bg = GetStyleColorU32(ImPlot3DCol_LegendBg);
  273. ImU32 col_bd = GetStyleColorU32(ImPlot3DCol_LegendBorder);
  274. draw_list->AddRectFilled(legend.Rect.Min, legend.Rect.Max, col_bg);
  275. draw_list->AddRect(legend.Rect.Min, legend.Rect.Max, col_bd);
  276. // Render legends
  277. ShowLegendEntries(plot.Items, legend.Rect, legend.Hovered, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !legend_horz, *draw_list);
  278. }
  279. //-----------------------------------------------------------------------------
  280. // [SECTION] Mouse Position Utils
  281. //-----------------------------------------------------------------------------
  282. void RenderMousePos() {
  283. ImPlot3DContext& gp = *GImPlot3D;
  284. ImPlot3DPlot& plot = *gp.CurrentPlot;
  285. if (ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_NoMouseText))
  286. return;
  287. ImVec2 mouse_pos = ImGui::GetMousePos();
  288. ImPlot3DPoint mouse_plot_pos = PixelsToPlotPlane(mouse_pos, ImPlane3D_YZ, true);
  289. if (mouse_plot_pos.IsNaN())
  290. mouse_plot_pos = PixelsToPlotPlane(mouse_pos, ImPlane3D_XZ, true);
  291. if (mouse_plot_pos.IsNaN())
  292. mouse_plot_pos = PixelsToPlotPlane(mouse_pos, ImPlane3D_XY, true);
  293. char buff[IMPLOT3D_LABEL_MAX_SIZE];
  294. if (!mouse_plot_pos.IsNaN()) {
  295. ImGuiTextBuffer builder;
  296. builder.append("(");
  297. for (int i = 0; i < 3; i++) {
  298. ImPlot3DAxis& axis = plot.Axes[i];
  299. if (i > 0)
  300. builder.append(", ");
  301. axis.Formatter(mouse_plot_pos[i], buff, IMPLOT3D_LABEL_MAX_SIZE, axis.FormatterData);
  302. builder.append(buff);
  303. }
  304. builder.append(")");
  305. const ImVec2 size = ImGui::CalcTextSize(builder.c_str());
  306. // TODO custom location/padding
  307. const ImVec2 pos = GetLocationPos(plot.PlotRect, size, ImPlot3DLocation_SouthEast, ImVec2(10, 10));
  308. ImDrawList& draw_list = *ImGui::GetWindowDrawList();
  309. draw_list.AddText(pos, GetStyleColorU32(ImPlot3DCol_InlayText), builder.c_str());
  310. }
  311. }
  312. //-----------------------------------------------------------------------------
  313. // [SECTION] Plot Box Utils
  314. //-----------------------------------------------------------------------------
  315. // Faces of the box (defined by 4 corner indices)
  316. static const int faces[6][4] = {
  317. {0, 3, 7, 4}, // X-min face
  318. {0, 4, 5, 1}, // Y-min face
  319. {0, 1, 2, 3}, // Z-min face
  320. {1, 2, 6, 5}, // X-max face
  321. {3, 7, 6, 2}, // Y-max face
  322. {4, 5, 6, 7}, // Z-max face
  323. };
  324. // Edges of the box (defined by 2 corner indices)
  325. static const int edges[12][2] = {
  326. // Bottom face edges
  327. {0, 1},
  328. {1, 2},
  329. {2, 3},
  330. {3, 0},
  331. // Top face edges
  332. {4, 5},
  333. {5, 6},
  334. {6, 7},
  335. {7, 4},
  336. // Vertical edges
  337. {0, 4},
  338. {1, 5},
  339. {2, 6},
  340. {3, 7},
  341. };
  342. // Face edges (4 edge indices for each face)
  343. static const int face_edges[6][4] = {
  344. {3, 11, 8, 7}, // X-min face
  345. {0, 8, 4, 9}, // Y-min face
  346. {0, 1, 2, 3}, // Z-min face
  347. {1, 9, 5, 10}, // X-max face
  348. {2, 10, 6, 11}, // Y-max face
  349. {4, 5, 6, 7}, // Z-max face
  350. };
  351. // Lookup table for axis_corners based on active_faces (3D plot)
  352. static const int axis_corners_lookup_3d[8][3][2] = {
  353. // Index 0: active_faces = {0, 0, 0}
  354. {{3, 2}, {1, 2}, {1, 5}},
  355. // Index 1: active_faces = {0, 0, 1}
  356. {{7, 6}, {5, 6}, {1, 5}},
  357. // Index 2: active_faces = {0, 1, 0}
  358. {{0, 1}, {1, 2}, {2, 6}},
  359. // Index 3: active_faces = {0, 1, 1}
  360. {{4, 5}, {5, 6}, {2, 6}},
  361. // Index 4: active_faces = {1, 0, 0}
  362. {{3, 2}, {0, 3}, {0, 4}},
  363. // Index 5: active_faces = {1, 0, 1}
  364. {{7, 6}, {4, 7}, {0, 4}},
  365. // Index 6: active_faces = {1, 1, 0}
  366. {{0, 1}, {0, 3}, {3, 7}},
  367. // Index 7: active_faces = {1, 1, 1}
  368. {{4, 5}, {4, 7}, {3, 7}},
  369. };
  370. int GetMouseOverPlane(const ImPlot3DPlot& plot, const bool* active_faces, const ImVec2* corners_pix, int* plane_out = nullptr) {
  371. ImGuiIO& io = ImGui::GetIO();
  372. ImVec2 mouse_pos = io.MousePos;
  373. if (plane_out)
  374. *plane_out = -1;
  375. // Check each active face
  376. for (int a = 0; a < 3; a++) {
  377. int face_idx = a + 3 * active_faces[a];
  378. ImVec2 p0 = corners_pix[faces[face_idx][0]];
  379. ImVec2 p1 = corners_pix[faces[face_idx][1]];
  380. ImVec2 p2 = corners_pix[faces[face_idx][2]];
  381. ImVec2 p3 = corners_pix[faces[face_idx][3]];
  382. // Check if the mouse is inside the face's quad (using a triangle check)
  383. if (ImTriangleContainsPoint(p0, p1, p2, mouse_pos) || ImTriangleContainsPoint(p2, p3, p0, mouse_pos)) {
  384. if (plane_out)
  385. *plane_out = a;
  386. return a; // Return the plane index: 0 -> YZ, 1 -> XZ, 2 -> XY
  387. }
  388. }
  389. return -1; // Not over any active plane
  390. }
  391. int GetMouseOverAxis(const ImPlot3DPlot& plot, const bool* active_faces, const ImVec2* corners_pix, const int plane_2d, int* edge_out = nullptr) {
  392. const float axis_proximity_threshold = 15.0f; // Distance in pixels to consider the mouse "close" to an axis
  393. ImGuiIO& io = ImGui::GetIO();
  394. ImVec2 mouse_pos = io.MousePos;
  395. if (edge_out)
  396. *edge_out = -1;
  397. bool visible_edges[12];
  398. for (int i = 0; i < 12; i++)
  399. visible_edges[i] = false;
  400. for (int a = 0; a < 3; a++) {
  401. int face_idx = a + 3 * active_faces[a];
  402. if (plane_2d != -1 && a != plane_2d)
  403. continue;
  404. for (size_t i = 0; i < 4; i++)
  405. visible_edges[face_edges[face_idx][i]] = true;
  406. }
  407. // Check each edge for proximity to the mouse
  408. for (int edge = 0; edge < 12; edge++) {
  409. if (!visible_edges[edge])
  410. continue;
  411. ImVec2 p0 = corners_pix[edges[edge][0]];
  412. ImVec2 p1 = corners_pix[edges[edge][1]];
  413. // Check distance to the edge
  414. ImVec2 closest_point = ImLineClosestPoint(p0, p1, mouse_pos);
  415. float dist = ImLengthSqr(mouse_pos - closest_point);
  416. if (dist <= axis_proximity_threshold) {
  417. if (edge_out)
  418. *edge_out = edge;
  419. // Determine which axis the edge belongs to
  420. if (edge == 0 || edge == 2 || edge == 4 || edge == 6)
  421. return 0; // X-axis
  422. else if (edge == 1 || edge == 3 || edge == 5 || edge == 7)
  423. return 1; // Y-axis
  424. else
  425. return 2; // Z-axis
  426. }
  427. }
  428. return -1; // Not over any axis
  429. }
  430. void RenderPlotBackground(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImVec2* corners_pix, const bool* active_faces, const int plane_2d) {
  431. const ImVec4 col_bg = GetStyleColorVec4(ImPlot3DCol_PlotBg);
  432. const ImVec4 col_bg_hov = col_bg + ImVec4(0.03, 0.03, 0.03, 0.0);
  433. int hovered_plane = -1;
  434. if (!plot.Held) {
  435. // If the mouse is not held, highlight plane hovering when mouse over it
  436. hovered_plane = GetMouseOverPlane(plot, active_faces, corners_pix);
  437. if (GetMouseOverAxis(plot, active_faces, corners_pix, plane_2d) != -1)
  438. hovered_plane = -1;
  439. } else {
  440. // If the mouse is held, highlight the held plane
  441. hovered_plane = plot.HeldPlaneIdx;
  442. }
  443. for (int a = 0; a < 3; a++) {
  444. int idx[4]; // Corner indices
  445. for (int i = 0; i < 4; i++)
  446. idx[i] = faces[a + 3 * active_faces[a]][i];
  447. const ImU32 col = ImGui::ColorConvertFloat4ToU32((hovered_plane == a) ? col_bg_hov : col_bg);
  448. draw_list->AddQuadFilled(corners_pix[idx[0]], corners_pix[idx[1]], corners_pix[idx[2]], corners_pix[idx[3]], col);
  449. }
  450. }
  451. void RenderPlotBorder(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImVec2* corners_pix, const bool* active_faces, const int plane_2d) {
  452. ImGuiIO& io = ImGui::GetIO();
  453. int hovered_edge = -1;
  454. if (!plot.Held)
  455. GetMouseOverAxis(plot, active_faces, corners_pix, plane_2d, &hovered_edge);
  456. else
  457. hovered_edge = plot.HeldEdgeIdx;
  458. bool render_edge[12];
  459. for (int i = 0; i < 12; i++)
  460. render_edge[i] = false;
  461. for (int a = 0; a < 3; a++) {
  462. int face_idx = a + 3 * active_faces[a];
  463. if (plane_2d != -1 && a != plane_2d)
  464. continue;
  465. for (size_t i = 0; i < 4; i++)
  466. render_edge[face_edges[face_idx][i]] = true;
  467. }
  468. ImU32 col_bd = GetStyleColorU32(ImPlot3DCol_PlotBorder);
  469. for (int i = 0; i < 12; i++) {
  470. if (render_edge[i]) {
  471. int idx0 = edges[i][0];
  472. int idx1 = edges[i][1];
  473. float thickness = i == hovered_edge ? 3.0f : 1.0f;
  474. draw_list->AddLine(corners_pix[idx0], corners_pix[idx1], col_bd, thickness);
  475. }
  476. }
  477. }
  478. void RenderGrid(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint* corners, const bool* active_faces, const int plane_2d) {
  479. ImVec4 col_grid = GetStyleColorVec4(ImPlot3DCol_AxisGrid);
  480. ImU32 col_grid_minor = ImGui::GetColorU32(col_grid * ImVec4(1, 1, 1, 0.3f));
  481. ImU32 col_grid_major = ImGui::GetColorU32(col_grid * ImVec4(1, 1, 1, 0.6f));
  482. for (int face = 0; face < 3; face++) {
  483. if (plane_2d != -1 && face != plane_2d)
  484. continue;
  485. int face_idx = face + 3 * active_faces[face];
  486. const ImPlot3DAxis& axis_u = plot.Axes[(face + 1) % 3];
  487. const ImPlot3DAxis& axis_v = plot.Axes[(face + 2) % 3];
  488. // Get the two axes (u and v) that define the face plane
  489. int idx0 = faces[face_idx][0];
  490. int idx1 = faces[face_idx][1];
  491. int idx2 = faces[face_idx][2];
  492. int idx3 = faces[face_idx][3];
  493. // Corners of the face in plot space
  494. ImPlot3DPoint p0 = corners[idx0];
  495. ImPlot3DPoint p1 = corners[idx1];
  496. ImPlot3DPoint p2 = corners[idx2];
  497. ImPlot3DPoint p3 = corners[idx3];
  498. // Vectors along the edges
  499. ImPlot3DPoint u_vec = p1 - p0;
  500. ImPlot3DPoint v_vec = p3 - p0;
  501. // Render grid lines along u axis (axis_u)
  502. if (!ImPlot3D::ImHasFlag(axis_u.Flags, ImPlot3DAxisFlags_NoGridLines))
  503. for (int t = 0; t < axis_u.Ticker.TickCount(); ++t) {
  504. const ImPlot3DTick& tick = axis_u.Ticker.Ticks[t];
  505. // Compute position along u
  506. float t_u = (tick.PlotPos - axis_u.Range.Min) / (axis_u.Range.Max - axis_u.Range.Min);
  507. ImPlot3DPoint p_start = p0 + u_vec * t_u;
  508. ImPlot3DPoint p_end = p3 + u_vec * t_u;
  509. // Convert to pixel coordinates
  510. ImVec2 p_start_pix = PlotToPixels(p_start);
  511. ImVec2 p_end_pix = PlotToPixels(p_end);
  512. // Get color
  513. ImU32 col_line = tick.Major ? col_grid_major : col_grid_minor;
  514. // Draw the grid line
  515. draw_list->AddLine(p_start_pix, p_end_pix, col_line);
  516. }
  517. // Render grid lines along v axis (axis_v)
  518. if (!ImPlot3D::ImHasFlag(axis_v.Flags, ImPlot3DAxisFlags_NoGridLines))
  519. for (int t = 0; t < axis_v.Ticker.TickCount(); ++t) {
  520. const ImPlot3DTick& tick = axis_v.Ticker.Ticks[t];
  521. // Compute position along v
  522. float t_v = (tick.PlotPos - axis_v.Range.Min) / (axis_v.Range.Max - axis_v.Range.Min);
  523. ImPlot3DPoint p_start = p0 + v_vec * t_v;
  524. ImPlot3DPoint p_end = p1 + v_vec * t_v;
  525. // Convert to pixel coordinates
  526. ImVec2 p_start_pix = PlotToPixels(p_start);
  527. ImVec2 p_end_pix = PlotToPixels(p_end);
  528. // Get color
  529. ImU32 col_line = tick.Major ? col_grid_major : col_grid_minor;
  530. // Draw the grid line
  531. draw_list->AddLine(p_start_pix, p_end_pix, col_line);
  532. }
  533. }
  534. }
  535. 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) {
  536. ImU32 col_tick = GetStyleColorU32(ImPlot3DCol_AxisTick);
  537. auto DeterminePlaneForAxis = [&](int axis_idx) {
  538. if (plane_2d != -1)
  539. return plane_2d;
  540. // If no plane chosen (-1), use:
  541. // X or Y axis -> XY plane (2)
  542. // Z axis -> YZ plane (0)
  543. if (axis_idx == 2)
  544. return 1; // Z-axis use XZ plane
  545. else
  546. return 2; // X or Y-axis use XY plane
  547. };
  548. for (int a = 0; a < 3; a++) {
  549. const ImPlot3DAxis& axis = plot.Axes[a];
  550. if (ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_NoTickMarks))
  551. continue;
  552. int idx0 = axis_corners[a][0];
  553. int idx1 = axis_corners[a][1];
  554. if (idx0 == idx1) // axis not visible or invalid
  555. continue;
  556. ImPlot3DPoint axis_start = corners[idx0];
  557. ImPlot3DPoint axis_end = corners[idx1];
  558. ImPlot3DPoint axis_dir = axis_end - axis_start;
  559. float axis_len = axis_dir.Length();
  560. if (axis_len < 1e-12f)
  561. continue;
  562. axis_dir /= axis_len;
  563. // Draw axis line
  564. ImVec2 axis_start_pix = corners_pix[idx0];
  565. ImVec2 axis_end_pix = corners_pix[idx1];
  566. draw_list->AddLine(axis_start_pix, axis_end_pix, col_tick);
  567. // Choose plane
  568. int chosen_plane = DeterminePlaneForAxis(a);
  569. // Project axis_dir onto chosen plane
  570. ImPlot3DPoint proj_dir = axis_dir;
  571. if (chosen_plane == 0) {
  572. // YZ plane: zero out x
  573. proj_dir.x = 0.0f;
  574. } else if (chosen_plane == 1) {
  575. // XZ plane: zero out y
  576. proj_dir.y = 0.0f;
  577. } else if (chosen_plane == 2) {
  578. // XY plane: zero out z
  579. proj_dir.z = 0.0f;
  580. }
  581. float proj_len = proj_dir.Length();
  582. if (proj_len < 1e-12f) {
  583. // Axis is parallel to plane normal or something degenerate, skip ticks
  584. continue;
  585. }
  586. proj_dir /= proj_len;
  587. // Rotate 90 degrees in chosen plane
  588. ImPlot3DPoint tick_dir;
  589. if (chosen_plane == 0) {
  590. // YZ plane
  591. // proj_dir=(0,py,pz), rotate 90°: (py,pz) -> (-pz,py)
  592. tick_dir = ImPlot3DPoint(0, -proj_dir.z, proj_dir.y);
  593. } else if (chosen_plane == 1) {
  594. // XZ plane (plane=1)
  595. // proj_dir=(px,0,pz), rotate 90°: (px,pz) -> (-pz,px)
  596. tick_dir = ImPlot3DPoint(-proj_dir.z, 0, proj_dir.x);
  597. } else {
  598. // XY plane
  599. // proj_dir=(px,py,0), rotate by 90°: (px,py) -> (-py,px)
  600. tick_dir = ImPlot3DPoint(-proj_dir.y, proj_dir.x, 0);
  601. }
  602. tick_dir.Normalize();
  603. // Tick lengths in NDC units
  604. const float major_size_ndc = 0.06f;
  605. const float minor_size_ndc = 0.03f;
  606. for (int t = 0; t < axis.Ticker.TickCount(); ++t) {
  607. const ImPlot3DTick& tick = axis.Ticker.Ticks[t];
  608. float v = (tick.PlotPos - axis.Range.Min) / (axis.Range.Max - axis.Range.Min);
  609. ImPlot3DPoint tick_pos_ndc = PlotToNDC(axis_start + axis_dir * (v * axis_len));
  610. // Half tick on each side of the axis line
  611. float size_tick_ndc = tick.Major ? major_size_ndc : minor_size_ndc;
  612. ImPlot3DPoint half_tick_ndc = tick_dir * (size_tick_ndc * 0.5f);
  613. ImPlot3DPoint T1_ndc = tick_pos_ndc - half_tick_ndc;
  614. ImPlot3DPoint T2_ndc = tick_pos_ndc + half_tick_ndc;
  615. ImVec2 T1_screen = NDCToPixels(T1_ndc);
  616. ImVec2 T2_screen = NDCToPixels(T2_ndc);
  617. draw_list->AddLine(T1_screen, T2_screen, col_tick);
  618. }
  619. }
  620. }
  621. void RenderTickLabels(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint* corners, const ImVec2* corners_pix, const int axis_corners[3][2]) {
  622. ImVec2 box_center_pix = PlotToPixels(plot.RangeCenter());
  623. ImU32 col_tick_txt = GetStyleColorU32(ImPlot3DCol_AxisText);
  624. for (int a = 0; a < 3; a++) {
  625. const ImPlot3DAxis& axis = plot.Axes[a];
  626. if (ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_NoTickLabels))
  627. continue;
  628. // Corner indices for this axis
  629. int idx0 = axis_corners[a][0];
  630. int idx1 = axis_corners[a][1];
  631. // If normal to the 2D plot, ignore the ticks
  632. if (idx0 == idx1)
  633. continue;
  634. // Start and end points of the axis in plot space
  635. ImPlot3DPoint axis_start = corners[idx0];
  636. ImPlot3DPoint axis_end = corners[idx1];
  637. // Direction vector along the axis
  638. ImPlot3DPoint axis_dir = axis_end - axis_start;
  639. // Convert axis start and end to screen space
  640. ImVec2 axis_start_pix = corners_pix[idx0];
  641. ImVec2 axis_end_pix = corners_pix[idx1];
  642. // Screen space axis direction
  643. ImVec2 axis_screen_dir = axis_end_pix - axis_start_pix;
  644. float axis_length = ImSqrt(ImLengthSqr(axis_screen_dir));
  645. if (axis_length != 0.0f)
  646. axis_screen_dir /= axis_length;
  647. else
  648. axis_screen_dir = ImVec2(1.0f, 0.0f); // Default direction if length is zero
  649. // Perpendicular direction in screen space
  650. ImVec2 offset_dir_pix = ImVec2(-axis_screen_dir.y, axis_screen_dir.x);
  651. // Make sure direction points away from cube center
  652. ImVec2 box_center_pix = PlotToPixels(plot.RangeCenter());
  653. ImVec2 axis_center_pix = (axis_start_pix + axis_end_pix) * 0.5f;
  654. ImVec2 center_to_axis_pix = axis_center_pix - box_center_pix;
  655. center_to_axis_pix /= ImSqrt(ImLengthSqr(center_to_axis_pix));
  656. if (ImDot(offset_dir_pix, center_to_axis_pix) < 0.0f)
  657. offset_dir_pix = -offset_dir_pix;
  658. // Adjust the offset magnitude
  659. float offset_magnitude = 20.0f; // TODO Calculate based on label size
  660. ImVec2 offset_pix = offset_dir_pix * offset_magnitude;
  661. // Compute angle perpendicular to axis in screen space
  662. float angle = atan2f(-axis_screen_dir.y, axis_screen_dir.x) + IM_PI * 0.5f;
  663. // Normalize angle to be between -π and π
  664. if (angle > IM_PI)
  665. angle -= 2 * IM_PI;
  666. if (angle < -IM_PI)
  667. angle += 2 * IM_PI;
  668. // Adjust angle to keep labels upright
  669. if (angle > IM_PI * 0.5f)
  670. angle -= IM_PI;
  671. if (angle < -IM_PI * 0.5f)
  672. angle += IM_PI;
  673. // Loop over ticks
  674. for (int t = 0; t < axis.Ticker.TickCount(); ++t) {
  675. const ImPlot3DTick& tick = axis.Ticker.Ticks[t];
  676. if (!tick.ShowLabel)
  677. continue;
  678. // Compute position along the axis
  679. float t_axis = (tick.PlotPos - axis.Range.Min) / (axis.Range.Max - axis.Range.Min);
  680. ImPlot3DPoint tick_pos = axis_start + axis_dir * t_axis;
  681. // Convert to pixel coordinates
  682. ImVec2 tick_pos_pix = PlotToPixels(tick_pos);
  683. // Get the tick label text
  684. const char* label = axis.Ticker.GetText(tick);
  685. // Adjust label position by offset
  686. ImVec2 label_pos_pix = tick_pos_pix + offset_pix;
  687. // Render the tick label
  688. AddTextRotated(draw_list, label_pos_pix, angle, col_tick_txt, label);
  689. }
  690. }
  691. }
  692. void RenderAxisLabels(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint* corners, const ImVec2* corners_pix, const int axis_corners[3][2]) {
  693. ImPlot3DPoint range_center = plot.RangeCenter();
  694. for (int a = 0; a < 3; a++) {
  695. const ImPlot3DAxis& axis = plot.Axes[a];
  696. if (!axis.HasLabel())
  697. continue;
  698. const char* label = axis.GetLabel();
  699. // Corner indices
  700. int idx0 = axis_corners[a][0];
  701. int idx1 = axis_corners[a][1];
  702. // If normal to the 2D plot, ignore axis label
  703. if (idx0 == idx1)
  704. continue;
  705. // Position at the end of the axis
  706. ImPlot3DPoint label_pos = (corners[idx0] + corners[idx1]) * 0.5f;
  707. // Add offset
  708. label_pos += (label_pos - range_center) * 0.4f;
  709. // Convert to pixel coordinates
  710. ImVec2 label_pos_pix = PlotToPixels(label_pos);
  711. // Adjust label position and angle
  712. ImU32 col_ax_txt = GetStyleColorU32(ImPlot3DCol_AxisText);
  713. // Compute text angle
  714. ImVec2 screen_delta = corners_pix[idx1] - corners_pix[idx0];
  715. float angle = atan2f(-screen_delta.y, screen_delta.x);
  716. if (angle > IM_PI * 0.5f)
  717. angle -= IM_PI;
  718. if (angle < -IM_PI * 0.5f)
  719. angle += IM_PI;
  720. AddTextRotated(draw_list, label_pos_pix, angle, col_ax_txt, label);
  721. }
  722. }
  723. // Function to compute active faces based on the rotation
  724. // If the plot is close to 2D, plane_2d is set to the plane index (0 -> YZ, 1 -> XZ, 2 -> XY)
  725. // plane_2d is set to -1 otherwise
  726. void ComputeActiveFaces(bool* active_faces, const ImPlot3DQuat& rotation, int* plane_2d = nullptr) {
  727. if (plane_2d)
  728. *plane_2d = -1;
  729. ImPlot3DPoint rot_face_n[3] = {
  730. rotation * ImPlot3DPoint(1.0f, 0.0f, 0.0f),
  731. rotation * ImPlot3DPoint(0.0f, 1.0f, 0.0f),
  732. rotation * ImPlot3DPoint(0.0f, 0.0f, 1.0f),
  733. };
  734. int num_deg = 0; // Check number of planes that are degenerate (seen as a line)
  735. for (int i = 0; i < 3; ++i) {
  736. // Determine the active face based on the Z component
  737. if (fabs(rot_face_n[i].z) < 0.025) {
  738. // If aligned with the plane, choose the min face for bottom/left
  739. active_faces[i] = rot_face_n[i].x + rot_face_n[i].y < 0.0f;
  740. num_deg++;
  741. } else {
  742. // Otherwise, determine based on the Z component
  743. active_faces[i] = rot_face_n[i].z < 0.0f;
  744. // Set this plane as possible 2d plane
  745. if (plane_2d)
  746. *plane_2d = i;
  747. }
  748. }
  749. // Only return 2d plane if there are exactly 2 degenerate planes
  750. if (num_deg != 2 && plane_2d)
  751. *plane_2d = -1;
  752. }
  753. // Function to compute the box corners in plot space
  754. void ComputeBoxCorners(ImPlot3DPoint* corners, const ImPlot3DPoint& range_min, const ImPlot3DPoint& range_max) {
  755. corners[0] = ImPlot3DPoint(range_min.x, range_min.y, range_min.z); // 0
  756. corners[1] = ImPlot3DPoint(range_max.x, range_min.y, range_min.z); // 1
  757. corners[2] = ImPlot3DPoint(range_max.x, range_max.y, range_min.z); // 2
  758. corners[3] = ImPlot3DPoint(range_min.x, range_max.y, range_min.z); // 3
  759. corners[4] = ImPlot3DPoint(range_min.x, range_min.y, range_max.z); // 4
  760. corners[5] = ImPlot3DPoint(range_max.x, range_min.y, range_max.z); // 5
  761. corners[6] = ImPlot3DPoint(range_max.x, range_max.y, range_max.z); // 6
  762. corners[7] = ImPlot3DPoint(range_min.x, range_max.y, range_max.z); // 7
  763. }
  764. // Function to compute the box corners in pixel space
  765. void ComputeBoxCornersPix(ImVec2* corners_pix, const ImPlot3DPoint* corners) {
  766. for (int i = 0; i < 8; i++) {
  767. corners_pix[i] = PlotToPixels(corners[i]);
  768. }
  769. }
  770. void RenderPlotBox(ImDrawList* draw_list, const ImPlot3DPlot& plot) {
  771. // Get plot parameters
  772. const ImRect& plot_area = plot.PlotRect;
  773. const ImPlot3DQuat& rotation = plot.Rotation;
  774. ImPlot3DPoint range_min = plot.RangeMin();
  775. ImPlot3DPoint range_max = plot.RangeMax();
  776. ImPlot3DPoint range_center = plot.RangeCenter();
  777. // Compute active faces
  778. bool active_faces[3];
  779. int plane_2d = -1;
  780. ComputeActiveFaces(active_faces, rotation, &plane_2d);
  781. bool is_2d = plane_2d != -1;
  782. // Compute box corners in plot space
  783. ImPlot3DPoint corners[8];
  784. ComputeBoxCorners(corners, range_min, range_max);
  785. // Compute box corners in pixel space
  786. ImVec2 corners_pix[8];
  787. ComputeBoxCornersPix(corners_pix, corners);
  788. // Compute axes start and end corners (given current rotation)
  789. int axis_corners[3][2];
  790. if (is_2d) {
  791. int face = plane_2d + 3 * active_faces[plane_2d]; // Face of the 2D plot
  792. int common_edges[2] = {-1, -1}; // Edges shared by the 3 faces
  793. // Find the common edges between the 3 faces
  794. for (int i = 0; i < 4; i++) {
  795. int edge = face_edges[face][i];
  796. for (int j = 0; j < 2; j++) {
  797. int axis = (plane_2d + 1 + j) % 3;
  798. int face_idx = axis + active_faces[axis] * 3;
  799. for (int k = 0; k < 4; k++) {
  800. if (face_edges[face_idx][k] == edge) {
  801. common_edges[j] = edge;
  802. break;
  803. }
  804. }
  805. }
  806. }
  807. // Get corners from 2 edges (origin is the corner in common)
  808. int origin_corner = -1;
  809. int x_corner = -1;
  810. int y_corner = -1;
  811. for (int i = 0; i < 2; i++)
  812. for (int j = 0; j < 2; j++)
  813. if (edges[common_edges[0]][i] == edges[common_edges[1]][j]) {
  814. origin_corner = edges[common_edges[0]][i];
  815. x_corner = edges[common_edges[0]][!i];
  816. y_corner = edges[common_edges[1]][!j];
  817. }
  818. // Swap x and y if they are flipped
  819. ImVec2 x_vec = corners_pix[x_corner] - corners_pix[origin_corner];
  820. ImVec2 y_vec = corners_pix[y_corner] - corners_pix[origin_corner];
  821. if (y_vec.x > x_vec.x)
  822. ImSwap(x_corner, y_corner);
  823. // Check which 3d axis the 2d axis refers to
  824. ImPlot3DPoint origin_3d = corners[origin_corner];
  825. ImPlot3DPoint x_3d = (corners[x_corner] - origin_3d).Normalized();
  826. ImPlot3DPoint y_3d = (corners[y_corner] - origin_3d).Normalized();
  827. int x_axis = -1;
  828. bool x_inverted = false;
  829. int y_axis = -1;
  830. bool y_inverted = false;
  831. for (int i = 0; i < 2; i++) {
  832. int axis_i = (plane_2d + 1 + i) % 3;
  833. if (y_axis != -1 || (ImAbs(x_3d[axis_i]) > 1e-8f && x_axis == -1)) {
  834. x_axis = axis_i;
  835. x_inverted = x_3d[axis_i] < 0.0f;
  836. } else {
  837. y_axis = axis_i;
  838. y_inverted = y_3d[axis_i] < 0.0f;
  839. }
  840. }
  841. // Set the 3d axis corners based on the 2d axis corners
  842. axis_corners[plane_2d][0] = -1;
  843. axis_corners[plane_2d][1] = -1;
  844. if (x_inverted) {
  845. axis_corners[x_axis][0] = x_corner;
  846. axis_corners[x_axis][1] = origin_corner;
  847. } else {
  848. axis_corners[x_axis][0] = origin_corner;
  849. axis_corners[x_axis][1] = x_corner;
  850. }
  851. if (y_inverted) {
  852. axis_corners[y_axis][0] = y_corner;
  853. axis_corners[y_axis][1] = origin_corner;
  854. } else {
  855. axis_corners[y_axis][0] = origin_corner;
  856. axis_corners[y_axis][1] = y_corner;
  857. }
  858. } else {
  859. int index = (active_faces[0] << 2) | (active_faces[1] << 1) | (active_faces[2]);
  860. for (int a = 0; a < 3; a++) {
  861. axis_corners[a][0] = axis_corners_lookup_3d[index][a][0];
  862. axis_corners[a][1] = axis_corners_lookup_3d[index][a][1];
  863. }
  864. }
  865. // Render components
  866. RenderPlotBackground(draw_list, plot, corners_pix, active_faces, plane_2d);
  867. RenderPlotBorder(draw_list, plot, corners_pix, active_faces, plane_2d);
  868. RenderGrid(draw_list, plot, corners, active_faces, plane_2d);
  869. RenderTickMarks(draw_list, plot, corners, corners_pix, axis_corners, plane_2d);
  870. RenderTickLabels(draw_list, plot, corners, corners_pix, axis_corners);
  871. RenderAxisLabels(draw_list, plot, corners, corners_pix, axis_corners);
  872. }
  873. //-----------------------------------------------------------------------------
  874. // [SECTION] Formatter
  875. //-----------------------------------------------------------------------------
  876. int Formatter_Default(float value, char* buff, int size, void* data) {
  877. char* fmt = (char*)data;
  878. return ImFormatString(buff, size, fmt, value);
  879. }
  880. //------------------------------------------------------------------------------
  881. // [SECTION] Locator
  882. //------------------------------------------------------------------------------
  883. double NiceNum(double x, bool round) {
  884. double f;
  885. double nf;
  886. int expv = (int)floor(ImLog10(x));
  887. f = x / ImPow(10.0, (double)expv);
  888. if (round)
  889. if (f < 1.5)
  890. nf = 1;
  891. else if (f < 3)
  892. nf = 2;
  893. else if (f < 7)
  894. nf = 5;
  895. else
  896. nf = 10;
  897. else if (f <= 1)
  898. nf = 1;
  899. else if (f <= 2)
  900. nf = 2;
  901. else if (f <= 5)
  902. nf = 5;
  903. else
  904. nf = 10;
  905. return nf * ImPow(10.0, expv);
  906. }
  907. void Locator_Default(ImPlot3DTicker& ticker, const ImPlot3DRange& range, ImPlot3DFormatter formatter, void* formatter_data) {
  908. if (range.Min == range.Max)
  909. return;
  910. const int nMinor = 5;
  911. const int nMajor = 3;
  912. const int max_ticks_labels = 7;
  913. const double nice_range = NiceNum(range.Size() * 0.99, false);
  914. const double interval = NiceNum(nice_range / (nMajor - 1), true);
  915. const double graphmin = floor(range.Min / interval) * interval;
  916. const double graphmax = ceil(range.Max / interval) * interval;
  917. bool first_major_set = false;
  918. int first_major_idx = 0;
  919. const int idx0 = ticker.TickCount(); // ticker may have user custom ticks
  920. ImVec2 total_size(0, 0);
  921. for (double major = graphmin; major < graphmax + 0.5 * interval; major += interval) {
  922. // is this zero? combat zero formatting issues
  923. if (major - interval < 0 && major + interval > 0)
  924. major = 0;
  925. if (range.Contains(major)) {
  926. if (!first_major_set) {
  927. first_major_idx = ticker.TickCount();
  928. first_major_set = true;
  929. }
  930. total_size += ticker.AddTick(major, true, true, formatter, formatter_data).LabelSize;
  931. }
  932. for (int i = 1; i < nMinor; ++i) {
  933. double minor = major + i * interval / nMinor;
  934. if (range.Contains(minor)) {
  935. total_size += ticker.AddTick(minor, false, true, formatter, formatter_data).LabelSize;
  936. }
  937. }
  938. }
  939. // Prune tick labels
  940. if (ticker.TickCount() > max_ticks_labels) {
  941. for (int i = first_major_idx - 1; i >= idx0; i -= 2)
  942. ticker.Ticks[i].ShowLabel = false;
  943. for (int i = first_major_idx + 1; i < ticker.TickCount(); i += 2)
  944. ticker.Ticks[i].ShowLabel = false;
  945. }
  946. }
  947. //------------------------------------------------------------------------------
  948. // [SECTION] Context Menus
  949. //------------------------------------------------------------------------------
  950. bool ShowLegendContextMenu(ImPlot3DLegend& legend, bool visible) {
  951. const float s = ImGui::GetFrameHeight();
  952. bool ret = false;
  953. if (ImGui::Checkbox("Show", &visible))
  954. ret = true;
  955. if (ImGui::RadioButton("H", ImPlot3D::ImHasFlag(legend.Flags, ImPlot3DLegendFlags_Horizontal)))
  956. legend.Flags |= ImPlot3DLegendFlags_Horizontal;
  957. ImGui::SameLine();
  958. if (ImGui::RadioButton("V", !ImPlot3D::ImHasFlag(legend.Flags, ImPlot3DLegendFlags_Horizontal)))
  959. legend.Flags &= ~ImPlot3DLegendFlags_Horizontal;
  960. ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 2));
  961. // clang-format off
  962. if (ImGui::Button("NW",ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_NorthWest; } ImGui::SameLine();
  963. if (ImGui::Button("N", ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_North; } ImGui::SameLine();
  964. if (ImGui::Button("NE",ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_NorthEast; }
  965. if (ImGui::Button("W", ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_West; } ImGui::SameLine();
  966. if (ImGui::InvisibleButton("C", ImVec2(1.5f*s,s))) { } ImGui::SameLine();
  967. if (ImGui::Button("E", ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_East; }
  968. if (ImGui::Button("SW",ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_SouthWest; } ImGui::SameLine();
  969. if (ImGui::Button("S", ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_South; } ImGui::SameLine();
  970. if (ImGui::Button("SE",ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_SouthEast; }
  971. // clang-format on
  972. ImGui::PopStyleVar();
  973. return ret;
  974. }
  975. void ShowAxisContextMenu(ImPlot3DAxis& axis) {
  976. ImGui::PushItemWidth(75);
  977. bool always_locked = axis.IsRangeLocked() || axis.IsAutoFitting();
  978. bool label = axis.HasLabel();
  979. bool grid = axis.HasGridLines();
  980. bool ticks = axis.HasTickMarks();
  981. bool labels = axis.HasTickLabels();
  982. double drag_speed = (axis.Range.Size() <= FLT_EPSILON) ? FLT_EPSILON * 1.0e+13 : 0.01 * axis.Range.Size(); // recover from almost equal axis limits.
  983. ImGui::BeginDisabled(always_locked);
  984. ImGui::CheckboxFlags("##LockMin", (unsigned int*)&axis.Flags, ImPlot3DAxisFlags_LockMin);
  985. ImGui::EndDisabled();
  986. ImGui::SameLine();
  987. ImGui::BeginDisabled(axis.IsLockedMin() || always_locked);
  988. float temp_min = axis.Range.Min;
  989. if (ImGui::DragFloat("Min", &temp_min, (float)drag_speed, -HUGE_VAL, axis.Range.Max - FLT_EPSILON)) {
  990. axis.SetMin(temp_min, true);
  991. }
  992. ImGui::EndDisabled();
  993. ImGui::BeginDisabled(always_locked);
  994. ImGui::CheckboxFlags("##LockMax", (unsigned int*)&axis.Flags, ImPlot3DAxisFlags_LockMax);
  995. ImGui::EndDisabled();
  996. ImGui::SameLine();
  997. ImGui::BeginDisabled(axis.IsLockedMax() || always_locked);
  998. float temp_max = axis.Range.Max;
  999. if (ImGui::DragFloat("Max", &temp_max, (float)drag_speed, axis.Range.Min + FLT_EPSILON, HUGE_VAL)) {
  1000. axis.SetMax(temp_max, true);
  1001. }
  1002. ImGui::EndDisabled();
  1003. ImGui::Separator();
  1004. // Flags
  1005. ImGui::CheckboxFlags("Auto-Fit", (unsigned int*)&axis.Flags, ImPlot3DAxisFlags_AutoFit);
  1006. ImGui::Separator();
  1007. ImGui::BeginDisabled(axis.Label.empty());
  1008. if (ImGui::Checkbox("Label", &label))
  1009. ImFlipFlag(axis.Flags, ImPlot3DAxisFlags_NoLabel);
  1010. ImGui::EndDisabled();
  1011. if (ImGui::Checkbox("Grid Lines", &grid))
  1012. ImFlipFlag(axis.Flags, ImPlot3DAxisFlags_NoGridLines);
  1013. if (ImGui::Checkbox("Tick Marks", &ticks))
  1014. ImFlipFlag(axis.Flags, ImPlot3DAxisFlags_NoTickMarks);
  1015. if (ImGui::Checkbox("Tick Labels", &labels))
  1016. ImFlipFlag(axis.Flags, ImPlot3DAxisFlags_NoTickLabels);
  1017. }
  1018. void ShowPlotContextMenu(ImPlot3DPlot& plot) {
  1019. ImPlot3DContext& gp = *GImPlot3D;
  1020. const bool owns_legend = gp.CurrentItems == &plot.Items;
  1021. char buf[16] = {};
  1022. const char* axis_labels[3] = {"X-Axis", "Y-Axis", "Z-Axis"};
  1023. for (int i = 0; i < 3; i++) {
  1024. ImPlot3DAxis& axis = plot.Axes[i];
  1025. ImGui::PushID(i);
  1026. ImFormatString(buf, sizeof(buf) - 1, i == 0 ? "X-Axis" : "X-Axis %d", i + 1);
  1027. if (ImGui::BeginMenu(axis.HasLabel() ? axis.GetLabel() : axis_labels[i])) {
  1028. ShowAxisContextMenu(axis);
  1029. ImGui::EndMenu();
  1030. }
  1031. ImGui::PopID();
  1032. }
  1033. ImGui::Separator();
  1034. if ((ImGui::BeginMenu("Legend"))) {
  1035. if (ShowLegendContextMenu(plot.Items.Legend, !ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_NoLegend)))
  1036. ImFlipFlag(plot.Flags, ImPlot3DFlags_NoLegend);
  1037. ImGui::EndMenu();
  1038. }
  1039. if ((ImGui::BeginMenu("Settings"))) {
  1040. ImGui::BeginDisabled(plot.Title.empty());
  1041. if (ImGui::MenuItem("Title", nullptr, plot.HasTitle()))
  1042. ImFlipFlag(plot.Flags, ImPlot3DFlags_NoTitle);
  1043. ImGui::EndDisabled();
  1044. ImGui::EndMenu();
  1045. }
  1046. }
  1047. //-----------------------------------------------------------------------------
  1048. // [SECTION] Begin/End Plot
  1049. //-----------------------------------------------------------------------------
  1050. bool BeginPlot(const char* title_id, const ImVec2& size, ImPlot3DFlags flags) {
  1051. IMPLOT3D_CHECK_CTX();
  1052. ImPlot3DContext& gp = *GImPlot3D;
  1053. IM_ASSERT_USER_ERROR(gp.CurrentPlot == nullptr, "Mismatched BeginPlot()/EndPlot()!");
  1054. // Get window
  1055. ImGuiContext& g = *GImGui;
  1056. ImGuiWindow* window = g.CurrentWindow;
  1057. // Skip if needed
  1058. if (window->SkipItems)
  1059. return false;
  1060. // Get or create plot
  1061. const ImGuiID ID = window->GetID(title_id);
  1062. const bool just_created = gp.Plots.GetByKey(ID) == nullptr;
  1063. gp.CurrentPlot = gp.Plots.GetOrAddByKey(ID);
  1064. gp.CurrentItems = &gp.CurrentPlot->Items;
  1065. ImPlot3DPlot& plot = *gp.CurrentPlot;
  1066. // Populate plot
  1067. plot.ID = ID;
  1068. plot.JustCreated = just_created;
  1069. if (just_created) {
  1070. plot.Rotation = init_rotation;
  1071. plot.FitThisFrame = true;
  1072. for (int i = 0; i < 3; i++) {
  1073. plot.Axes[i] = ImPlot3DAxis();
  1074. plot.Axes[i].FitThisFrame = true;
  1075. }
  1076. }
  1077. if (plot.PreviousFlags != flags)
  1078. plot.Flags = flags;
  1079. plot.PreviousFlags = flags;
  1080. plot.SetupLocked = false;
  1081. plot.OpenContextThisFrame = false;
  1082. // Populate title
  1083. plot.SetTitle(title_id);
  1084. // Calculate frame size
  1085. ImVec2 frame_size = ImGui::CalcItemSize(size, gp.Style.PlotDefaultSize.x, gp.Style.PlotDefaultSize.y);
  1086. if (frame_size.x < gp.Style.PlotMinSize.x && size.x < 0.0f)
  1087. frame_size.x = gp.Style.PlotMinSize.x;
  1088. if (frame_size.y < gp.Style.PlotMinSize.y && size.y < 0.0f)
  1089. frame_size.y = gp.Style.PlotMinSize.y;
  1090. // Create child window to capture scroll
  1091. ImGui::BeginChild(title_id, frame_size, false, ImGuiWindowFlags_NoScrollbar);
  1092. window = ImGui::GetCurrentWindow();
  1093. window->ScrollMax.y = 1.0f;
  1094. plot.FrameRect = ImRect(window->DC.CursorPos, window->DC.CursorPos + frame_size);
  1095. ImGui::ItemSize(plot.FrameRect);
  1096. if (!ImGui::ItemAdd(plot.FrameRect, plot.ID, &plot.FrameRect)) {
  1097. gp.CurrentPlot = nullptr;
  1098. gp.CurrentItems = nullptr;
  1099. ImGui::EndChild();
  1100. return false;
  1101. }
  1102. // Reset legend
  1103. plot.Items.Legend.Reset();
  1104. // Push frame rect clipping
  1105. ImGui::PushClipRect(plot.FrameRect.Min, plot.FrameRect.Max, true);
  1106. plot.DrawList._Flags = window->DrawList->Flags;
  1107. plot.DrawList._SharedData = ImGui::GetDrawListSharedData();
  1108. return true;
  1109. }
  1110. void EndPlot() {
  1111. IMPLOT3D_CHECK_CTX();
  1112. ImPlot3DContext& gp = *GImPlot3D;
  1113. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "Mismatched BeginPlot()/EndPlot()!");
  1114. ImPlot3DPlot& plot = *gp.CurrentPlot;
  1115. // Move triangles from 3D draw list to ImGui draw list
  1116. plot.DrawList.SortedMoveToImGuiDrawList();
  1117. // Handle data fitting
  1118. if (plot.FitThisFrame) {
  1119. plot.FitThisFrame = false;
  1120. for (int i = 0; i < 3; i++) {
  1121. if (plot.Axes[i].FitThisFrame) {
  1122. plot.Axes[i].FitThisFrame = false;
  1123. plot.Axes[i].ApplyFit();
  1124. }
  1125. }
  1126. }
  1127. // Lock setup if not already done
  1128. SetupLock();
  1129. // Reset legend hover
  1130. plot.Items.Legend.Hovered = false;
  1131. // Render legend
  1132. RenderLegend();
  1133. // Render mouse position
  1134. RenderMousePos();
  1135. // Legend context menu
  1136. if (ImGui::BeginPopup("##LegendContext")) {
  1137. ImGui::Text("Legend");
  1138. ImGui::Separator();
  1139. if (ShowLegendContextMenu(plot.Items.Legend, !ImPlot3D::ImHasFlag(plot.Flags, ImPlot3DFlags_NoLegend)))
  1140. ImFlipFlag(plot.Flags, ImPlot3DFlags_NoLegend);
  1141. ImGui::EndPopup();
  1142. }
  1143. // Axis context menus
  1144. static const char* axis_contexts[3] = {"##XAxisContext", "##YAxisContext", "##ZAxisContext"};
  1145. for (int i = 0; i < 3; i++) {
  1146. ImPlot3DAxis& axis = plot.Axes[i];
  1147. if (ImGui::BeginPopup(axis_contexts[i])) {
  1148. ImGui::Text(axis.HasLabel() ? axis.GetLabel() : "%c-Axis", 'X' + i);
  1149. ImGui::Separator();
  1150. ShowAxisContextMenu(axis);
  1151. ImGui::EndPopup();
  1152. }
  1153. }
  1154. // Plot context menu
  1155. if (ImGui::BeginPopup("##PlotContext")) {
  1156. ShowPlotContextMenu(plot);
  1157. ImGui::EndPopup();
  1158. }
  1159. // Pop frame rect clipping
  1160. ImGui::PopClipRect();
  1161. // End child window
  1162. ImGui::EndChild();
  1163. // Reset current plot
  1164. gp.CurrentPlot = nullptr;
  1165. gp.CurrentItems = nullptr;
  1166. // Reset the plot items for the next frame
  1167. for (int i = 0; i < plot.Items.GetItemCount(); i++)
  1168. plot.Items.GetItemByIndex(i)->SeenThisFrame = false;
  1169. }
  1170. //-----------------------------------------------------------------------------
  1171. // [SECTION] Setup
  1172. //-----------------------------------------------------------------------------
  1173. void SetupAxis(ImAxis3D idx, const char* label, ImPlot3DAxisFlags flags) {
  1174. ImPlot3DContext& gp = *GImPlot3D;
  1175. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  1176. "SetupAxis() needs to be called after BeginPlot() and before any setup locking functions (e.g. PlotX)!");
  1177. // Get plot and axis
  1178. ImPlot3DPlot& plot = *gp.CurrentPlot;
  1179. ImPlot3DAxis& axis = plot.Axes[idx];
  1180. if (axis.PreviousFlags != flags)
  1181. axis.Flags = flags;
  1182. axis.PreviousFlags = flags;
  1183. axis.SetLabel(label);
  1184. }
  1185. void SetupAxisLimits(ImAxis3D idx, double min_lim, double max_lim, ImPlot3DCond cond) {
  1186. ImPlot3DContext& gp = *GImPlot3D;
  1187. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  1188. "SetupAxisLimits() needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); // get plot and axis
  1189. ImPlot3DPlot& plot = *gp.CurrentPlot;
  1190. ImPlot3DAxis& axis = plot.Axes[idx];
  1191. if (!plot.Initialized || cond == ImPlot3DCond_Always) {
  1192. axis.SetRange(min_lim, max_lim);
  1193. axis.RangeCond = cond;
  1194. axis.FitThisFrame = false;
  1195. }
  1196. }
  1197. void SetupAxes(const char* x_label, const char* y_label, const char* z_label, ImPlot3DAxisFlags x_flags, ImPlot3DAxisFlags y_flags, ImPlot3DAxisFlags z_flags) {
  1198. SetupAxis(ImAxis3D_X, x_label, x_flags);
  1199. SetupAxis(ImAxis3D_Y, y_label, y_flags);
  1200. SetupAxis(ImAxis3D_Z, z_label, z_flags);
  1201. }
  1202. void SetupAxesLimits(double x_min, double x_max, double y_min, double y_max, double z_min, double z_max, ImPlot3DCond cond) {
  1203. SetupAxisLimits(ImAxis3D_X, x_min, x_max, cond);
  1204. SetupAxisLimits(ImAxis3D_Y, y_min, y_max, cond);
  1205. SetupAxisLimits(ImAxis3D_Z, z_min, z_max, cond);
  1206. if (cond == ImPlot3DCond_Once)
  1207. GImPlot3D->CurrentPlot->FitThisFrame = false;
  1208. }
  1209. void SetupLegend(ImPlot3DLocation location, ImPlot3DLegendFlags flags) {
  1210. ImPlot3DContext& gp = *GImPlot3D;
  1211. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  1212. "SetupLegend() needs to be called after BeginPlot() and before any setup locking functions (e.g. PlotX)!");
  1213. IM_ASSERT_USER_ERROR(gp.CurrentItems != nullptr,
  1214. "SetupLegend() needs to be called within an itemized context!");
  1215. ImPlot3DLegend& legend = gp.CurrentItems->Legend;
  1216. if (legend.PreviousLocation != location)
  1217. legend.Location = location;
  1218. legend.PreviousLocation = location;
  1219. if (legend.PreviousFlags != flags)
  1220. legend.Flags = flags;
  1221. legend.PreviousFlags = flags;
  1222. }
  1223. //-----------------------------------------------------------------------------
  1224. // [SECTION] Plot Utils
  1225. //-----------------------------------------------------------------------------
  1226. ImPlot3DPlot* GetCurrentPlot() {
  1227. return GImPlot3D->CurrentPlot;
  1228. }
  1229. void BustPlotCache() {
  1230. ImPlot3DContext& gp = *GImPlot3D;
  1231. gp.Plots.Clear();
  1232. }
  1233. ImVec2 PlotToPixels(const ImPlot3DPoint& point) {
  1234. ImPlot3DContext& gp = *GImPlot3D;
  1235. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PlotToPixels() needs to be called between BeginPlot() and EndPlot()!");
  1236. return NDCToPixels(PlotToNDC(point));
  1237. }
  1238. ImVec2 PlotToPixels(double x, double y, double z) {
  1239. return PlotToPixels(ImPlot3DPoint(x, y, z));
  1240. }
  1241. ImPlot3DRay PixelsToPlotRay(const ImVec2& pix) {
  1242. ImPlot3DContext& gp = *GImPlot3D;
  1243. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PixelsToPlotRay() needs to be called between BeginPlot() and EndPlot()!");
  1244. return NDCRayToPlotRay(PixelsToNDCRay(pix));
  1245. }
  1246. ImPlot3DRay PixelsToPlotRay(double x, double y) {
  1247. return PixelsToPlotRay(ImVec2(x, y));
  1248. }
  1249. ImPlot3DPoint PixelsToPlotPlane(const ImVec2& pix, ImPlane3D plane, bool mask) {
  1250. ImPlot3DContext& gp = *GImPlot3D;
  1251. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PixelsToPlotPlane() needs to be called between BeginPlot() and EndPlot()!");
  1252. ImPlot3DPlot& plot = *gp.CurrentPlot;
  1253. ImPlot3DRay ray = PixelsToNDCRay(pix);
  1254. const ImPlot3DPoint& O = ray.Origin;
  1255. const ImPlot3DPoint& D = ray.Direction;
  1256. // Helper lambda to check intersection with a given coordinate and return intersection point if valid.
  1257. auto IntersectPlane = [&](float coord) -> ImPlot3DPoint {
  1258. // Solve for t in O[axis] + D[axis]*t = coord
  1259. float denom = 0.0f;
  1260. float numer = 0.0f;
  1261. if (plane == ImPlane3D_YZ) {
  1262. denom = D.x;
  1263. numer = coord - O.x;
  1264. } else if (plane == ImPlane3D_XZ) {
  1265. denom = D.y;
  1266. numer = coord - O.y;
  1267. } else if (plane == ImPlane3D_XY) {
  1268. denom = D.z;
  1269. numer = coord - O.z;
  1270. }
  1271. if (ImAbs(denom) < 1e-12f) {
  1272. // Ray is parallel or nearly parallel to the plane
  1273. return ImPlot3DPoint(NAN, NAN, NAN);
  1274. }
  1275. float t = numer / denom;
  1276. if (t < 0.0f) {
  1277. // Intersection behind the ray origin
  1278. return ImPlot3DPoint(NAN, NAN, NAN);
  1279. }
  1280. return O + D * t;
  1281. };
  1282. // Helper lambda to check if point P is within the plot box
  1283. auto InRange = [&](const ImPlot3DPoint& P) {
  1284. return P.x >= -0.5 && P.x <= 0.5 &&
  1285. P.y >= -0.5 && P.y <= 0.5 &&
  1286. P.z >= -0.5 && P.z <= 0.5;
  1287. };
  1288. // Compute which plane to intersect with
  1289. bool active_faces[3];
  1290. ComputeActiveFaces(active_faces, plot.Rotation);
  1291. // Calculate intersection point with the planes
  1292. ImPlot3DPoint P = IntersectPlane(active_faces[plane] ? 0.5 : -0.5);
  1293. if (P.IsNaN())
  1294. return P;
  1295. // Handle mask (if one of the intersections is out of range, set it to NAN)
  1296. if (mask) {
  1297. switch (plane) {
  1298. case ImPlane3D_YZ:
  1299. if (!InRange(ImPlot3DPoint(0.0, P.y, P.z)))
  1300. return ImPlot3DPoint(NAN, NAN, NAN);
  1301. break;
  1302. case ImPlane3D_XZ:
  1303. if (!InRange(ImPlot3DPoint(P.x, 0.0, P.z)))
  1304. return ImPlot3DPoint(NAN, NAN, NAN);
  1305. break;
  1306. case ImPlane3D_XY:
  1307. if (!InRange(ImPlot3DPoint(P.x, P.y, 0.0)))
  1308. return ImPlot3DPoint(NAN, NAN, NAN);
  1309. break;
  1310. }
  1311. }
  1312. return NDCToPlot(P);
  1313. }
  1314. ImPlot3DPoint PixelsToPlotPlane(double x, double y, ImPlane3D plane, bool mask) {
  1315. return PixelsToPlotPlane(ImVec2(x, y), plane, mask);
  1316. }
  1317. ImVec2 GetPlotPos() {
  1318. ImPlot3DContext& gp = *GImPlot3D;
  1319. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetPlotPos() needs to be called between BeginPlot() and EndPlot()!");
  1320. SetupLock();
  1321. return gp.CurrentPlot->PlotRect.Min;
  1322. }
  1323. ImVec2 GetPlotSize() {
  1324. ImPlot3DContext& gp = *GImPlot3D;
  1325. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetPlotSize() needs to be called between BeginPlot() and EndPlot()!");
  1326. SetupLock();
  1327. return gp.CurrentPlot->PlotRect.GetSize();
  1328. }
  1329. ImVec2 GetFramePos() {
  1330. ImPlot3DContext& gp = *GImPlot3D;
  1331. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetFramePos() needs to be called between BeginPlot() and EndPlot()!");
  1332. return gp.CurrentPlot->FrameRect.Min;
  1333. }
  1334. ImVec2 GetFrameSize() {
  1335. ImPlot3DContext& gp = *GImPlot3D;
  1336. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetFrameSize() needs to be called between BeginPlot() and EndPlot()!");
  1337. return gp.CurrentPlot->FrameRect.GetSize();
  1338. }
  1339. ImPlot3DPoint PlotToNDC(const ImPlot3DPoint& point) {
  1340. ImPlot3DContext& gp = *GImPlot3D;
  1341. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PlotToNDC() needs to be called between BeginPlot() and EndPlot()!");
  1342. ImPlot3DPlot& plot = *gp.CurrentPlot;
  1343. SetupLock();
  1344. ImPlot3DPoint ndc_point;
  1345. for (int i = 0; i < 3; i++)
  1346. ndc_point[i] = plot.Axes[i].PlotToNDC(point[i]);
  1347. return ndc_point;
  1348. }
  1349. ImPlot3DPoint NDCToPlot(const ImPlot3DPoint& point) {
  1350. ImPlot3DContext& gp = *GImPlot3D;
  1351. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "NDCToPlot() needs to be called between BeginPlot() and EndPlot()!");
  1352. ImPlot3DPlot& plot = *gp.CurrentPlot;
  1353. SetupLock();
  1354. ImPlot3DPoint plot_point;
  1355. for (int i = 0; i < 3; i++)
  1356. plot_point[i] = plot.Axes[i].NDCToPlot(point[i]);
  1357. return plot_point;
  1358. }
  1359. ImVec2 NDCToPixels(const ImPlot3DPoint& point) {
  1360. ImPlot3DContext& gp = *GImPlot3D;
  1361. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "NDCToPixels() needs to be called between BeginPlot() and EndPlot()!");
  1362. ImPlot3DPlot& plot = *gp.CurrentPlot;
  1363. SetupLock();
  1364. float zoom = ImMin(plot.PlotRect.GetWidth(), plot.PlotRect.GetHeight()) / 1.8f;
  1365. ImVec2 center = plot.PlotRect.GetCenter();
  1366. ImPlot3DPoint point_pix = zoom * (plot.Rotation * point);
  1367. point_pix.y *= -1.0f; // Invert y-axis
  1368. point_pix.x += center.x;
  1369. point_pix.y += center.y;
  1370. return {point_pix.x, point_pix.y};
  1371. }
  1372. ImPlot3DRay PixelsToNDCRay(const ImVec2& pix) {
  1373. ImPlot3DContext& gp = *GImPlot3D;
  1374. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PixelsToNDCRay() needs to be called between BeginPlot() and EndPlot()!");
  1375. ImPlot3DPlot& plot = *gp.CurrentPlot;
  1376. SetupLock();
  1377. // Calculate zoom factor and plot center
  1378. float zoom = ImMin(plot.PlotRect.GetWidth(), plot.PlotRect.GetHeight()) / 1.8f;
  1379. ImVec2 center = plot.PlotRect.GetCenter();
  1380. // Undo screen transformations to get back to NDC space
  1381. float x = (pix.x - center.x) / zoom;
  1382. float y = -(pix.y - center.y) / zoom; // Invert y-axis
  1383. // Define near and far points in NDC space along the z-axis
  1384. ImPlot3DPoint ndc_near = plot.Rotation.Inverse() * ImPlot3DPoint(x, y, -10.0f);
  1385. ImPlot3DPoint ndc_far = plot.Rotation.Inverse() * ImPlot3DPoint(x, y, 10.0f);
  1386. // Create the ray in NDC space
  1387. ImPlot3DRay ndc_ray;
  1388. ndc_ray.Origin = ndc_near;
  1389. ndc_ray.Direction = (ndc_far - ndc_near).Normalized();
  1390. return ndc_ray;
  1391. }
  1392. ImPlot3DRay NDCRayToPlotRay(const ImPlot3DRay& ray) {
  1393. ImPlot3DContext& gp = *GImPlot3D;
  1394. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "NDCRayToPlotRay() needs to be called between BeginPlot() and EndPlot()!");
  1395. ImPlot3DPlot& plot = *gp.CurrentPlot;
  1396. SetupLock();
  1397. // Convert NDC origin and a point along the ray to plot coordinates
  1398. ImPlot3DPoint plot_origin = NDCToPlot(ray.Origin);
  1399. ImPlot3DPoint ndc_point_along_ray = ray.Origin + ray.Direction;
  1400. ImPlot3DPoint plot_point_along_ray = NDCToPlot(ndc_point_along_ray);
  1401. // Compute the direction in plot coordinates
  1402. ImPlot3DPoint plot_direction = (plot_point_along_ray - plot_origin).Normalized();
  1403. // Create the ray in plot coordinates
  1404. ImPlot3DRay plot_ray;
  1405. plot_ray.Origin = plot_origin;
  1406. plot_ray.Direction = plot_direction;
  1407. return plot_ray;
  1408. }
  1409. //-----------------------------------------------------------------------------
  1410. // [SECTION] Setup Utils
  1411. //-----------------------------------------------------------------------------
  1412. static const float MOUSE_CURSOR_DRAG_THRESHOLD = 5.0f;
  1413. static const float ANIMATION_ANGULAR_VELOCITY = 2 * 3.1415f;
  1414. void HandleInput(ImPlot3DPlot& plot) {
  1415. ImGuiIO& IO = ImGui::GetIO();
  1416. // clang-format off
  1417. const ImGuiButtonFlags plot_button_flags = ImGuiButtonFlags_AllowOverlap
  1418. | ImGuiButtonFlags_PressedOnClick
  1419. | ImGuiButtonFlags_PressedOnDoubleClick
  1420. | ImGuiButtonFlags_MouseButtonLeft
  1421. | ImGuiButtonFlags_MouseButtonRight
  1422. | ImGuiButtonFlags_MouseButtonMiddle;
  1423. // clang-format on
  1424. const bool plot_clicked = ImGui::ButtonBehavior(plot.PlotRect, plot.ID, &plot.Hovered, &plot.Held, plot_button_flags);
  1425. #if (IMGUI_VERSION_NUM < 18966)
  1426. ImGui::SetItemAllowOverlap(); // Handled by ButtonBehavior()
  1427. #endif
  1428. // State
  1429. const ImVec2 rot_drag = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right);
  1430. const bool rotating = ImLengthSqr(rot_drag) > MOUSE_CURSOR_DRAG_THRESHOLD;
  1431. // Check if any axis/plane is hovered
  1432. const ImPlot3DQuat& rotation = plot.Rotation;
  1433. ImPlot3DPoint range_min = plot.RangeMin();
  1434. ImPlot3DPoint range_max = plot.RangeMax();
  1435. bool active_faces[3];
  1436. int plane_2d = -1;
  1437. ComputeActiveFaces(active_faces, rotation, &plane_2d);
  1438. ImPlot3DPoint corners[8];
  1439. ComputeBoxCorners(corners, range_min, range_max);
  1440. ImVec2 corners_pix[8];
  1441. ComputeBoxCornersPix(corners_pix, corners);
  1442. int hovered_plane_idx = -1;
  1443. int hovered_plane = GetMouseOverPlane(plot, active_faces, corners_pix, &hovered_plane_idx);
  1444. int hovered_edge_idx = -1;
  1445. int hovered_axis = GetMouseOverAxis(plot, active_faces, corners_pix, plane_2d, &hovered_edge_idx);
  1446. if (hovered_axis != -1) {
  1447. hovered_plane_idx = -1;
  1448. hovered_plane = -1;
  1449. }
  1450. // If the user is no longer pressing the translation/zoom buttons, set axes as not held
  1451. if (!ImGui::IsMouseDown(ImGuiMouseButton_Left) && !ImGui::IsMouseDown(ImGuiMouseButton_Middle)) {
  1452. for (int i = 0; i < 3; i++)
  1453. plot.Axes[i].Held = false;
  1454. }
  1455. // Reset held edge/plane indices (it will be set if mouse button is down)
  1456. if (!plot.Held) {
  1457. plot.HeldEdgeIdx = -1;
  1458. plot.HeldPlaneIdx = -1;
  1459. }
  1460. // Check which axes should be transformed (fit/zoom/translate)
  1461. bool any_axis_held = plot.Axes[0].Held || plot.Axes[1].Held || plot.Axes[2].Held;
  1462. static bool transform_axis[3] = {false, false, false};
  1463. if (!any_axis_held) {
  1464. // Only update the transformation axes if the user is not already performing a transformation
  1465. transform_axis[0] = transform_axis[1] = transform_axis[2] = false;
  1466. if (hovered_axis != -1) {
  1467. transform_axis[hovered_axis] = true;
  1468. } else if (hovered_plane != -1) {
  1469. transform_axis[(hovered_plane + 1) % 3] = true;
  1470. transform_axis[(hovered_plane + 2) % 3] = true;
  1471. } else {
  1472. transform_axis[0] = transform_axis[1] = transform_axis[2] = true;
  1473. }
  1474. }
  1475. // Handle translation/zoom fit with double click
  1476. if (plot_clicked && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left) || ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Middle)) {
  1477. plot.FitThisFrame = true;
  1478. for (int i = 0; i < 3; i++)
  1479. plot.Axes[i].FitThisFrame = transform_axis[i];
  1480. }
  1481. // Handle auto fit
  1482. for (int i = 0; i < 3; i++)
  1483. if (plot.Axes[i].IsAutoFitting()) {
  1484. plot.FitThisFrame = true;
  1485. plot.Axes[i].FitThisFrame = true;
  1486. }
  1487. // Handle translation with right mouse button
  1488. if (plot.Held && ImGui::IsMouseDown(ImGuiMouseButton_Left)) {
  1489. ImVec2 delta(IO.MouseDelta.x, IO.MouseDelta.y);
  1490. if (transform_axis[0] && transform_axis[1] && transform_axis[2]) {
  1491. // Perform unconstrained translation (translate on the viewer plane)
  1492. // Compute delta_pixels in 3D (invert y-axis)
  1493. ImPlot3DPoint delta_pixels(delta.x, -delta.y, 0.0f);
  1494. // Convert delta to NDC space
  1495. float zoom = ImMin(plot.PlotRect.GetWidth(), plot.PlotRect.GetHeight()) / 1.8f;
  1496. ImPlot3DPoint delta_NDC = plot.Rotation.Inverse() * (delta_pixels / zoom);
  1497. // Convert delta to plot space
  1498. ImPlot3DPoint delta_plot = delta_NDC * (plot.RangeMax() - plot.RangeMin());
  1499. // Adjust plot range to translate the plot
  1500. for (int i = 0; i < 3; i++) {
  1501. if (transform_axis[i]) {
  1502. plot.Axes[i].SetRange(plot.Axes[i].Range.Min - delta_plot[i], plot.Axes[i].Range.Max - delta_plot[i]);
  1503. plot.Axes[i].Held = true;
  1504. }
  1505. // If no axis was held before (user started translating in this frame), set the held edge/plane indices
  1506. if (!any_axis_held) {
  1507. plot.HeldEdgeIdx = hovered_edge_idx;
  1508. plot.HeldPlaneIdx = hovered_plane_idx;
  1509. }
  1510. }
  1511. } else if (transform_axis[0] || transform_axis[1] || transform_axis[2]) {
  1512. // Translate along plane/axis
  1513. // Mouse delta in pixels
  1514. ImVec2 mouse_pos = ImGui::GetMousePos();
  1515. ImVec2 mouse_delta(IO.MouseDelta.x, IO.MouseDelta.y);
  1516. // TODO Choose best plane given transform_axis and current view
  1517. // For now it crashes when transforming only one axis in the 2D view
  1518. ImPlane3D plane = ImPlane3D_XY;
  1519. if (transform_axis[1] && transform_axis[2])
  1520. plane = ImPlane3D_YZ;
  1521. else if (transform_axis[0] && transform_axis[2])
  1522. plane = ImPlane3D_XZ;
  1523. else if (transform_axis[2])
  1524. plane = ImPlane3D_YZ;
  1525. ImPlot3DPoint mouse_plot = PixelsToPlotPlane(mouse_pos, plane, false);
  1526. ImPlot3DPoint mouse_delta_plot = PixelsToPlotPlane(mouse_pos + mouse_delta, plane, false);
  1527. ImPlot3DPoint delta_plot = mouse_delta_plot - mouse_plot;
  1528. // Apply translation to the selected axes
  1529. for (int i = 0; i < 3; i++) {
  1530. if (transform_axis[i]) {
  1531. plot.Axes[i].SetRange(plot.Axes[i].Range.Min - delta_plot[i],
  1532. plot.Axes[i].Range.Max - delta_plot[i]);
  1533. plot.Axes[i].Held = true;
  1534. }
  1535. if (!any_axis_held) {
  1536. plot.HeldEdgeIdx = hovered_edge_idx;
  1537. plot.HeldPlaneIdx = hovered_plane_idx;
  1538. }
  1539. }
  1540. }
  1541. }
  1542. // Handle context click with right mouse button
  1543. if (plot.Held && ImGui::IsMouseClicked(ImGuiMouseButton_Right))
  1544. plot.ContextClick = true;
  1545. if (rotating || ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Right))
  1546. plot.ContextClick = false;
  1547. // Handle reset rotation with left mouse double click
  1548. if (plot.Held && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Right)) {
  1549. plot.RotationAnimationEnd = plot.Rotation;
  1550. // Calculate rotation to align the z-axis with the camera direction
  1551. if (hovered_plane == -1) {
  1552. plot.RotationAnimationEnd = init_rotation;
  1553. } else {
  1554. // Compute plane normal
  1555. ImPlot3DPoint axis_normal = ImPlot3DPoint(0.0f, 0.0f, 0.0f);
  1556. axis_normal[hovered_plane] = active_faces[hovered_plane] ? -1.0f : 1.0f;
  1557. // Compute rotation to align the plane normal with the z-axis
  1558. ImPlot3DQuat align_normal = ImPlot3DQuat::FromTwoVectors(plot.RotationAnimationEnd * axis_normal, ImPlot3DPoint(0.0f, 0.0f, 1.0f));
  1559. plot.RotationAnimationEnd = align_normal * plot.RotationAnimationEnd;
  1560. if (hovered_plane != 2) {
  1561. // Compute rotation to point z-axis up
  1562. ImPlot3DQuat align_up = ImPlot3DQuat::FromTwoVectors(plot.RotationAnimationEnd * ImPlot3DPoint(0.0f, 0.0f, 1.0f), ImPlot3DPoint(0.0f, 1.0f, 0.0f));
  1563. plot.RotationAnimationEnd = align_up * plot.RotationAnimationEnd;
  1564. } else {
  1565. // Find the axis most aligned with the up direction
  1566. ImPlot3DPoint up(0.0f, 1.0f, 0.0f);
  1567. ImPlot3DPoint x_axis = plot.RotationAnimationEnd * ImPlot3DPoint(1.0f, 0.0f, 0.0f);
  1568. ImPlot3DPoint y_axis = plot.RotationAnimationEnd * ImPlot3DPoint(0.0f, 1.0f, 0.0f);
  1569. ImPlot3DPoint neg_x_axis = plot.RotationAnimationEnd * ImPlot3DPoint(-1.0f, 0.0f, 0.0f);
  1570. ImPlot3DPoint neg_y_axis = plot.RotationAnimationEnd * ImPlot3DPoint(0.0f, -1.0f, 0.0f);
  1571. struct AxisAlignment {
  1572. ImPlot3DPoint axis;
  1573. float dot;
  1574. };
  1575. AxisAlignment candidates[] = {
  1576. {x_axis, x_axis.Dot(up)},
  1577. {y_axis, y_axis.Dot(up)},
  1578. {neg_x_axis, neg_x_axis.Dot(up)},
  1579. {neg_y_axis, neg_y_axis.Dot(up)},
  1580. };
  1581. // Find the candidate with the maximum dot product
  1582. AxisAlignment* best_candidate = &candidates[0];
  1583. for (int i = 1; i < 4; ++i) {
  1584. if (candidates[i].dot > best_candidate->dot) {
  1585. best_candidate = &candidates[i];
  1586. }
  1587. }
  1588. // Compute the rotation to align the best candidate with the up direction
  1589. ImPlot3DQuat align_up = ImPlot3DQuat::FromTwoVectors(best_candidate->axis, up);
  1590. plot.RotationAnimationEnd = align_up * plot.RotationAnimationEnd;
  1591. }
  1592. }
  1593. // Compute the angular distance between current and target rotation
  1594. float dot_product = ImClamp(plot.Rotation.Dot(plot.RotationAnimationEnd), -1.0f, 1.0f);
  1595. float angle = 2.0f * acosf(fabsf(dot_product));
  1596. // Calculate animation time for constant the angular velocity
  1597. plot.AnimationTime = angle / ANIMATION_ANGULAR_VELOCITY;
  1598. }
  1599. // Handle rotation with left mouse dragging
  1600. if (plot.Held && ImGui::IsMouseDown(ImGuiMouseButton_Right)) {
  1601. ImVec2 delta(IO.MouseDelta.x, IO.MouseDelta.y);
  1602. // Map delta to rotation angles (in radians)
  1603. float angle_x = delta.x * (3.1415f / 180.0f);
  1604. float angle_y = delta.y * (3.1415f / 180.0f);
  1605. // Create quaternions for the rotations
  1606. ImPlot3DQuat quat_x(angle_y, ImPlot3DPoint(1.0f, 0.0f, 0.0f));
  1607. ImPlot3DQuat quat_z(angle_x, ImPlot3DPoint(0.0f, 0.0f, 1.0f));
  1608. // Combine the new rotations with the current rotation
  1609. plot.Rotation = quat_x * plot.Rotation * quat_z;
  1610. plot.Rotation.Normalize();
  1611. }
  1612. // Handle zoom with mouse wheel
  1613. if (plot.Hovered && (ImGui::IsMouseDown(ImGuiMouseButton_Middle) || IO.MouseWheel != 0)) {
  1614. float delta = ImGui::IsMouseDown(ImGuiMouseButton_Middle) ? (-0.01f * IO.MouseDelta.y) : (-0.1f * IO.MouseWheel);
  1615. float zoom = 1.0f + delta;
  1616. for (int i = 0; i < 3; i++) {
  1617. ImPlot3DAxis& axis = plot.Axes[i];
  1618. float center = (axis.Range.Min + axis.Range.Max) * 0.5f;
  1619. float size = axis.Range.Max - axis.Range.Min;
  1620. size *= zoom;
  1621. if (transform_axis[i]) {
  1622. plot.Axes[i].SetRange(center - size * 0.5f, center + size * 0.5f);
  1623. plot.Axes[i].Held = true;
  1624. }
  1625. // If no axis was held before (user started zoom in this frame), set the held edge/plane indices
  1626. if (!any_axis_held) {
  1627. plot.HeldEdgeIdx = hovered_edge_idx;
  1628. plot.HeldPlaneIdx = hovered_plane_idx;
  1629. }
  1630. }
  1631. }
  1632. // Handle context menu (should not happen if it is not a double click action)
  1633. bool not_double_click = (float)(ImGui::GetTime() - IO.MouseClickedTime[ImGuiMouseButton_Right]) > IO.MouseDoubleClickTime;
  1634. if (plot.Hovered && plot.ContextClick && not_double_click && !ImGui::IsMouseDown(ImGuiMouseButton_Right)) {
  1635. plot.ContextClick = false;
  1636. plot.OpenContextThisFrame = true;
  1637. }
  1638. // TODO Only open context menu if the mouse is not in the middle of double click action
  1639. const char* axis_contexts[3] = {"##XAxisContext", "##YAxisContext", "##ZAxisContext"};
  1640. if (plot.OpenContextThisFrame) {
  1641. if (plot.Items.Legend.Hovered)
  1642. ImGui::OpenPopup("##LegendContext");
  1643. else if (hovered_axis != -1) {
  1644. ImGui::OpenPopup(axis_contexts[hovered_axis]);
  1645. } else if (hovered_plane != -1) {
  1646. ImGui::OpenPopup(axis_contexts[hovered_plane]);
  1647. } else if (plot.Hovered) {
  1648. ImGui::OpenPopup("##PlotContext");
  1649. }
  1650. }
  1651. }
  1652. void SetupLock() {
  1653. ImPlot3DContext& gp = *GImPlot3D;
  1654. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "SetupLock() needs to be called between BeginPlot() and EndPlot()!");
  1655. ImPlot3DPlot& plot = *gp.CurrentPlot;
  1656. if (plot.SetupLocked)
  1657. return;
  1658. // Lock setup
  1659. plot.SetupLocked = true;
  1660. ImGuiContext& g = *GImGui;
  1661. ImGuiWindow* window = g.CurrentWindow;
  1662. ImDrawList* draw_list = window->DrawList;
  1663. ImGui::PushClipRect(plot.FrameRect.Min, plot.FrameRect.Max, true);
  1664. // Set default formatter/locator
  1665. for (int i = 0; i < 3; i++) {
  1666. ImPlot3DAxis& axis = plot.Axes[i];
  1667. // Set formatter
  1668. if (axis.Formatter == nullptr) {
  1669. axis.Formatter = Formatter_Default;
  1670. if (axis.FormatterData == nullptr)
  1671. axis.FormatterData = (void*)IMPLOT3D_LABEL_FORMAT;
  1672. }
  1673. // Set locator
  1674. if (axis.Locator == nullptr)
  1675. axis.Locator = Locator_Default;
  1676. }
  1677. // Draw frame background
  1678. ImU32 f_bg_color = GetStyleColorU32(ImPlot3DCol_FrameBg);
  1679. draw_list->AddRectFilled(plot.FrameRect.Min, plot.FrameRect.Max, f_bg_color);
  1680. // Compute canvas/canvas rectangle
  1681. plot.CanvasRect = ImRect(plot.FrameRect.Min + gp.Style.PlotPadding, plot.FrameRect.Max - gp.Style.PlotPadding);
  1682. plot.PlotRect = plot.CanvasRect;
  1683. // Compute ticks
  1684. for (int i = 0; i < 3; i++) {
  1685. ImPlot3DAxis& axis = plot.Axes[i];
  1686. axis.Ticker.Reset();
  1687. axis.Locator(axis.Ticker, axis.Range, axis.Formatter, axis.FormatterData);
  1688. }
  1689. // Render title
  1690. if (plot.HasTitle()) {
  1691. ImU32 col = GetStyleColorU32(ImPlot3DCol_TitleText);
  1692. ImVec2 top_center = ImVec2(plot.FrameRect.GetCenter().x, plot.CanvasRect.Min.y);
  1693. AddTextCentered(draw_list, top_center, col, plot.GetTitle());
  1694. plot.PlotRect.Min.y += ImGui::GetTextLineHeight() + gp.Style.LabelPadding.y;
  1695. }
  1696. // Handle animation
  1697. if (plot.AnimationTime > 0.0f) {
  1698. float dt = ImGui::GetIO().DeltaTime;
  1699. float t = ImClamp(dt / plot.AnimationTime, 0.0f, 1.0f);
  1700. plot.AnimationTime -= dt;
  1701. if (plot.AnimationTime < 0.0f)
  1702. plot.AnimationTime = 0.0f;
  1703. plot.Rotation = ImPlot3DQuat::Slerp(plot.Rotation, plot.RotationAnimationEnd, t);
  1704. }
  1705. plot.Initialized = true;
  1706. // Handle user input
  1707. HandleInput(plot);
  1708. // Render plot box
  1709. RenderPlotBox(draw_list, plot);
  1710. ImGui::PopClipRect();
  1711. }
  1712. //-----------------------------------------------------------------------------
  1713. // [SECTION] Miscellaneous
  1714. //-----------------------------------------------------------------------------
  1715. ImDrawList* GetPlotDrawList() {
  1716. return ImGui::GetWindowDrawList();
  1717. }
  1718. //-----------------------------------------------------------------------------
  1719. // [SECTION] Styles
  1720. //-----------------------------------------------------------------------------
  1721. struct ImPlot3DStyleVarInfo {
  1722. ImGuiDataType Type;
  1723. ImU32 Count;
  1724. ImU32 Offset;
  1725. void* GetVarPtr(ImPlot3DStyle* style) const { return (void*)((unsigned char*)style + Offset); }
  1726. };
  1727. static const ImPlot3DStyleVarInfo GPlot3DStyleVarInfo[] =
  1728. {
  1729. // Item style
  1730. {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlot3DStyle, LineWeight)}, // ImPlot3DStyleVar_LineWeight
  1731. {ImGuiDataType_S32, 1, (ImU32)IM_OFFSETOF(ImPlot3DStyle, Marker)}, // ImPlot3DStyleVar_Marker
  1732. {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlot3DStyle, MarkerSize)}, // ImPlot3DStyleVar_MarkerSize
  1733. {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlot3DStyle, MarkerWeight)}, // ImPlot3DStyleVar_MarkerWeight
  1734. {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlot3DStyle, FillAlpha)}, // ImPlot3DStyleVar_FillAlpha
  1735. // Plot style
  1736. {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlot3DStyle, PlotDefaultSize)}, // ImPlot3DStyleVar_Plot3DDefaultSize
  1737. {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlot3DStyle, PlotMinSize)}, // ImPlot3DStyleVar_Plot3DMinSize
  1738. {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlot3DStyle, PlotPadding)}, // ImPlot3DStyleVar_Plot3DPadding
  1739. // Label style
  1740. {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlot3DStyle, LabelPadding)}, // ImPlot3DStyleVar_LabelPaddine
  1741. {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlot3DStyle, LegendPadding)}, // ImPlot3DStyleVar_LegendPadding
  1742. {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlot3DStyle, LegendInnerPadding)}, // ImPlot3DStyleVar_LegendInnerPadding
  1743. {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlot3DStyle, LegendSpacing)}, // ImPlot3DStyleVar_LegendSpacing
  1744. };
  1745. static const ImPlot3DStyleVarInfo* GetPlotStyleVarInfo(ImPlot3DStyleVar idx) {
  1746. IM_ASSERT(idx >= 0 && idx < ImPlot3DStyleVar_COUNT);
  1747. IM_ASSERT(IM_ARRAYSIZE(GPlot3DStyleVarInfo) == ImPlot3DStyleVar_COUNT);
  1748. return &GPlot3DStyleVarInfo[idx];
  1749. }
  1750. ImPlot3DStyle& GetStyle() { return GImPlot3D->Style; }
  1751. void StyleColorsAuto(ImPlot3DStyle* dst) {
  1752. ImPlot3DStyle* style = dst ? dst : &ImPlot3D::GetStyle();
  1753. ImVec4* colors = style->Colors;
  1754. colors[ImPlot3DCol_Line] = IMPLOT3D_AUTO_COL;
  1755. colors[ImPlot3DCol_Fill] = IMPLOT3D_AUTO_COL;
  1756. colors[ImPlot3DCol_MarkerOutline] = IMPLOT3D_AUTO_COL;
  1757. colors[ImPlot3DCol_MarkerFill] = IMPLOT3D_AUTO_COL;
  1758. colors[ImPlot3DCol_TitleText] = IMPLOT3D_AUTO_COL;
  1759. colors[ImPlot3DCol_InlayText] = IMPLOT3D_AUTO_COL;
  1760. colors[ImPlot3DCol_FrameBg] = IMPLOT3D_AUTO_COL;
  1761. colors[ImPlot3DCol_PlotBg] = IMPLOT3D_AUTO_COL;
  1762. colors[ImPlot3DCol_PlotBorder] = IMPLOT3D_AUTO_COL;
  1763. colors[ImPlot3DCol_LegendBg] = IMPLOT3D_AUTO_COL;
  1764. colors[ImPlot3DCol_LegendBorder] = IMPLOT3D_AUTO_COL;
  1765. colors[ImPlot3DCol_LegendText] = IMPLOT3D_AUTO_COL;
  1766. colors[ImPlot3DCol_AxisText] = IMPLOT3D_AUTO_COL;
  1767. colors[ImPlot3DCol_AxisGrid] = IMPLOT3D_AUTO_COL;
  1768. colors[ImPlot3DCol_AxisTick] = IMPLOT3D_AUTO_COL;
  1769. }
  1770. void StyleColorsDark(ImPlot3DStyle* dst) {
  1771. ImPlot3DStyle* style = dst ? dst : &ImPlot3D::GetStyle();
  1772. ImVec4* colors = style->Colors;
  1773. colors[ImPlot3DCol_Line] = IMPLOT3D_AUTO_COL;
  1774. colors[ImPlot3DCol_Fill] = IMPLOT3D_AUTO_COL;
  1775. colors[ImPlot3DCol_MarkerOutline] = IMPLOT3D_AUTO_COL;
  1776. colors[ImPlot3DCol_MarkerFill] = IMPLOT3D_AUTO_COL;
  1777. colors[ImPlot3DCol_TitleText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
  1778. colors[ImPlot3DCol_InlayText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
  1779. colors[ImPlot3DCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f);
  1780. colors[ImPlot3DCol_PlotBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.50f);
  1781. colors[ImPlot3DCol_PlotBorder] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f);
  1782. colors[ImPlot3DCol_LegendBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f);
  1783. colors[ImPlot3DCol_LegendBorder] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f);
  1784. colors[ImPlot3DCol_LegendText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
  1785. colors[ImPlot3DCol_AxisText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
  1786. colors[ImPlot3DCol_AxisGrid] = ImVec4(1.00f, 1.00f, 1.00f, 0.25f);
  1787. colors[ImPlot3DCol_AxisTick] = IMPLOT3D_AUTO_COL;
  1788. }
  1789. void StyleColorsLight(ImPlot3DStyle* dst) {
  1790. ImPlot3DStyle* style = dst ? dst : &ImPlot3D::GetStyle();
  1791. ImVec4* colors = style->Colors;
  1792. colors[ImPlot3DCol_Line] = IMPLOT3D_AUTO_COL;
  1793. colors[ImPlot3DCol_Fill] = IMPLOT3D_AUTO_COL;
  1794. colors[ImPlot3DCol_MarkerOutline] = IMPLOT3D_AUTO_COL;
  1795. colors[ImPlot3DCol_MarkerFill] = IMPLOT3D_AUTO_COL;
  1796. colors[ImPlot3DCol_TitleText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
  1797. colors[ImPlot3DCol_InlayText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
  1798. colors[ImPlot3DCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
  1799. colors[ImPlot3DCol_PlotBg] = ImVec4(0.42f, 0.57f, 1.00f, 0.13f);
  1800. colors[ImPlot3DCol_PlotBorder] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
  1801. colors[ImPlot3DCol_LegendBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.98f);
  1802. colors[ImPlot3DCol_LegendBorder] = ImVec4(0.82f, 0.82f, 0.82f, 0.80f);
  1803. colors[ImPlot3DCol_LegendText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
  1804. colors[ImPlot3DCol_AxisText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
  1805. colors[ImPlot3DCol_AxisGrid] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
  1806. colors[ImPlot3DCol_AxisTick] = IMPLOT3D_AUTO_COL;
  1807. }
  1808. void StyleColorsClassic(ImPlot3DStyle* dst) {
  1809. ImPlot3DStyle* style = dst ? dst : &ImPlot3D::GetStyle();
  1810. ImVec4* colors = style->Colors;
  1811. colors[ImPlot3DCol_Line] = IMPLOT3D_AUTO_COL;
  1812. colors[ImPlot3DCol_Fill] = IMPLOT3D_AUTO_COL;
  1813. colors[ImPlot3DCol_MarkerOutline] = IMPLOT3D_AUTO_COL;
  1814. colors[ImPlot3DCol_MarkerFill] = IMPLOT3D_AUTO_COL;
  1815. colors[ImPlot3DCol_TitleText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
  1816. colors[ImPlot3DCol_InlayText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
  1817. colors[ImPlot3DCol_FrameBg] = ImVec4(0.43f, 0.43f, 0.43f, 0.39f);
  1818. colors[ImPlot3DCol_PlotBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.35f);
  1819. colors[ImPlot3DCol_PlotBorder] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f);
  1820. colors[ImPlot3DCol_LegendBg] = ImVec4(0.11f, 0.11f, 0.14f, 0.92f);
  1821. colors[ImPlot3DCol_LegendBorder] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f);
  1822. colors[ImPlot3DCol_LegendText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
  1823. colors[ImPlot3DCol_AxisText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
  1824. colors[ImPlot3DCol_AxisGrid] = ImVec4(0.90f, 0.90f, 0.90f, 0.25f);
  1825. colors[ImPlot3DCol_AxisTick] = IMPLOT3D_AUTO_COL;
  1826. }
  1827. void PushStyleColor(ImPlot3DCol idx, ImU32 col) {
  1828. ImPlot3DContext& gp = *GImPlot3D;
  1829. ImGuiColorMod backup;
  1830. backup.Col = (ImGuiCol)idx;
  1831. backup.BackupValue = gp.Style.Colors[idx];
  1832. gp.ColorModifiers.push_back(backup);
  1833. gp.Style.Colors[idx] = ImGui::ColorConvertU32ToFloat4(col);
  1834. }
  1835. void PushStyleColor(ImPlot3DCol idx, const ImVec4& col) {
  1836. ImPlot3DContext& gp = *GImPlot3D;
  1837. ImGuiColorMod backup;
  1838. backup.Col = (ImGuiCol)idx;
  1839. backup.BackupValue = gp.Style.Colors[idx];
  1840. gp.ColorModifiers.push_back(backup);
  1841. gp.Style.Colors[idx] = col;
  1842. }
  1843. void PopStyleColor(int count) {
  1844. ImPlot3DContext& gp = *GImPlot3D;
  1845. IM_ASSERT_USER_ERROR(count <= gp.ColorModifiers.Size, "You can't pop more modifiers than have been pushed!");
  1846. while (count > 0) {
  1847. ImGuiColorMod& backup = gp.ColorModifiers.back();
  1848. gp.Style.Colors[backup.Col] = backup.BackupValue;
  1849. gp.ColorModifiers.pop_back();
  1850. count--;
  1851. }
  1852. }
  1853. void PushStyleVar(ImPlot3DStyleVar idx, float val) {
  1854. ImPlot3DContext& gp = *GImPlot3D;
  1855. const ImPlot3DStyleVarInfo* var_info = GetPlotStyleVarInfo(idx);
  1856. if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) {
  1857. float* pvar = (float*)var_info->GetVarPtr(&gp.Style);
  1858. gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar));
  1859. *pvar = val;
  1860. return;
  1861. }
  1862. IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
  1863. }
  1864. void PushStyleVar(ImPlot3DStyleVar idx, int val) {
  1865. ImPlot3DContext& gp = *GImPlot3D;
  1866. const ImPlot3DStyleVarInfo* var_info = GetPlotStyleVarInfo(idx);
  1867. if (var_info->Type == ImGuiDataType_S32 && var_info->Count == 1) {
  1868. int* pvar = (int*)var_info->GetVarPtr(&gp.Style);
  1869. gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar));
  1870. *pvar = val;
  1871. return;
  1872. } else if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) {
  1873. float* pvar = (float*)var_info->GetVarPtr(&gp.Style);
  1874. gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar));
  1875. *pvar = (float)val;
  1876. return;
  1877. }
  1878. IM_ASSERT(0 && "Called PushStyleVar() int variant but variable is not a int!");
  1879. }
  1880. void PushStyleVar(ImPlot3DStyleVar idx, const ImVec2& val) {
  1881. ImPlot3DContext& gp = *GImPlot3D;
  1882. const ImPlot3DStyleVarInfo* var_info = GetPlotStyleVarInfo(idx);
  1883. if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2) {
  1884. ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&gp.Style);
  1885. gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar));
  1886. *pvar = val;
  1887. return;
  1888. }
  1889. IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
  1890. }
  1891. void PopStyleVar(int count) {
  1892. ImPlot3DContext& gp = *GImPlot3D;
  1893. IM_ASSERT_USER_ERROR(count <= gp.StyleModifiers.Size, "You can't pop more modifiers than have been pushed!");
  1894. while (count > 0) {
  1895. ImGuiStyleMod& backup = gp.StyleModifiers.back();
  1896. const ImPlot3DStyleVarInfo* info = GetPlotStyleVarInfo(backup.VarIdx);
  1897. void* data = info->GetVarPtr(&gp.Style);
  1898. if (info->Type == ImGuiDataType_Float && info->Count == 1) {
  1899. ((float*)data)[0] = backup.BackupFloat[0];
  1900. } else if (info->Type == ImGuiDataType_Float && info->Count == 2) {
  1901. ((float*)data)[0] = backup.BackupFloat[0];
  1902. ((float*)data)[1] = backup.BackupFloat[1];
  1903. } else if (info->Type == ImGuiDataType_S32 && info->Count == 1) {
  1904. ((int*)data)[0] = backup.BackupInt[0];
  1905. }
  1906. gp.StyleModifiers.pop_back();
  1907. count--;
  1908. }
  1909. }
  1910. ImVec4 GetStyleColorVec4(ImPlot3DCol idx) {
  1911. return IsColorAuto(idx) ? GetAutoColor(idx) : GImPlot3D->Style.Colors[idx];
  1912. }
  1913. ImU32 GetStyleColorU32(ImPlot3DCol idx) {
  1914. return ImGui::ColorConvertFloat4ToU32(ImPlot3D::GetStyleColorVec4(idx));
  1915. }
  1916. //------------------------------------------------------------------------------
  1917. // [SECTION] Colormaps
  1918. //------------------------------------------------------------------------------
  1919. ImPlot3DColormap AddColormap(const char* name, const ImVec4* colormap, int size, bool qual) {
  1920. ImPlot3DContext& gp = *GImPlot3D;
  1921. IM_ASSERT_USER_ERROR(size > 1, "The colormap size must be greater than 1!");
  1922. IM_ASSERT_USER_ERROR(gp.ColormapData.GetIndex(name) == -1, "The colormap name has already been used!");
  1923. ImVector<ImU32> buffer;
  1924. buffer.resize(size);
  1925. for (int i = 0; i < size; ++i)
  1926. buffer[i] = ImGui::ColorConvertFloat4ToU32(colormap[i]);
  1927. return gp.ColormapData.Append(name, buffer.Data, size, qual);
  1928. }
  1929. ImPlot3DColormap AddColormap(const char* name, const ImU32* colormap, int size, bool qual) {
  1930. ImPlot3DContext& gp = *GImPlot3D;
  1931. IM_ASSERT_USER_ERROR(size > 1, "The colormap size must be greater than 1!");
  1932. IM_ASSERT_USER_ERROR(gp.ColormapData.GetIndex(name) == -1, "The colormap name has already be used!");
  1933. return gp.ColormapData.Append(name, colormap, size, qual);
  1934. }
  1935. int GetColormapCount() {
  1936. ImPlot3DContext& gp = *GImPlot3D;
  1937. return gp.ColormapData.Count;
  1938. }
  1939. const char* GetColormapName(ImPlot3DColormap colormap) {
  1940. ImPlot3DContext& gp = *GImPlot3D;
  1941. return gp.ColormapData.GetName(colormap);
  1942. }
  1943. ImPlot3DColormap GetColormapIndex(const char* name) {
  1944. ImPlot3DContext& gp = *GImPlot3D;
  1945. return gp.ColormapData.GetIndex(name);
  1946. }
  1947. void PushColormap(ImPlot3DColormap colormap) {
  1948. ImPlot3DContext& gp = *GImPlot3D;
  1949. IM_ASSERT_USER_ERROR(colormap >= 0 && colormap < gp.ColormapData.Count, "The colormap index is invalid!");
  1950. gp.ColormapModifiers.push_back(gp.Style.Colormap);
  1951. gp.Style.Colormap = colormap;
  1952. }
  1953. void PushColormap(const char* name) {
  1954. ImPlot3DContext& gp = *GImPlot3D;
  1955. ImPlot3DColormap idx = gp.ColormapData.GetIndex(name);
  1956. IM_ASSERT_USER_ERROR(idx != -1, "The colormap name is invalid!");
  1957. PushColormap(idx);
  1958. }
  1959. void PopColormap(int count) {
  1960. ImPlot3DContext& gp = *GImPlot3D;
  1961. IM_ASSERT_USER_ERROR(count <= gp.ColormapModifiers.Size, "You can't pop more modifiers than have been pushed!");
  1962. while (count > 0) {
  1963. const ImPlot3DColormap& backup = gp.ColormapModifiers.back();
  1964. gp.Style.Colormap = backup;
  1965. gp.ColormapModifiers.pop_back();
  1966. count--;
  1967. }
  1968. }
  1969. ImU32 NextColormapColorU32() {
  1970. ImPlot3DContext& gp = *GImPlot3D;
  1971. IM_ASSERT_USER_ERROR(gp.CurrentItems != nullptr, "NextColormapColor() needs to be called between BeginPlot() and EndPlot()!");
  1972. int idx = gp.CurrentItems->ColormapIdx % gp.ColormapData.GetKeyCount(gp.Style.Colormap);
  1973. ImU32 col = gp.ColormapData.GetKeyColor(gp.Style.Colormap, idx);
  1974. gp.CurrentItems->ColormapIdx++;
  1975. return col;
  1976. }
  1977. ImVec4 NextColormapColor() {
  1978. return ImGui::ColorConvertU32ToFloat4(NextColormapColorU32());
  1979. }
  1980. int GetColormapSize(ImPlot3DColormap cmap) {
  1981. ImPlot3DContext& gp = *GImPlot3D;
  1982. cmap = cmap == IMPLOT3D_AUTO ? gp.Style.Colormap : cmap;
  1983. IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!");
  1984. return gp.ColormapData.GetKeyCount(cmap);
  1985. }
  1986. ImU32 GetColormapColorU32(int idx, ImPlot3DColormap cmap) {
  1987. ImPlot3DContext& gp = *GImPlot3D;
  1988. cmap = cmap == IMPLOT3D_AUTO ? gp.Style.Colormap : cmap;
  1989. IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!");
  1990. idx = idx % gp.ColormapData.GetKeyCount(cmap);
  1991. return gp.ColormapData.GetKeyColor(cmap, idx);
  1992. }
  1993. ImVec4 GetColormapColor(int idx, ImPlot3DColormap cmap) {
  1994. return ImGui::ColorConvertU32ToFloat4(GetColormapColorU32(idx, cmap));
  1995. }
  1996. ImU32 SampleColormapU32(float t, ImPlot3DColormap cmap) {
  1997. ImPlot3DContext& gp = *GImPlot3D;
  1998. cmap = cmap == IMPLOT3D_AUTO ? gp.Style.Colormap : cmap;
  1999. IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!");
  2000. return gp.ColormapData.LerpTable(cmap, t);
  2001. }
  2002. ImVec4 SampleColormap(float t, ImPlot3DColormap cmap) {
  2003. return ImGui::ColorConvertU32ToFloat4(SampleColormapU32(t, cmap));
  2004. }
  2005. //-----------------------------------------------------------------------------
  2006. // [SECTION] Context Utils
  2007. //-----------------------------------------------------------------------------
  2008. #define IMPLOT3D_APPEND_CMAP(name, qual) ctx->ColormapData.Append(#name, name, sizeof(name) / sizeof(ImU32), qual)
  2009. #define IM_RGB(r, g, b) IM_COL32(r, g, b, 255)
  2010. void InitializeContext(ImPlot3DContext* ctx) {
  2011. ResetContext(ctx);
  2012. const ImU32 Deep[] = {4289753676, 4283598045, 4285048917, 4283584196, 4289950337, 4284512403, 4291005402, 4287401100, 4285839820, 4291671396};
  2013. const ImU32 Dark[] = {4280031972, 4290281015, 4283084621, 4288892568, 4278222847, 4281597951, 4280833702, 4290740727, 4288256409};
  2014. const ImU32 Pastel[] = {4289639675, 4293119411, 4291161036, 4293184478, 4289124862, 4291624959, 4290631909, 4293712637, 4294111986};
  2015. const ImU32 Paired[] = {4293119554, 4290017311, 4287291314, 4281114675, 4288256763, 4280031971, 4285513725, 4278222847, 4292260554, 4288298346, 4288282623, 4280834481};
  2016. const ImU32 Viridis[] = {4283695428, 4285867080, 4287054913, 4287455029, 4287526954, 4287402273, 4286883874, 4285579076, 4283552122, 4280737725, 4280674301};
  2017. const ImU32 Plasma[] = {4287039501, 4288480321, 4289200234, 4288941455, 4287638193, 4286072780, 4284638433, 4283139314, 4281771772, 4280667900, 4280416752};
  2018. const ImU32 Hot[] = {4278190144, 4278190208, 4278190271, 4278190335, 4278206719, 4278223103, 4278239231, 4278255615, 4283826175, 4289396735, 4294967295};
  2019. const ImU32 Cool[] = {4294967040, 4294960666, 4294954035, 4294947661, 4294941030, 4294934656, 4294928025, 4294921651, 4294915020, 4294908646, 4294902015};
  2020. const ImU32 Pink[] = {4278190154, 4282532475, 4284308894, 4285690554, 4286879686, 4287870160, 4288794330, 4289651940, 4291685869, 4293392118, 4294967295};
  2021. const ImU32 Jet[] = {4289331200, 4294901760, 4294923520, 4294945280, 4294967040, 4289396565, 4283826090, 4278255615, 4278233855, 4278212095, 4278190335};
  2022. 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)};
  2023. 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)};
  2024. 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)};
  2025. 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)};
  2026. 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)};
  2027. const ImU32 Greys[] = {IM_COL32_WHITE, IM_COL32_BLACK};
  2028. IMPLOT3D_APPEND_CMAP(Deep, true);
  2029. IMPLOT3D_APPEND_CMAP(Dark, true);
  2030. IMPLOT3D_APPEND_CMAP(Pastel, true);
  2031. IMPLOT3D_APPEND_CMAP(Paired, true);
  2032. IMPLOT3D_APPEND_CMAP(Viridis, false);
  2033. IMPLOT3D_APPEND_CMAP(Plasma, false);
  2034. IMPLOT3D_APPEND_CMAP(Hot, false);
  2035. IMPLOT3D_APPEND_CMAP(Cool, false);
  2036. IMPLOT3D_APPEND_CMAP(Pink, false);
  2037. IMPLOT3D_APPEND_CMAP(Jet, false);
  2038. IMPLOT3D_APPEND_CMAP(Twilight, false);
  2039. IMPLOT3D_APPEND_CMAP(RdBu, false);
  2040. IMPLOT3D_APPEND_CMAP(BrBG, false);
  2041. IMPLOT3D_APPEND_CMAP(PiYG, false);
  2042. IMPLOT3D_APPEND_CMAP(Spectral, false);
  2043. IMPLOT3D_APPEND_CMAP(Greys, false);
  2044. }
  2045. void ResetContext(ImPlot3DContext* ctx) {
  2046. ctx->Plots.Clear();
  2047. ctx->CurrentPlot = nullptr;
  2048. ctx->CurrentItems = nullptr;
  2049. ctx->NextItemData.Reset();
  2050. ctx->Style = ImPlot3DStyle();
  2051. }
  2052. //-----------------------------------------------------------------------------
  2053. // [SECTION] Style Utils
  2054. //-----------------------------------------------------------------------------
  2055. bool IsColorAuto(const ImVec4& col) {
  2056. return col.w == -1.0f;
  2057. }
  2058. bool IsColorAuto(ImPlot3DCol idx) {
  2059. return IsColorAuto(GImPlot3D->Style.Colors[idx]);
  2060. }
  2061. ImVec4 GetAutoColor(ImPlot3DCol idx) {
  2062. switch (idx) {
  2063. case ImPlot3DCol_Line: return IMPLOT3D_AUTO_COL; // Plot dependent
  2064. case ImPlot3DCol_Fill: return IMPLOT3D_AUTO_COL; // Plot dependent
  2065. case ImPlot3DCol_MarkerOutline: return IMPLOT3D_AUTO_COL; // Plot dependent
  2066. case ImPlot3DCol_MarkerFill: return IMPLOT3D_AUTO_COL; // Plot dependent
  2067. case ImPlot3DCol_TitleText: return ImGui::GetStyleColorVec4(ImGuiCol_Text);
  2068. case ImPlot3DCol_InlayText: return ImGui::GetStyleColorVec4(ImGuiCol_Text);
  2069. case ImPlot3DCol_FrameBg: return ImGui::GetStyleColorVec4(ImGuiCol_FrameBg);
  2070. case ImPlot3DCol_PlotBg: return ImGui::GetStyleColorVec4(ImGuiCol_WindowBg);
  2071. case ImPlot3DCol_PlotBorder: return ImGui::GetStyleColorVec4(ImGuiCol_Border);
  2072. case ImPlot3DCol_LegendBg: return ImGui::GetStyleColorVec4(ImGuiCol_PopupBg);
  2073. case ImPlot3DCol_LegendBorder: return ImGui::GetStyleColorVec4(ImGuiCol_Border);
  2074. case ImPlot3DCol_LegendText: return ImGui::GetStyleColorVec4(ImGuiCol_Text);
  2075. case ImPlot3DCol_AxisText: return ImGui::GetStyleColorVec4(ImGuiCol_Text);
  2076. case ImPlot3DCol_AxisGrid: return ImGui::GetStyleColorVec4(ImGuiCol_Text) * ImVec4(1, 1, 1, 0.25f);
  2077. case ImPlot3DCol_AxisTick: return GetStyleColorVec4(ImPlot3DCol_AxisGrid);
  2078. default: return IMPLOT3D_AUTO_COL;
  2079. }
  2080. }
  2081. const char* GetStyleColorName(ImPlot3DCol idx) {
  2082. static const char* color_names[ImPlot3DCol_COUNT] = {
  2083. "Line",
  2084. "Fill",
  2085. "MarkerOutline",
  2086. "MarkerFill",
  2087. "TitleText",
  2088. "InlayText",
  2089. "FrameBg",
  2090. "PlotBg",
  2091. "PlotBorder",
  2092. "LegendBg",
  2093. "LegendBorder",
  2094. "LegendText",
  2095. "AxisText",
  2096. "AxisGrid",
  2097. "AxisTick",
  2098. };
  2099. return color_names[idx];
  2100. }
  2101. const ImPlot3DNextItemData& GetItemData() { return GImPlot3D->NextItemData; }
  2102. } // namespace ImPlot3D
  2103. //-----------------------------------------------------------------------------
  2104. // [SECTION] ImPlot3DPoint
  2105. //-----------------------------------------------------------------------------
  2106. ImPlot3DPoint ImPlot3DPoint::operator*(float rhs) const { return ImPlot3DPoint(x * rhs, y * rhs, z * rhs); }
  2107. ImPlot3DPoint ImPlot3DPoint::operator/(float rhs) const { return ImPlot3DPoint(x / rhs, y / rhs, z / rhs); }
  2108. ImPlot3DPoint ImPlot3DPoint::operator+(const ImPlot3DPoint& rhs) const { return ImPlot3DPoint(x + rhs.x, y + rhs.y, z + rhs.z); }
  2109. ImPlot3DPoint ImPlot3DPoint::operator-(const ImPlot3DPoint& rhs) const { return ImPlot3DPoint(x - rhs.x, y - rhs.y, z - rhs.z); }
  2110. ImPlot3DPoint ImPlot3DPoint::operator*(const ImPlot3DPoint& rhs) const { return ImPlot3DPoint(x * rhs.x, y * rhs.y, z * rhs.z); }
  2111. ImPlot3DPoint ImPlot3DPoint::operator/(const ImPlot3DPoint& rhs) const { return ImPlot3DPoint(x / rhs.x, y / rhs.y, z / rhs.z); }
  2112. ImPlot3DPoint ImPlot3DPoint::operator-() const { return ImPlot3DPoint(-x, -y, -z); }
  2113. ImPlot3DPoint& ImPlot3DPoint::operator*=(float rhs) {
  2114. x *= rhs;
  2115. y *= rhs;
  2116. z *= rhs;
  2117. return *this;
  2118. }
  2119. ImPlot3DPoint& ImPlot3DPoint::operator/=(float rhs) {
  2120. x /= rhs;
  2121. y /= rhs;
  2122. z /= rhs;
  2123. return *this;
  2124. }
  2125. ImPlot3DPoint& ImPlot3DPoint::operator+=(const ImPlot3DPoint& rhs) {
  2126. x += rhs.x;
  2127. y += rhs.y;
  2128. z += rhs.z;
  2129. return *this;
  2130. }
  2131. ImPlot3DPoint& ImPlot3DPoint::operator-=(const ImPlot3DPoint& rhs) {
  2132. x -= rhs.x;
  2133. y -= rhs.y;
  2134. z -= rhs.z;
  2135. return *this;
  2136. }
  2137. ImPlot3DPoint& ImPlot3DPoint::operator*=(const ImPlot3DPoint& rhs) {
  2138. x *= rhs.x;
  2139. y *= rhs.y;
  2140. z *= rhs.z;
  2141. return *this;
  2142. }
  2143. ImPlot3DPoint& ImPlot3DPoint::operator/=(const ImPlot3DPoint& rhs) {
  2144. x /= rhs.x;
  2145. y /= rhs.y;
  2146. z /= rhs.z;
  2147. return *this;
  2148. }
  2149. bool ImPlot3DPoint::operator==(const ImPlot3DPoint& rhs) const { return x == rhs.x && y == rhs.y && z == rhs.z; }
  2150. bool ImPlot3DPoint::operator!=(const ImPlot3DPoint& rhs) const { return !(*this == rhs); }
  2151. float ImPlot3DPoint::Dot(const ImPlot3DPoint& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z; }
  2152. ImPlot3DPoint ImPlot3DPoint::Cross(const ImPlot3DPoint& rhs) const {
  2153. return ImPlot3DPoint(y * rhs.z - z * rhs.y, z * rhs.x - x * rhs.z, x * rhs.y - y * rhs.x);
  2154. }
  2155. float ImPlot3DPoint::Length() const { return ImSqrt(x * x + y * y + z * z); }
  2156. float ImPlot3DPoint::LengthSquared() const { return x * x + y * y + z * z; }
  2157. void ImPlot3DPoint::Normalize() {
  2158. float l = Length();
  2159. x /= l;
  2160. y /= l;
  2161. z /= l;
  2162. }
  2163. ImPlot3DPoint ImPlot3DPoint::Normalized() const {
  2164. float l = Length();
  2165. return ImPlot3DPoint(x / l, y / l, z / l);
  2166. }
  2167. ImPlot3DPoint operator*(float lhs, const ImPlot3DPoint& rhs) {
  2168. return ImPlot3DPoint(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z);
  2169. }
  2170. bool ImPlot3DPoint::IsNaN() const {
  2171. return ImPlot3D::ImNan(x) || ImPlot3D::ImNan(y) || ImPlot3D::ImNan(z);
  2172. }
  2173. //-----------------------------------------------------------------------------
  2174. // [SECTION] ImPlot3DBox
  2175. //-----------------------------------------------------------------------------
  2176. void ImPlot3DBox::Expand(const ImPlot3DPoint& point) {
  2177. Min.x = ImMin(Min.x, point.x);
  2178. Min.y = ImMin(Min.y, point.y);
  2179. Min.z = ImMin(Min.z, point.z);
  2180. Max.x = ImMax(Max.x, point.x);
  2181. Max.y = ImMax(Max.y, point.y);
  2182. Max.z = ImMax(Max.z, point.z);
  2183. }
  2184. bool ImPlot3DBox::Contains(const ImPlot3DPoint& point) const {
  2185. return (point.x >= Min.x && point.x <= Max.x) &&
  2186. (point.y >= Min.y && point.y <= Max.y) &&
  2187. (point.z >= Min.z && point.z <= Max.z);
  2188. }
  2189. bool ImPlot3DBox::ClipLineSegment(const ImPlot3DPoint& p0, const ImPlot3DPoint& p1, ImPlot3DPoint& p0_clipped, ImPlot3DPoint& p1_clipped) const {
  2190. // Check if the line segment is completely inside the box
  2191. if (Contains(p0) && Contains(p1)) {
  2192. p0_clipped = p0;
  2193. p1_clipped = p1;
  2194. return true;
  2195. }
  2196. // Perform Liang-Barsky 3D clipping
  2197. double t0 = 0.0;
  2198. double t1 = 1.0;
  2199. ImPlot3DPoint d = p1 - p0;
  2200. // Define the clipping boundaries
  2201. const double xmin = Min.x, xmax = Max.x;
  2202. const double ymin = Min.y, ymax = Max.y;
  2203. const double zmin = Min.z, zmax = Max.z;
  2204. // Lambda function to update t0 and t1
  2205. auto update = [&](double p, double q) -> bool {
  2206. if (p == 0.0) {
  2207. if (q < 0.0)
  2208. return false; // Line is parallel and outside the boundary
  2209. else
  2210. return true; // Line is parallel and inside or coincident with boundary
  2211. }
  2212. double r = q / p;
  2213. if (p < 0.0) {
  2214. if (r > t1)
  2215. return false; // Line is outside
  2216. if (r > t0)
  2217. t0 = r; // Move up t0
  2218. } else {
  2219. if (r < t0)
  2220. return false; // Line is outside
  2221. if (r < t1)
  2222. t1 = r; // Move down t1
  2223. }
  2224. return true;
  2225. };
  2226. // Clip against each boundary
  2227. if (!update(-d.x, p0.x - xmin))
  2228. return false; // Left
  2229. if (!update(d.x, xmax - p0.x))
  2230. return false; // Right
  2231. if (!update(-d.y, p0.y - ymin))
  2232. return false; // Bottom
  2233. if (!update(d.y, ymax - p0.y))
  2234. return false; // Top
  2235. if (!update(-d.z, p0.z - zmin))
  2236. return false; // Near
  2237. if (!update(d.z, zmax - p0.z))
  2238. return false; // Far
  2239. // Compute clipped points
  2240. p0_clipped = p0 + d * t0;
  2241. p1_clipped = p0 + d * t1;
  2242. return true;
  2243. }
  2244. //-----------------------------------------------------------------------------
  2245. // [SECTION] ImPlot3DRange
  2246. //-----------------------------------------------------------------------------
  2247. void ImPlot3DRange::Expand(float value) {
  2248. Min = ImMin(Min, value);
  2249. Max = ImMax(Max, value);
  2250. }
  2251. bool ImPlot3DRange::Contains(float value) const {
  2252. return value >= Min && value <= Max;
  2253. }
  2254. //-----------------------------------------------------------------------------
  2255. // [SECTION] ImPlot3DQuat
  2256. //-----------------------------------------------------------------------------
  2257. ImPlot3DQuat::ImPlot3DQuat(float _angle, const ImPlot3DPoint& _axis) {
  2258. float half_angle = _angle * 0.5f;
  2259. float s = std::sin(half_angle);
  2260. x = s * _axis.x;
  2261. y = s * _axis.y;
  2262. z = s * _axis.z;
  2263. w = std::cos(half_angle);
  2264. }
  2265. ImPlot3DQuat ImPlot3DQuat::FromTwoVectors(const ImPlot3DPoint& v0, const ImPlot3DPoint& v1) {
  2266. ImPlot3DQuat q;
  2267. // Compute the dot product and lengths of the vectors
  2268. float dot = v0.Dot(v1);
  2269. float length_v0 = v0.Length();
  2270. float length_v1 = v1.Length();
  2271. // Normalize the dot product
  2272. float normalized_dot = dot / (length_v0 * length_v1);
  2273. // Handle edge cases: if vectors are very close or identical
  2274. const float epsilon = 1e-6f;
  2275. if (std::fabs(normalized_dot - 1.0f) < epsilon) {
  2276. // v0 and v1 are nearly identical; return an identity quaternion
  2277. q.x = 0.0f;
  2278. q.y = 0.0f;
  2279. q.z = 0.0f;
  2280. q.w = 1.0f;
  2281. return q;
  2282. }
  2283. // Handle edge case: if vectors are opposite
  2284. if (std::fabs(normalized_dot + 1.0f) < epsilon) {
  2285. // v0 and v1 are opposite; choose an arbitrary orthogonal axis
  2286. ImPlot3DPoint arbitrary_axis = std::fabs(v0.x) > std::fabs(v0.z) ? ImPlot3DPoint(-v0.y, v0.x, 0.0f)
  2287. : ImPlot3DPoint(0.0f, -v0.z, v0.y);
  2288. arbitrary_axis.Normalize();
  2289. q.x = arbitrary_axis.x;
  2290. q.y = arbitrary_axis.y;
  2291. q.z = arbitrary_axis.z;
  2292. q.w = 0.0f;
  2293. return q;
  2294. }
  2295. // General case
  2296. ImPlot3DPoint axis = v0.Cross(v1);
  2297. axis.Normalize();
  2298. float angle = std::acos(normalized_dot);
  2299. float half_angle = angle * 0.5f;
  2300. float s = std::sin(half_angle);
  2301. q.x = s * axis.x;
  2302. q.y = s * axis.y;
  2303. q.z = s * axis.z;
  2304. q.w = std::cos(half_angle);
  2305. return q;
  2306. }
  2307. float ImPlot3DQuat::Length() const {
  2308. return std::sqrt(x * x + y * y + z * z + w * w);
  2309. }
  2310. ImPlot3DQuat ImPlot3DQuat::Normalized() const {
  2311. float l = Length();
  2312. return ImPlot3DQuat(x / l, y / l, z / l, w / l);
  2313. }
  2314. ImPlot3DQuat ImPlot3DQuat::Conjugate() const {
  2315. return ImPlot3DQuat(-x, -y, -z, w);
  2316. }
  2317. ImPlot3DQuat ImPlot3DQuat::Inverse() const {
  2318. float l_squared = x * x + y * y + z * z + w * w;
  2319. return ImPlot3DQuat(-x / l_squared, -y / l_squared, -z / l_squared, w / l_squared);
  2320. }
  2321. ImPlot3DQuat ImPlot3DQuat::operator*(const ImPlot3DQuat& rhs) const {
  2322. return ImPlot3DQuat(
  2323. w * rhs.x + x * rhs.w + y * rhs.z - z * rhs.y,
  2324. w * rhs.y - x * rhs.z + y * rhs.w + z * rhs.x,
  2325. w * rhs.z + x * rhs.y - y * rhs.x + z * rhs.w,
  2326. w * rhs.w - x * rhs.x - y * rhs.y - z * rhs.z);
  2327. }
  2328. ImPlot3DQuat& ImPlot3DQuat::Normalize() {
  2329. float l = Length();
  2330. x /= l;
  2331. y /= l;
  2332. z /= l;
  2333. w /= l;
  2334. return *this;
  2335. }
  2336. ImPlot3DPoint ImPlot3DQuat::operator*(const ImPlot3DPoint& point) const {
  2337. // Extract vector part of the quaternion
  2338. ImPlot3DPoint qv(x, y, z);
  2339. // Compute the cross products needed for rotation
  2340. ImPlot3DPoint uv = qv.Cross(point); // uv = qv x point
  2341. ImPlot3DPoint uuv = qv.Cross(uv); // uuv = qv x uv
  2342. // Compute the rotated vector
  2343. return point + (uv * w * 2.0f) + (uuv * 2.0f);
  2344. }
  2345. bool ImPlot3DQuat::operator==(const ImPlot3DQuat& rhs) const {
  2346. return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w;
  2347. }
  2348. bool ImPlot3DQuat::operator!=(const ImPlot3DQuat& rhs) const {
  2349. return !(*this == rhs);
  2350. }
  2351. ImPlot3DQuat ImPlot3DQuat::Slerp(const ImPlot3DQuat& q1, const ImPlot3DQuat& q2, float t) {
  2352. // Clamp t to [0, 1]
  2353. t = ImClamp(t, 0.0f, 1.0f);
  2354. // Compute the dot product (cosine of the angle between quaternions)
  2355. float dot = q1.x * q2.x + q1.y * q2.y + q1.z * q2.z + q1.w * q2.w;
  2356. // If the dot product is negative, negate one quaternion to take the shorter path
  2357. ImPlot3DQuat q2_ = q2;
  2358. if (dot < 0.0f) {
  2359. q2_ = ImPlot3DQuat(-q2.x, -q2.y, -q2.z, -q2.w);
  2360. dot = -dot;
  2361. }
  2362. // If the quaternions are very close, use linear interpolation to avoid numerical instability
  2363. if (dot > 0.9995f) {
  2364. return ImPlot3DQuat(
  2365. q1.x + t * (q2_.x - q1.x),
  2366. q1.y + t * (q2_.y - q1.y),
  2367. q1.z + t * (q2_.z - q1.z),
  2368. q1.w + t * (q2_.w - q1.w))
  2369. .Normalized();
  2370. }
  2371. // Compute the angle and the interpolation factors
  2372. float theta_0 = std::acos(dot); // Angle between input quaternions
  2373. float theta = theta_0 * t; // Interpolated angle
  2374. float sin_theta = std::sin(theta); // Sine of interpolated angle
  2375. float sin_theta_0 = std::sin(theta_0); // Sine of original angle
  2376. float s1 = std::cos(theta) - dot * sin_theta / sin_theta_0;
  2377. float s2 = sin_theta / sin_theta_0;
  2378. // Interpolate and return the result
  2379. return ImPlot3DQuat(
  2380. s1 * q1.x + s2 * q2_.x,
  2381. s1 * q1.y + s2 * q2_.y,
  2382. s1 * q1.z + s2 * q2_.z,
  2383. s1 * q1.w + s2 * q2_.w);
  2384. }
  2385. float ImPlot3DQuat::Dot(const ImPlot3DQuat& rhs) const {
  2386. return x * rhs.x + y * rhs.y + z * rhs.z + w * rhs.w;
  2387. }
  2388. //-----------------------------------------------------------------------------
  2389. // [SECTION] ImDrawList3D
  2390. //-----------------------------------------------------------------------------
  2391. void ImDrawList3D::PrimReserve(int idx_count, int vtx_count) {
  2392. IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0 && idx_count % 3 == 0);
  2393. int vtx_buffer_old_size = VtxBuffer.Size;
  2394. VtxBuffer.resize(vtx_buffer_old_size + vtx_count);
  2395. _VtxWritePtr = VtxBuffer.Data + vtx_buffer_old_size;
  2396. int idx_buffer_old_size = IdxBuffer.Size;
  2397. IdxBuffer.resize(idx_buffer_old_size + idx_count);
  2398. _IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size;
  2399. int z_buffer_old_size = ZBuffer.Size;
  2400. ZBuffer.resize(z_buffer_old_size + idx_count / 3);
  2401. _ZWritePtr = ZBuffer.Data + z_buffer_old_size;
  2402. }
  2403. void ImDrawList3D::PrimUnreserve(int idx_count, int vtx_count) {
  2404. IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0 && idx_count % 3 == 0);
  2405. VtxBuffer.shrink(VtxBuffer.Size - vtx_count);
  2406. IdxBuffer.shrink(IdxBuffer.Size - idx_count);
  2407. ZBuffer.shrink(ZBuffer.Size - idx_count / 3);
  2408. }
  2409. void ImDrawList3D::SortedMoveToImGuiDrawList() {
  2410. ImDrawList& draw_list = *ImGui::GetWindowDrawList();
  2411. const int tri_count = ZBuffer.Size;
  2412. if (tri_count == 0) {
  2413. // No triangles, just clear and return
  2414. VtxBuffer.clear();
  2415. IdxBuffer.clear();
  2416. ZBuffer.clear();
  2417. _VtxCurrentIdx = 0;
  2418. _VtxWritePtr = VtxBuffer.Data;
  2419. _IdxWritePtr = IdxBuffer.Data;
  2420. _ZWritePtr = ZBuffer.Data;
  2421. return;
  2422. }
  2423. // Build an array of (z, tri_idx)
  2424. struct TriRef {
  2425. float z;
  2426. int tri_idx;
  2427. };
  2428. TriRef* tris = (TriRef*)IM_ALLOC(sizeof(TriRef) * tri_count);
  2429. for (int i = 0; i < tri_count; i++) {
  2430. tris[i].z = ZBuffer[i];
  2431. tris[i].tri_idx = i;
  2432. }
  2433. // Sort by z (distance from viewer)
  2434. ImQsort(tris, (size_t)tri_count, sizeof(TriRef),
  2435. [](const void* a, const void* b) {
  2436. float za = ((const TriRef*)a)->z;
  2437. float zb = ((const TriRef*)b)->z;
  2438. return (za < zb) ? -1 : (za > zb) ? 1
  2439. : 0;
  2440. });
  2441. // Reserve space in the ImGui draw list
  2442. draw_list.PrimReserve(IdxBuffer.Size, VtxBuffer.Size);
  2443. // Copy vertices (no reordering needed)
  2444. memcpy(draw_list._VtxWritePtr, VtxBuffer.Data, VtxBuffer.Size * sizeof(ImDrawVert));
  2445. unsigned int idx_offset = draw_list._VtxCurrentIdx;
  2446. draw_list._VtxWritePtr += VtxBuffer.Size;
  2447. draw_list._VtxCurrentIdx += (unsigned int)VtxBuffer.Size;
  2448. // Maximum index allowed to not overflow ImDrawIdx
  2449. unsigned int max_index_allowed = MaxIdx() - idx_offset;
  2450. // Copy indices with triangle sorting based on distance from viewer
  2451. ImDrawIdx* idx_out = draw_list._IdxWritePtr;
  2452. ImDrawIdx* idx_in = IdxBuffer.Data;
  2453. int triangles_added = 0;
  2454. for (int i = 0; i < tri_count; i++) {
  2455. int tri_i = tris[i].tri_idx;
  2456. int base_idx = tri_i * 3;
  2457. unsigned int i0 = (unsigned int)idx_in[base_idx + 0];
  2458. unsigned int i1 = (unsigned int)idx_in[base_idx + 1];
  2459. unsigned int i2 = (unsigned int)idx_in[base_idx + 2];
  2460. // Check if after adding offset any of these indices exceed max_index_allowed
  2461. if (i0 > max_index_allowed || i1 > max_index_allowed || i2 > max_index_allowed)
  2462. break;
  2463. idx_out[0] = (ImDrawIdx)(i0 + idx_offset);
  2464. idx_out[1] = (ImDrawIdx)(i1 + idx_offset);
  2465. idx_out[2] = (ImDrawIdx)(i2 + idx_offset);
  2466. idx_out += 3;
  2467. triangles_added++;
  2468. }
  2469. draw_list._IdxWritePtr = idx_out;
  2470. // Clear local buffers since we've moved them
  2471. VtxBuffer.clear();
  2472. IdxBuffer.clear();
  2473. ZBuffer.clear();
  2474. _VtxCurrentIdx = 0;
  2475. _VtxWritePtr = VtxBuffer.Data;
  2476. _IdxWritePtr = IdxBuffer.Data;
  2477. _ZWritePtr = ZBuffer.Data;
  2478. IM_FREE(tris);
  2479. }
  2480. //-----------------------------------------------------------------------------
  2481. // [SECTION] ImPlot3DAxis
  2482. //-----------------------------------------------------------------------------
  2483. bool ImPlot3DAxis::HasLabel() const { return !Label.empty() && !ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_NoLabel); }
  2484. bool ImPlot3DAxis::HasGridLines() const { return !ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_NoGridLines); }
  2485. bool ImPlot3DAxis::HasTickLabels() const { return !ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_NoTickLabels); }
  2486. bool ImPlot3DAxis::HasTickMarks() const { return !ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_NoTickMarks); }
  2487. bool ImPlot3DAxis::IsAutoFitting() const { return ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_AutoFit); }
  2488. void ImPlot3DAxis::ExtendFit(float value) {
  2489. FitExtents.Min = ImMin(FitExtents.Min, value);
  2490. FitExtents.Max = ImMax(FitExtents.Max, value);
  2491. }
  2492. void ImPlot3DAxis::ApplyFit() {
  2493. if (!IsLockedMin() && !ImPlot3D::ImNanOrInf(FitExtents.Min))
  2494. Range.Min = FitExtents.Min;
  2495. if (!IsLockedMax() && !ImPlot3D::ImNanOrInf(FitExtents.Max))
  2496. Range.Max = FitExtents.Max;
  2497. if (ImPlot3D::ImAlmostEqual(Range.Min, Range.Max)) {
  2498. Range.Max += 0.5;
  2499. Range.Min -= 0.5;
  2500. }
  2501. FitExtents.Min = HUGE_VAL;
  2502. FitExtents.Max = -HUGE_VAL;
  2503. }
  2504. float ImPlot3DAxis::PlotToNDC(float value) const {
  2505. return (value - Range.Min) / (Range.Max - Range.Min) - 0.5f;
  2506. }
  2507. float ImPlot3DAxis::NDCToPlot(float value) const {
  2508. return Range.Min + (value + 0.5f) * (Range.Max - Range.Min);
  2509. }
  2510. //-----------------------------------------------------------------------------
  2511. // [SECTION] ImPlot3DPlot
  2512. //-----------------------------------------------------------------------------
  2513. void ImPlot3DPlot::ExtendFit(const ImPlot3DPoint& point) {
  2514. for (int i = 0; i < 3; i++) {
  2515. if (!ImPlot3D::ImNanOrInf(point[i]) && Axes[i].FitThisFrame)
  2516. Axes[i].ExtendFit(point[i]);
  2517. }
  2518. }
  2519. ImPlot3DPoint ImPlot3DPlot::RangeMin() const {
  2520. return ImPlot3DPoint(Axes[0].Range.Min, Axes[1].Range.Min, Axes[2].Range.Min);
  2521. }
  2522. ImPlot3DPoint ImPlot3DPlot::RangeMax() const {
  2523. return ImPlot3DPoint(Axes[0].Range.Max, Axes[1].Range.Max, Axes[2].Range.Max);
  2524. }
  2525. ImPlot3DPoint ImPlot3DPlot::RangeCenter() const {
  2526. return ImPlot3DPoint(
  2527. (Axes[0].Range.Min + Axes[0].Range.Max) * 0.5f,
  2528. (Axes[1].Range.Min + Axes[1].Range.Max) * 0.5f,
  2529. (Axes[2].Range.Min + Axes[2].Range.Max) * 0.5f);
  2530. }
  2531. void ImPlot3DPlot::SetRange(const ImPlot3DPoint& min, const ImPlot3DPoint& max) {
  2532. Axes[0].SetRange(min.x, max.x);
  2533. Axes[1].SetRange(min.y, max.y);
  2534. Axes[2].SetRange(min.z, max.z);
  2535. }
  2536. //-----------------------------------------------------------------------------
  2537. // [SECTION] ImPlot3DStyle
  2538. //-----------------------------------------------------------------------------
  2539. ImPlot3DStyle::ImPlot3DStyle() {
  2540. // Item style
  2541. LineWeight = 1.0f;
  2542. Marker = ImPlot3DMarker_None;
  2543. MarkerSize = 4.0f;
  2544. MarkerWeight = 1.0f;
  2545. FillAlpha = 1.0f;
  2546. // Plot style
  2547. PlotDefaultSize = ImVec2(400, 400);
  2548. PlotMinSize = ImVec2(200, 200);
  2549. PlotPadding = ImVec2(10, 10);
  2550. LabelPadding = ImVec2(5, 5);
  2551. // Legend style
  2552. LegendPadding = ImVec2(10, 10);
  2553. LegendInnerPadding = ImVec2(5, 5);
  2554. LegendSpacing = ImVec2(5, 0);
  2555. // Colors
  2556. ImPlot3D::StyleColorsAuto(this);
  2557. Colormap = ImPlot3DColormap_Deep;
  2558. };
  2559. #endif // #ifndef IMGUI_DISABLE