implot_internal.h 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667
  1. // MIT License
  2. // Copyright (c) 2023 Evan Pezent
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. // The above copyright notice and this permission notice shall be included in all
  10. // copies or substantial portions of the Software.
  11. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17. // SOFTWARE.
  18. // ImPlot v0.16
  19. // You may use this file to debug, understand or extend ImPlot features but we
  20. // don't provide any guarantee of forward compatibility!
  21. //-----------------------------------------------------------------------------
  22. // [SECTION] Header Mess
  23. //-----------------------------------------------------------------------------
  24. #pragma once
  25. #include <time.h>
  26. #include "imgui_internal.h"
  27. #ifndef IMPLOT_VERSION
  28. #error Must include implot.h before implot_internal.h
  29. #endif
  30. // Support for pre-1.84 versions. ImPool's GetSize() -> GetBufSize()
  31. #if (IMGUI_VERSION_NUM < 18303)
  32. #define GetBufSize GetSize
  33. #endif
  34. //-----------------------------------------------------------------------------
  35. // [SECTION] Constants
  36. //-----------------------------------------------------------------------------
  37. // Constants can be changed unless stated otherwise. We may move some of these
  38. // to ImPlotStyleVar_ over time.
  39. // Mimimum allowable timestamp value 01/01/1970 @ 12:00am (UTC) (DO NOT DECREASE THIS)
  40. #define IMPLOT_MIN_TIME 0
  41. // Maximum allowable timestamp value 01/01/3000 @ 12:00am (UTC) (DO NOT INCREASE THIS)
  42. #define IMPLOT_MAX_TIME 32503680000
  43. // Default label format for axis labels
  44. #define IMPLOT_LABEL_FORMAT "%g"
  45. // Max character size for tick labels
  46. #define IMPLOT_LABEL_MAX_SIZE 32
  47. //-----------------------------------------------------------------------------
  48. // [SECTION] Macros
  49. //-----------------------------------------------------------------------------
  50. #define IMPLOT_NUM_X_AXES ImAxis_Y1
  51. #define IMPLOT_NUM_Y_AXES (ImAxis_COUNT - IMPLOT_NUM_X_AXES)
  52. // Split ImU32 color into RGB components [0 255]
  53. #define IM_COL32_SPLIT_RGB(col,r,g,b) \
  54. ImU32 r = ((col >> IM_COL32_R_SHIFT) & 0xFF); \
  55. ImU32 g = ((col >> IM_COL32_G_SHIFT) & 0xFF); \
  56. ImU32 b = ((col >> IM_COL32_B_SHIFT) & 0xFF);
  57. //-----------------------------------------------------------------------------
  58. // [SECTION] Forward Declarations
  59. //-----------------------------------------------------------------------------
  60. struct ImPlotTick;
  61. struct ImPlotAxis;
  62. struct ImPlotAxisColor;
  63. struct ImPlotItem;
  64. struct ImPlotLegend;
  65. struct ImPlotPlot;
  66. struct ImPlotNextPlotData;
  67. struct ImPlotTicker;
  68. //-----------------------------------------------------------------------------
  69. // [SECTION] Context Pointer
  70. //-----------------------------------------------------------------------------
  71. #ifndef GImPlot
  72. extern IMPLOT_API ImPlotContext* GImPlot; // Current implicit context pointer
  73. #endif
  74. //-----------------------------------------------------------------------------
  75. // [SECTION] Generic Helpers
  76. //-----------------------------------------------------------------------------
  77. // Computes the common (base-10) logarithm
  78. static inline float ImLog10(float x) { return log10f(x); }
  79. static inline double ImLog10(double x) { return log10(x); }
  80. static inline float ImSinh(float x) { return sinhf(x); }
  81. static inline double ImSinh(double x) { return sinh(x); }
  82. static inline float ImAsinh(float x) { return asinhf(x); }
  83. static inline double ImAsinh(double x) { return asinh(x); }
  84. // Returns true if a flag is set
  85. template <typename TSet, typename TFlag>
  86. static inline bool ImHasFlag(TSet set, TFlag flag) { return (set & flag) == flag; }
  87. // Flips a flag in a flagset
  88. template <typename TSet, typename TFlag>
  89. static inline void ImFlipFlag(TSet& set, TFlag flag) { ImHasFlag(set, flag) ? set &= ~flag : set |= flag; }
  90. // Linearly remaps x from [x0 x1] to [y0 y1].
  91. template <typename T>
  92. static inline T ImRemap(T x, T x0, T x1, T y0, T y1) { return y0 + (x - x0) * (y1 - y0) / (x1 - x0); }
  93. // Linear rempas x from [x0 x1] to [0 1]
  94. template <typename T>
  95. static inline T ImRemap01(T x, T x0, T x1) { return (x - x0) / (x1 - x0); }
  96. // Returns always positive modulo (assumes r != 0)
  97. static inline int ImPosMod(int l, int r) { return (l % r + r) % r; }
  98. // Returns true if val is NAN
  99. static inline bool ImNan(double val) { return isnan(val); }
  100. // Returns true if val is NAN or INFINITY
  101. static inline bool ImNanOrInf(double val) { return !(val >= -DBL_MAX && val <= DBL_MAX) || ImNan(val); }
  102. // Turns NANs to 0s
  103. static inline double ImConstrainNan(double val) { return ImNan(val) ? 0 : val; }
  104. // Turns infinity to floating point maximums
  105. static inline double ImConstrainInf(double val) { return val >= DBL_MAX ? DBL_MAX : val <= -DBL_MAX ? - DBL_MAX : val; }
  106. // Turns numbers less than or equal to 0 to 0.001 (sort of arbitrary, is there a better way?)
  107. static inline double ImConstrainLog(double val) { return val <= 0 ? 0.001f : val; }
  108. // Turns numbers less than 0 to zero
  109. static inline double ImConstrainTime(double val) { return val < IMPLOT_MIN_TIME ? IMPLOT_MIN_TIME : (val > IMPLOT_MAX_TIME ? IMPLOT_MAX_TIME : val); }
  110. // True if two numbers are approximately equal using units in the last place.
  111. static inline bool ImAlmostEqual(double v1, double v2, int ulp = 2) { return ImAbs(v1-v2) < DBL_EPSILON * ImAbs(v1+v2) * ulp || ImAbs(v1-v2) < DBL_MIN; }
  112. // Finds min value in an unsorted array
  113. template <typename T>
  114. static inline T ImMinArray(const T* values, int count) { T m = values[0]; for (int i = 1; i < count; ++i) { if (values[i] < m) { m = values[i]; } } return m; }
  115. // Finds the max value in an unsorted array
  116. template <typename T>
  117. static inline T ImMaxArray(const T* values, int count) { T m = values[0]; for (int i = 1; i < count; ++i) { if (values[i] > m) { m = values[i]; } } return m; }
  118. // Finds the min and max value in an unsorted array
  119. template <typename T>
  120. static inline void ImMinMaxArray(const T* values, int count, T* min_out, T* max_out) {
  121. T Min = values[0]; T Max = values[0];
  122. for (int i = 1; i < count; ++i) {
  123. if (values[i] < Min) { Min = values[i]; }
  124. if (values[i] > Max) { Max = values[i]; }
  125. }
  126. *min_out = Min; *max_out = Max;
  127. }
  128. // Finds the sim of an array
  129. template <typename T>
  130. static inline T ImSum(const T* values, int count) {
  131. T sum = 0;
  132. for (int i = 0; i < count; ++i)
  133. sum += values[i];
  134. return sum;
  135. }
  136. // Finds the mean of an array
  137. template <typename T>
  138. static inline double ImMean(const T* values, int count) {
  139. double den = 1.0 / count;
  140. double mu = 0;
  141. for (int i = 0; i < count; ++i)
  142. mu += (double)values[i] * den;
  143. return mu;
  144. }
  145. // Finds the sample standard deviation of an array
  146. template <typename T>
  147. static inline double ImStdDev(const T* values, int count) {
  148. double den = 1.0 / (count - 1.0);
  149. double mu = ImMean(values, count);
  150. double x = 0;
  151. for (int i = 0; i < count; ++i)
  152. x += ((double)values[i] - mu) * ((double)values[i] - mu) * den;
  153. return sqrt(x);
  154. }
  155. // Mix color a and b by factor s in [0 256]
  156. static inline ImU32 ImMixU32(ImU32 a, ImU32 b, ImU32 s) {
  157. #ifdef IMPLOT_MIX64
  158. const ImU32 af = 256-s;
  159. const ImU32 bf = s;
  160. const ImU64 al = (a & 0x00ff00ff) | (((ImU64)(a & 0xff00ff00)) << 24);
  161. const ImU64 bl = (b & 0x00ff00ff) | (((ImU64)(b & 0xff00ff00)) << 24);
  162. const ImU64 mix = (al * af + bl * bf);
  163. return ((mix >> 32) & 0xff00ff00) | ((mix & 0xff00ff00) >> 8);
  164. #else
  165. const ImU32 af = 256-s;
  166. const ImU32 bf = s;
  167. const ImU32 al = (a & 0x00ff00ff);
  168. const ImU32 ah = (a & 0xff00ff00) >> 8;
  169. const ImU32 bl = (b & 0x00ff00ff);
  170. const ImU32 bh = (b & 0xff00ff00) >> 8;
  171. const ImU32 ml = (al * af + bl * bf);
  172. const ImU32 mh = (ah * af + bh * bf);
  173. return (mh & 0xff00ff00) | ((ml & 0xff00ff00) >> 8);
  174. #endif
  175. }
  176. // Lerp across an array of 32-bit collors given t in [0.0 1.0]
  177. static inline ImU32 ImLerpU32(const ImU32* colors, int size, float t) {
  178. int i1 = (int)((size - 1 ) * t);
  179. int i2 = i1 + 1;
  180. if (i2 == size || size == 1)
  181. return colors[i1];
  182. float den = 1.0f / (size - 1);
  183. float t1 = i1 * den;
  184. float t2 = i2 * den;
  185. float tr = ImRemap01(t, t1, t2);
  186. return ImMixU32(colors[i1], colors[i2], (ImU32)(tr*256));
  187. }
  188. // Set alpha channel of 32-bit color from float in range [0.0 1.0]
  189. static inline ImU32 ImAlphaU32(ImU32 col, float alpha) {
  190. return col & ~((ImU32)((1.0f-alpha)*255)<<IM_COL32_A_SHIFT);
  191. }
  192. // Returns true of two ranges overlap
  193. template <typename T>
  194. static inline bool ImOverlaps(T min_a, T max_a, T min_b, T max_b) {
  195. return min_a <= max_b && min_b <= max_a;
  196. }
  197. //-----------------------------------------------------------------------------
  198. // [SECTION] ImPlot Enums
  199. //-----------------------------------------------------------------------------
  200. typedef int ImPlotTimeUnit; // -> enum ImPlotTimeUnit_
  201. typedef int ImPlotDateFmt; // -> enum ImPlotDateFmt_
  202. typedef int ImPlotTimeFmt; // -> enum ImPlotTimeFmt_
  203. enum ImPlotTimeUnit_ {
  204. ImPlotTimeUnit_Us, // microsecond
  205. ImPlotTimeUnit_Ms, // millisecond
  206. ImPlotTimeUnit_S, // second
  207. ImPlotTimeUnit_Min, // minute
  208. ImPlotTimeUnit_Hr, // hour
  209. ImPlotTimeUnit_Day, // day
  210. ImPlotTimeUnit_Mo, // month
  211. ImPlotTimeUnit_Yr, // year
  212. ImPlotTimeUnit_COUNT
  213. };
  214. enum ImPlotDateFmt_ { // default [ ISO 8601 ]
  215. ImPlotDateFmt_None = 0,
  216. ImPlotDateFmt_DayMo, // 10/3 [ --10-03 ]
  217. ImPlotDateFmt_DayMoYr, // 10/3/91 [ 1991-10-03 ]
  218. ImPlotDateFmt_MoYr, // Oct 1991 [ 1991-10 ]
  219. ImPlotDateFmt_Mo, // Oct [ --10 ]
  220. ImPlotDateFmt_Yr // 1991 [ 1991 ]
  221. };
  222. enum ImPlotTimeFmt_ { // default [ 24 Hour Clock ]
  223. ImPlotTimeFmt_None = 0,
  224. ImPlotTimeFmt_Us, // .428 552 [ .428 552 ]
  225. ImPlotTimeFmt_SUs, // :29.428 552 [ :29.428 552 ]
  226. ImPlotTimeFmt_SMs, // :29.428 [ :29.428 ]
  227. ImPlotTimeFmt_S, // :29 [ :29 ]
  228. ImPlotTimeFmt_MinSMs, // 21:29.428 [ 21:29.428 ]
  229. ImPlotTimeFmt_HrMinSMs, // 7:21:29.428pm [ 19:21:29.428 ]
  230. ImPlotTimeFmt_HrMinS, // 7:21:29pm [ 19:21:29 ]
  231. ImPlotTimeFmt_HrMin, // 7:21pm [ 19:21 ]
  232. ImPlotTimeFmt_Hr // 7pm [ 19:00 ]
  233. };
  234. //-----------------------------------------------------------------------------
  235. // [SECTION] Callbacks
  236. //-----------------------------------------------------------------------------
  237. typedef void (*ImPlotLocator)(ImPlotTicker& ticker, const ImPlotRange& range, float pixels, bool vertical, ImPlotFormatter formatter, void* formatter_data);
  238. //-----------------------------------------------------------------------------
  239. // [SECTION] Structs
  240. //-----------------------------------------------------------------------------
  241. // Combined date/time format spec
  242. struct ImPlotDateTimeSpec {
  243. ImPlotDateTimeSpec() {}
  244. ImPlotDateTimeSpec(ImPlotDateFmt date_fmt, ImPlotTimeFmt time_fmt, bool use_24_hr_clk = false, bool use_iso_8601 = false) {
  245. Date = date_fmt;
  246. Time = time_fmt;
  247. UseISO8601 = use_iso_8601;
  248. Use24HourClock = use_24_hr_clk;
  249. }
  250. ImPlotDateFmt Date;
  251. ImPlotTimeFmt Time;
  252. bool UseISO8601;
  253. bool Use24HourClock;
  254. };
  255. // Two part timestamp struct.
  256. struct ImPlotTime {
  257. time_t S; // second part
  258. int Us; // microsecond part
  259. ImPlotTime() { S = 0; Us = 0; }
  260. ImPlotTime(time_t s, int us = 0) { S = s + us / 1000000; Us = us % 1000000; }
  261. void RollOver() { S = S + Us / 1000000; Us = Us % 1000000; }
  262. double ToDouble() const { return (double)S + (double)Us / 1000000.0; }
  263. static ImPlotTime FromDouble(double t) { return ImPlotTime((time_t)t, (int)(t * 1000000 - floor(t) * 1000000)); }
  264. };
  265. static inline ImPlotTime operator+(const ImPlotTime& lhs, const ImPlotTime& rhs)
  266. { return ImPlotTime(lhs.S + rhs.S, lhs.Us + rhs.Us); }
  267. static inline ImPlotTime operator-(const ImPlotTime& lhs, const ImPlotTime& rhs)
  268. { return ImPlotTime(lhs.S - rhs.S, lhs.Us - rhs.Us); }
  269. static inline bool operator==(const ImPlotTime& lhs, const ImPlotTime& rhs)
  270. { return lhs.S == rhs.S && lhs.Us == rhs.Us; }
  271. static inline bool operator<(const ImPlotTime& lhs, const ImPlotTime& rhs)
  272. { return lhs.S == rhs.S ? lhs.Us < rhs.Us : lhs.S < rhs.S; }
  273. static inline bool operator>(const ImPlotTime& lhs, const ImPlotTime& rhs)
  274. { return rhs < lhs; }
  275. static inline bool operator<=(const ImPlotTime& lhs, const ImPlotTime& rhs)
  276. { return lhs < rhs || lhs == rhs; }
  277. static inline bool operator>=(const ImPlotTime& lhs, const ImPlotTime& rhs)
  278. { return lhs > rhs || lhs == rhs; }
  279. // Colormap data storage
  280. struct ImPlotColormapData {
  281. ImVector<ImU32> Keys;
  282. ImVector<int> KeyCounts;
  283. ImVector<int> KeyOffsets;
  284. ImVector<ImU32> Tables;
  285. ImVector<int> TableSizes;
  286. ImVector<int> TableOffsets;
  287. ImGuiTextBuffer Text;
  288. ImVector<int> TextOffsets;
  289. ImVector<bool> Quals;
  290. ImGuiStorage Map;
  291. int Count;
  292. ImPlotColormapData() { Count = 0; }
  293. int Append(const char* name, const ImU32* keys, int count, bool qual) {
  294. if (GetIndex(name) != -1)
  295. return -1;
  296. KeyOffsets.push_back(Keys.size());
  297. KeyCounts.push_back(count);
  298. Keys.reserve(Keys.size()+count);
  299. for (int i = 0; i < count; ++i)
  300. Keys.push_back(keys[i]);
  301. TextOffsets.push_back(Text.size());
  302. Text.append(name, name + strlen(name) + 1);
  303. Quals.push_back(qual);
  304. ImGuiID id = ImHashStr(name);
  305. int idx = Count++;
  306. Map.SetInt(id,idx);
  307. _AppendTable(idx);
  308. return idx;
  309. }
  310. void _AppendTable(ImPlotColormap cmap) {
  311. int key_count = GetKeyCount(cmap);
  312. const ImU32* keys = GetKeys(cmap);
  313. int off = Tables.size();
  314. TableOffsets.push_back(off);
  315. if (IsQual(cmap)) {
  316. Tables.reserve(key_count);
  317. for (int i = 0; i < key_count; ++i)
  318. Tables.push_back(keys[i]);
  319. TableSizes.push_back(key_count);
  320. }
  321. else {
  322. int max_size = 255 * (key_count-1) + 1;
  323. Tables.reserve(off + max_size);
  324. // ImU32 last = keys[0];
  325. // Tables.push_back(last);
  326. // int n = 1;
  327. for (int i = 0; i < key_count-1; ++i) {
  328. for (int s = 0; s < 255; ++s) {
  329. ImU32 a = keys[i];
  330. ImU32 b = keys[i+1];
  331. ImU32 c = ImMixU32(a,b,s);
  332. // if (c != last) {
  333. Tables.push_back(c);
  334. // last = c;
  335. // n++;
  336. // }
  337. }
  338. }
  339. ImU32 c = keys[key_count-1];
  340. // if (c != last) {
  341. Tables.push_back(c);
  342. // n++;
  343. // }
  344. // TableSizes.push_back(n);
  345. TableSizes.push_back(max_size);
  346. }
  347. }
  348. void RebuildTables() {
  349. Tables.resize(0);
  350. TableSizes.resize(0);
  351. TableOffsets.resize(0);
  352. for (int i = 0; i < Count; ++i)
  353. _AppendTable(i);
  354. }
  355. inline bool IsQual(ImPlotColormap cmap) const { return Quals[cmap]; }
  356. inline const char* GetName(ImPlotColormap cmap) const { return cmap < Count ? Text.Buf.Data + TextOffsets[cmap] : nullptr; }
  357. inline ImPlotColormap GetIndex(const char* name) const { ImGuiID key = ImHashStr(name); return Map.GetInt(key,-1); }
  358. inline const ImU32* GetKeys(ImPlotColormap cmap) const { return &Keys[KeyOffsets[cmap]]; }
  359. inline int GetKeyCount(ImPlotColormap cmap) const { return KeyCounts[cmap]; }
  360. inline ImU32 GetKeyColor(ImPlotColormap cmap, int idx) const { return Keys[KeyOffsets[cmap]+idx]; }
  361. inline void SetKeyColor(ImPlotColormap cmap, int idx, ImU32 value) { Keys[KeyOffsets[cmap]+idx] = value; RebuildTables(); }
  362. inline const ImU32* GetTable(ImPlotColormap cmap) const { return &Tables[TableOffsets[cmap]]; }
  363. inline int GetTableSize(ImPlotColormap cmap) const { return TableSizes[cmap]; }
  364. inline ImU32 GetTableColor(ImPlotColormap cmap, int idx) const { return Tables[TableOffsets[cmap]+idx]; }
  365. inline ImU32 LerpTable(ImPlotColormap cmap, float t) const {
  366. int off = TableOffsets[cmap];
  367. int siz = TableSizes[cmap];
  368. int idx = Quals[cmap] ? ImClamp((int)(siz*t),0,siz-1) : (int)((siz - 1) * t + 0.5f);
  369. return Tables[off + idx];
  370. }
  371. };
  372. // ImPlotPoint with positive/negative error values
  373. struct ImPlotPointError {
  374. double X, Y, Neg, Pos;
  375. ImPlotPointError(double x, double y, double neg, double pos) {
  376. X = x; Y = y; Neg = neg; Pos = pos;
  377. }
  378. };
  379. // Interior plot label/annotation
  380. struct ImPlotAnnotation {
  381. ImVec2 Pos;
  382. ImVec2 Offset;
  383. ImU32 ColorBg;
  384. ImU32 ColorFg;
  385. int TextOffset;
  386. bool Clamp;
  387. ImPlotAnnotation() {
  388. ColorBg = ColorFg = 0;
  389. TextOffset = 0;
  390. Clamp = false;
  391. }
  392. };
  393. // Collection of plot labels
  394. struct ImPlotAnnotationCollection {
  395. ImVector<ImPlotAnnotation> Annotations;
  396. ImGuiTextBuffer TextBuffer;
  397. int Size;
  398. ImPlotAnnotationCollection() { Reset(); }
  399. void AppendV(const ImVec2& pos, const ImVec2& off, ImU32 bg, ImU32 fg, bool clamp, const char* fmt, va_list args) IM_FMTLIST(7) {
  400. ImPlotAnnotation an;
  401. an.Pos = pos; an.Offset = off;
  402. an.ColorBg = bg; an.ColorFg = fg;
  403. an.TextOffset = TextBuffer.size();
  404. an.Clamp = clamp;
  405. Annotations.push_back(an);
  406. TextBuffer.appendfv(fmt, args);
  407. const char nul[] = "";
  408. TextBuffer.append(nul,nul+1);
  409. Size++;
  410. }
  411. void Append(const ImVec2& pos, const ImVec2& off, ImU32 bg, ImU32 fg, bool clamp, const char* fmt, ...) IM_FMTARGS(7) {
  412. va_list args;
  413. va_start(args, fmt);
  414. AppendV(pos, off, bg, fg, clamp, fmt, args);
  415. va_end(args);
  416. }
  417. const char* GetText(int idx) {
  418. return TextBuffer.Buf.Data + Annotations[idx].TextOffset;
  419. }
  420. void Reset() {
  421. Annotations.shrink(0);
  422. TextBuffer.Buf.shrink(0);
  423. Size = 0;
  424. }
  425. };
  426. struct ImPlotTag {
  427. ImAxis Axis;
  428. double Value;
  429. ImU32 ColorBg;
  430. ImU32 ColorFg;
  431. int TextOffset;
  432. };
  433. struct ImPlotTagCollection {
  434. ImVector<ImPlotTag> Tags;
  435. ImGuiTextBuffer TextBuffer;
  436. int Size;
  437. ImPlotTagCollection() { Reset(); }
  438. void AppendV(ImAxis axis, double value, ImU32 bg, ImU32 fg, const char* fmt, va_list args) IM_FMTLIST(6) {
  439. ImPlotTag tag;
  440. tag.Axis = axis;
  441. tag.Value = value;
  442. tag.ColorBg = bg;
  443. tag.ColorFg = fg;
  444. tag.TextOffset = TextBuffer.size();
  445. Tags.push_back(tag);
  446. TextBuffer.appendfv(fmt, args);
  447. const char nul[] = "";
  448. TextBuffer.append(nul,nul+1);
  449. Size++;
  450. }
  451. void Append(ImAxis axis, double value, ImU32 bg, ImU32 fg, const char* fmt, ...) IM_FMTARGS(6) {
  452. va_list args;
  453. va_start(args, fmt);
  454. AppendV(axis, value, bg, fg, fmt, args);
  455. va_end(args);
  456. }
  457. const char* GetText(int idx) {
  458. return TextBuffer.Buf.Data + Tags[idx].TextOffset;
  459. }
  460. void Reset() {
  461. Tags.shrink(0);
  462. TextBuffer.Buf.shrink(0);
  463. Size = 0;
  464. }
  465. };
  466. // Tick mark info
  467. struct ImPlotTick
  468. {
  469. double PlotPos;
  470. float PixelPos;
  471. ImVec2 LabelSize;
  472. int TextOffset;
  473. bool Major;
  474. bool ShowLabel;
  475. int Level;
  476. int Idx;
  477. ImPlotTick(double value, bool major, int level, bool show_label) {
  478. PixelPos = 0;
  479. PlotPos = value;
  480. Major = major;
  481. ShowLabel = show_label;
  482. Level = level;
  483. TextOffset = -1;
  484. }
  485. };
  486. // Collection of ticks
  487. struct ImPlotTicker {
  488. ImVector<ImPlotTick> Ticks;
  489. ImGuiTextBuffer TextBuffer;
  490. ImVec2 MaxSize;
  491. ImVec2 LateSize;
  492. int Levels;
  493. ImPlotTicker() {
  494. Reset();
  495. }
  496. ImPlotTick& AddTick(double value, bool major, int level, bool show_label, const char* label) {
  497. ImPlotTick tick(value, major, level, show_label);
  498. if (show_label && label != nullptr) {
  499. tick.TextOffset = TextBuffer.size();
  500. TextBuffer.append(label, label + strlen(label) + 1);
  501. tick.LabelSize = ImGui::CalcTextSize(TextBuffer.Buf.Data + tick.TextOffset);
  502. }
  503. return AddTick(tick);
  504. }
  505. ImPlotTick& AddTick(double value, bool major, int level, bool show_label, ImPlotFormatter formatter, void* data) {
  506. ImPlotTick tick(value, major, level, show_label);
  507. if (show_label && formatter != nullptr) {
  508. char buff[IMPLOT_LABEL_MAX_SIZE];
  509. tick.TextOffset = TextBuffer.size();
  510. formatter(tick.PlotPos, buff, sizeof(buff), data);
  511. TextBuffer.append(buff, buff + strlen(buff) + 1);
  512. tick.LabelSize = ImGui::CalcTextSize(TextBuffer.Buf.Data + tick.TextOffset);
  513. }
  514. return AddTick(tick);
  515. }
  516. inline ImPlotTick& AddTick(ImPlotTick tick) {
  517. if (tick.ShowLabel) {
  518. MaxSize.x = tick.LabelSize.x > MaxSize.x ? tick.LabelSize.x : MaxSize.x;
  519. MaxSize.y = tick.LabelSize.y > MaxSize.y ? tick.LabelSize.y : MaxSize.y;
  520. }
  521. tick.Idx = Ticks.size();
  522. Ticks.push_back(tick);
  523. return Ticks.back();
  524. }
  525. const char* GetText(int idx) const {
  526. return TextBuffer.Buf.Data + Ticks[idx].TextOffset;
  527. }
  528. const char* GetText(const ImPlotTick& tick) {
  529. return GetText(tick.Idx);
  530. }
  531. void OverrideSizeLate(const ImVec2& size) {
  532. LateSize.x = size.x > LateSize.x ? size.x : LateSize.x;
  533. LateSize.y = size.y > LateSize.y ? size.y : LateSize.y;
  534. }
  535. void Reset() {
  536. Ticks.shrink(0);
  537. TextBuffer.Buf.shrink(0);
  538. MaxSize = LateSize;
  539. LateSize = ImVec2(0,0);
  540. Levels = 1;
  541. }
  542. int TickCount() const {
  543. return Ticks.Size;
  544. }
  545. };
  546. // Axis state information that must persist after EndPlot
  547. struct ImPlotAxis
  548. {
  549. ImGuiID ID;
  550. ImPlotAxisFlags Flags;
  551. ImPlotAxisFlags PreviousFlags;
  552. ImPlotRange Range;
  553. ImPlotCond RangeCond;
  554. ImPlotScale Scale;
  555. ImPlotRange FitExtents;
  556. ImPlotAxis* OrthoAxis;
  557. ImPlotRange ConstraintRange;
  558. ImPlotRange ConstraintZoom;
  559. ImPlotTicker Ticker;
  560. ImPlotFormatter Formatter;
  561. void* FormatterData;
  562. char FormatSpec[16];
  563. ImPlotLocator Locator;
  564. double* LinkedMin;
  565. double* LinkedMax;
  566. int PickerLevel;
  567. ImPlotTime PickerTimeMin, PickerTimeMax;
  568. ImPlotTransform TransformForward;
  569. ImPlotTransform TransformInverse;
  570. void* TransformData;
  571. float PixelMin, PixelMax;
  572. double ScaleMin, ScaleMax;
  573. double ScaleToPixel;
  574. float Datum1, Datum2;
  575. ImRect HoverRect;
  576. int LabelOffset;
  577. ImU32 ColorMaj, ColorMin, ColorTick, ColorTxt, ColorBg, ColorHov, ColorAct, ColorHiLi;
  578. bool Enabled;
  579. bool Vertical;
  580. bool FitThisFrame;
  581. bool HasRange;
  582. bool HasFormatSpec;
  583. bool ShowDefaultTicks;
  584. bool Hovered;
  585. bool Held;
  586. ImPlotAxis() {
  587. ID = 0;
  588. Flags = PreviousFlags = ImPlotAxisFlags_None;
  589. Range.Min = 0;
  590. Range.Max = 1;
  591. Scale = ImPlotScale_Linear;
  592. TransformForward = TransformInverse = nullptr;
  593. TransformData = nullptr;
  594. FitExtents.Min = HUGE_VAL;
  595. FitExtents.Max = -HUGE_VAL;
  596. OrthoAxis = nullptr;
  597. ConstraintRange = ImPlotRange(-INFINITY,INFINITY);
  598. ConstraintZoom = ImPlotRange(DBL_MIN,INFINITY);
  599. LinkedMin = LinkedMax = nullptr;
  600. PickerLevel = 0;
  601. Datum1 = Datum2 = 0;
  602. PixelMin = PixelMax = 0;
  603. LabelOffset = -1;
  604. ColorMaj = ColorMin = ColorTick = ColorTxt = ColorBg = ColorHov = ColorAct = 0;
  605. ColorHiLi = IM_COL32_BLACK_TRANS;
  606. Formatter = nullptr;
  607. FormatterData = nullptr;
  608. Locator = nullptr;
  609. Enabled = Hovered = Held = FitThisFrame = HasRange = HasFormatSpec = false;
  610. ShowDefaultTicks = true;
  611. }
  612. inline void Reset() {
  613. Enabled = false;
  614. Scale = ImPlotScale_Linear;
  615. TransformForward = TransformInverse = nullptr;
  616. TransformData = nullptr;
  617. LabelOffset = -1;
  618. HasFormatSpec = false;
  619. Formatter = nullptr;
  620. FormatterData = nullptr;
  621. Locator = nullptr;
  622. ShowDefaultTicks = true;
  623. FitThisFrame = false;
  624. FitExtents.Min = HUGE_VAL;
  625. FitExtents.Max = -HUGE_VAL;
  626. OrthoAxis = nullptr;
  627. ConstraintRange = ImPlotRange(-INFINITY,INFINITY);
  628. ConstraintZoom = ImPlotRange(DBL_MIN,INFINITY);
  629. Ticker.Reset();
  630. }
  631. inline bool SetMin(double _min, bool force=false) {
  632. if (!force && IsLockedMin())
  633. return false;
  634. _min = ImConstrainNan(ImConstrainInf(_min));
  635. if (_min < ConstraintRange.Min)
  636. _min = ConstraintRange.Min;
  637. double z = Range.Max - _min;
  638. if (z < ConstraintZoom.Min)
  639. _min = Range.Max - ConstraintZoom.Min;
  640. if (z > ConstraintZoom.Max)
  641. _min = Range.Max - ConstraintZoom.Max;
  642. if (_min >= Range.Max)
  643. return false;
  644. Range.Min = _min;
  645. PickerTimeMin = ImPlotTime::FromDouble(Range.Min);
  646. UpdateTransformCache();
  647. return true;
  648. };
  649. inline bool SetMax(double _max, bool force=false) {
  650. if (!force && IsLockedMax())
  651. return false;
  652. _max = ImConstrainNan(ImConstrainInf(_max));
  653. if (_max > ConstraintRange.Max)
  654. _max = ConstraintRange.Max;
  655. double z = _max - Range.Min;
  656. if (z < ConstraintZoom.Min)
  657. _max = Range.Min + ConstraintZoom.Min;
  658. if (z > ConstraintZoom.Max)
  659. _max = Range.Min + ConstraintZoom.Max;
  660. if (_max <= Range.Min)
  661. return false;
  662. Range.Max = _max;
  663. PickerTimeMax = ImPlotTime::FromDouble(Range.Max);
  664. UpdateTransformCache();
  665. return true;
  666. };
  667. inline void SetRange(double v1, double v2) {
  668. Range.Min = ImMin(v1,v2);
  669. Range.Max = ImMax(v1,v2);
  670. Constrain();
  671. PickerTimeMin = ImPlotTime::FromDouble(Range.Min);
  672. PickerTimeMax = ImPlotTime::FromDouble(Range.Max);
  673. UpdateTransformCache();
  674. }
  675. inline void SetRange(const ImPlotRange& range) {
  676. SetRange(range.Min, range.Max);
  677. }
  678. inline void SetAspect(double unit_per_pix) {
  679. double new_size = unit_per_pix * PixelSize();
  680. double delta = (new_size - Range.Size()) * 0.5;
  681. if (IsLocked())
  682. return;
  683. else if (IsLockedMin() && !IsLockedMax())
  684. SetRange(Range.Min, Range.Max + 2*delta);
  685. else if (!IsLockedMin() && IsLockedMax())
  686. SetRange(Range.Min - 2*delta, Range.Max);
  687. else
  688. SetRange(Range.Min - delta, Range.Max + delta);
  689. }
  690. inline float PixelSize() const { return ImAbs(PixelMax - PixelMin); }
  691. inline double GetAspect() const { return Range.Size() / PixelSize(); }
  692. inline void Constrain() {
  693. Range.Min = ImConstrainNan(ImConstrainInf(Range.Min));
  694. Range.Max = ImConstrainNan(ImConstrainInf(Range.Max));
  695. if (Range.Min < ConstraintRange.Min)
  696. Range.Min = ConstraintRange.Min;
  697. if (Range.Max > ConstraintRange.Max)
  698. Range.Max = ConstraintRange.Max;
  699. double z = Range.Size();
  700. if (z < ConstraintZoom.Min) {
  701. double delta = (ConstraintZoom.Min - z) * 0.5;
  702. Range.Min -= delta;
  703. Range.Max += delta;
  704. }
  705. if (z > ConstraintZoom.Max) {
  706. double delta = (z - ConstraintZoom.Max) * 0.5;
  707. Range.Min += delta;
  708. Range.Max -= delta;
  709. }
  710. if (Range.Max <= Range.Min)
  711. Range.Max = Range.Min + DBL_EPSILON;
  712. }
  713. inline void UpdateTransformCache() {
  714. ScaleToPixel = (PixelMax - PixelMin) / Range.Size();
  715. if (TransformForward != nullptr) {
  716. ScaleMin = TransformForward(Range.Min, TransformData);
  717. ScaleMax = TransformForward(Range.Max, TransformData);
  718. }
  719. else {
  720. ScaleMin = Range.Min;
  721. ScaleMax = Range.Max;
  722. }
  723. }
  724. inline float PlotToPixels(double plt) const {
  725. if (TransformForward != nullptr) {
  726. double s = TransformForward(plt, TransformData);
  727. double t = (s - ScaleMin) / (ScaleMax - ScaleMin);
  728. plt = Range.Min + Range.Size() * t;
  729. }
  730. return (float)(PixelMin + ScaleToPixel * (plt - Range.Min));
  731. }
  732. inline double PixelsToPlot(float pix) const {
  733. double plt = (pix - PixelMin) / ScaleToPixel + Range.Min;
  734. if (TransformInverse != nullptr) {
  735. double t = (plt - Range.Min) / Range.Size();
  736. double s = t * (ScaleMax - ScaleMin) + ScaleMin;
  737. plt = TransformInverse(s, TransformData);
  738. }
  739. return plt;
  740. }
  741. inline void ExtendFit(double v) {
  742. if (!ImNanOrInf(v) && v >= ConstraintRange.Min && v <= ConstraintRange.Max) {
  743. FitExtents.Min = v < FitExtents.Min ? v : FitExtents.Min;
  744. FitExtents.Max = v > FitExtents.Max ? v : FitExtents.Max;
  745. }
  746. }
  747. inline void ExtendFitWith(ImPlotAxis& alt, double v, double v_alt) {
  748. if (ImHasFlag(Flags, ImPlotAxisFlags_RangeFit) && !alt.Range.Contains(v_alt))
  749. return;
  750. if (!ImNanOrInf(v) && v >= ConstraintRange.Min && v <= ConstraintRange.Max) {
  751. FitExtents.Min = v < FitExtents.Min ? v : FitExtents.Min;
  752. FitExtents.Max = v > FitExtents.Max ? v : FitExtents.Max;
  753. }
  754. }
  755. inline void ApplyFit(float padding) {
  756. const double ext_size = FitExtents.Size() * 0.5;
  757. FitExtents.Min -= ext_size * padding;
  758. FitExtents.Max += ext_size * padding;
  759. if (!IsLockedMin() && !ImNanOrInf(FitExtents.Min))
  760. Range.Min = FitExtents.Min;
  761. if (!IsLockedMax() && !ImNanOrInf(FitExtents.Max))
  762. Range.Max = FitExtents.Max;
  763. if (ImAlmostEqual(Range.Min, Range.Max)) {
  764. Range.Max += 0.5;
  765. Range.Min -= 0.5;
  766. }
  767. Constrain();
  768. UpdateTransformCache();
  769. }
  770. inline bool HasLabel() const { return LabelOffset != -1 && !ImHasFlag(Flags, ImPlotAxisFlags_NoLabel); }
  771. inline bool HasGridLines() const { return !ImHasFlag(Flags, ImPlotAxisFlags_NoGridLines); }
  772. inline bool HasTickLabels() const { return !ImHasFlag(Flags, ImPlotAxisFlags_NoTickLabels); }
  773. inline bool HasTickMarks() const { return !ImHasFlag(Flags, ImPlotAxisFlags_NoTickMarks); }
  774. inline bool WillRender() const { return Enabled && (HasGridLines() || HasTickLabels() || HasTickMarks()); }
  775. inline bool IsOpposite() const { return ImHasFlag(Flags, ImPlotAxisFlags_Opposite); }
  776. inline bool IsInverted() const { return ImHasFlag(Flags, ImPlotAxisFlags_Invert); }
  777. inline bool IsForeground() const { return ImHasFlag(Flags, ImPlotAxisFlags_Foreground); }
  778. inline bool IsAutoFitting() const { return ImHasFlag(Flags, ImPlotAxisFlags_AutoFit); }
  779. inline bool CanInitFit() const { return !ImHasFlag(Flags, ImPlotAxisFlags_NoInitialFit) && !HasRange && !LinkedMin && !LinkedMax; }
  780. inline bool IsRangeLocked() const { return HasRange && RangeCond == ImPlotCond_Always; }
  781. inline bool IsLockedMin() const { return !Enabled || IsRangeLocked() || ImHasFlag(Flags, ImPlotAxisFlags_LockMin); }
  782. inline bool IsLockedMax() const { return !Enabled || IsRangeLocked() || ImHasFlag(Flags, ImPlotAxisFlags_LockMax); }
  783. inline bool IsLocked() const { return IsLockedMin() && IsLockedMax(); }
  784. inline bool IsInputLockedMin() const { return IsLockedMin() || IsAutoFitting(); }
  785. inline bool IsInputLockedMax() const { return IsLockedMax() || IsAutoFitting(); }
  786. inline bool IsInputLocked() const { return IsLocked() || IsAutoFitting(); }
  787. inline bool HasMenus() const { return !ImHasFlag(Flags, ImPlotAxisFlags_NoMenus); }
  788. inline bool IsPanLocked(bool increasing) {
  789. if (ImHasFlag(Flags, ImPlotAxisFlags_PanStretch)) {
  790. return IsInputLocked();
  791. }
  792. else {
  793. if (IsLockedMin() || IsLockedMax() || IsAutoFitting())
  794. return false;
  795. if (increasing)
  796. return Range.Max == ConstraintRange.Max;
  797. else
  798. return Range.Min == ConstraintRange.Min;
  799. }
  800. }
  801. void PushLinks() {
  802. if (LinkedMin) { *LinkedMin = Range.Min; }
  803. if (LinkedMax) { *LinkedMax = Range.Max; }
  804. }
  805. void PullLinks() {
  806. if (LinkedMin && LinkedMax) { SetRange(*LinkedMin, *LinkedMax); }
  807. else if (LinkedMin) { SetMin(*LinkedMin,true); }
  808. else if (LinkedMax) { SetMax(*LinkedMax,true); }
  809. }
  810. };
  811. // Align plots group data
  812. struct ImPlotAlignmentData {
  813. bool Vertical;
  814. float PadA;
  815. float PadB;
  816. float PadAMax;
  817. float PadBMax;
  818. ImPlotAlignmentData() {
  819. Vertical = true;
  820. PadA = PadB = PadAMax = PadBMax = 0;
  821. }
  822. void Begin() { PadAMax = PadBMax = 0; }
  823. void Update(float& pad_a, float& pad_b, float& delta_a, float& delta_b) {
  824. float bak_a = pad_a; float bak_b = pad_b;
  825. if (PadAMax < pad_a) { PadAMax = pad_a; }
  826. if (PadBMax < pad_b) { PadBMax = pad_b; }
  827. if (pad_a < PadA) { pad_a = PadA; delta_a = pad_a - bak_a; } else { delta_a = 0; }
  828. if (pad_b < PadB) { pad_b = PadB; delta_b = pad_b - bak_b; } else { delta_b = 0; }
  829. }
  830. void End() { PadA = PadAMax; PadB = PadBMax; }
  831. void Reset() { PadA = PadB = PadAMax = PadBMax = 0; }
  832. };
  833. // State information for Plot items
  834. struct ImPlotItem
  835. {
  836. ImGuiID ID;
  837. ImU32 Color;
  838. ImRect LegendHoverRect;
  839. int NameOffset;
  840. bool Show;
  841. bool LegendHovered;
  842. bool SeenThisFrame;
  843. ImPlotItem() {
  844. ID = 0;
  845. Color = IM_COL32_WHITE;
  846. NameOffset = -1;
  847. Show = true;
  848. SeenThisFrame = false;
  849. LegendHovered = false;
  850. }
  851. ~ImPlotItem() { ID = 0; }
  852. };
  853. // Holds Legend state
  854. struct ImPlotLegend
  855. {
  856. ImPlotLegendFlags Flags;
  857. ImPlotLegendFlags PreviousFlags;
  858. ImPlotLocation Location;
  859. ImPlotLocation PreviousLocation;
  860. ImVector<int> Indices;
  861. ImGuiTextBuffer Labels;
  862. ImRect Rect;
  863. bool Hovered;
  864. bool Held;
  865. bool CanGoInside;
  866. ImPlotLegend() {
  867. Flags = PreviousFlags = ImPlotLegendFlags_None;
  868. CanGoInside = true;
  869. Hovered = Held = false;
  870. Location = PreviousLocation = ImPlotLocation_NorthWest;
  871. }
  872. void Reset() { Indices.shrink(0); Labels.Buf.shrink(0); }
  873. };
  874. // Holds Items and Legend data
  875. struct ImPlotItemGroup
  876. {
  877. ImGuiID ID;
  878. ImPlotLegend Legend;
  879. ImPool<ImPlotItem> ItemPool;
  880. int ColormapIdx;
  881. ImPlotItemGroup() { ID = 0; ColormapIdx = 0; }
  882. int GetItemCount() const { return ItemPool.GetBufSize(); }
  883. ImGuiID GetItemID(const char* label_id) { return ImGui::GetID(label_id); /* GetIDWithSeed */ }
  884. ImPlotItem* GetItem(ImGuiID id) { return ItemPool.GetByKey(id); }
  885. ImPlotItem* GetItem(const char* label_id) { return GetItem(GetItemID(label_id)); }
  886. ImPlotItem* GetOrAddItem(ImGuiID id) { return ItemPool.GetOrAddByKey(id); }
  887. ImPlotItem* GetItemByIndex(int i) { return ItemPool.GetByIndex(i); }
  888. int GetItemIndex(ImPlotItem* item) { return ItemPool.GetIndex(item); }
  889. int GetLegendCount() const { return Legend.Indices.size(); }
  890. ImPlotItem* GetLegendItem(int i) { return ItemPool.GetByIndex(Legend.Indices[i]); }
  891. const char* GetLegendLabel(int i) { return Legend.Labels.Buf.Data + GetLegendItem(i)->NameOffset; }
  892. void Reset() { ItemPool.Clear(); Legend.Reset(); ColormapIdx = 0; }
  893. };
  894. // Holds Plot state information that must persist after EndPlot
  895. struct ImPlotPlot
  896. {
  897. ImGuiID ID;
  898. ImPlotFlags Flags;
  899. ImPlotFlags PreviousFlags;
  900. ImPlotLocation MouseTextLocation;
  901. ImPlotMouseTextFlags MouseTextFlags;
  902. ImPlotAxis Axes[ImAxis_COUNT];
  903. ImGuiTextBuffer TextBuffer;
  904. ImPlotItemGroup Items;
  905. ImAxis CurrentX;
  906. ImAxis CurrentY;
  907. ImRect FrameRect;
  908. ImRect CanvasRect;
  909. ImRect PlotRect;
  910. ImRect AxesRect;
  911. ImRect SelectRect;
  912. ImVec2 SelectStart;
  913. int TitleOffset;
  914. bool JustCreated;
  915. bool Initialized;
  916. bool SetupLocked;
  917. bool FitThisFrame;
  918. bool Hovered;
  919. bool Held;
  920. bool Selecting;
  921. bool Selected;
  922. bool ContextLocked;
  923. ImPlotPlot() {
  924. Flags = PreviousFlags = ImPlotFlags_None;
  925. for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i)
  926. XAxis(i).Vertical = false;
  927. for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i)
  928. YAxis(i).Vertical = true;
  929. SelectStart = ImVec2(0,0);
  930. CurrentX = ImAxis_X1;
  931. CurrentY = ImAxis_Y1;
  932. MouseTextLocation = ImPlotLocation_South | ImPlotLocation_East;
  933. MouseTextFlags = ImPlotMouseTextFlags_None;
  934. TitleOffset = -1;
  935. JustCreated = true;
  936. Initialized = SetupLocked = FitThisFrame = false;
  937. Hovered = Held = Selected = Selecting = ContextLocked = false;
  938. }
  939. inline bool IsInputLocked() const {
  940. for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i) {
  941. if (!XAxis(i).IsInputLocked())
  942. return false;
  943. }
  944. for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i) {
  945. if (!YAxis(i).IsInputLocked())
  946. return false;
  947. }
  948. return true;
  949. }
  950. inline void ClearTextBuffer() { TextBuffer.Buf.shrink(0); }
  951. inline void SetTitle(const char* title) {
  952. if (title && ImGui::FindRenderedTextEnd(title, nullptr) != title) {
  953. TitleOffset = TextBuffer.size();
  954. TextBuffer.append(title, title + strlen(title) + 1);
  955. }
  956. else {
  957. TitleOffset = -1;
  958. }
  959. }
  960. inline bool HasTitle() const { return TitleOffset != -1 && !ImHasFlag(Flags, ImPlotFlags_NoTitle); }
  961. inline const char* GetTitle() const { return TextBuffer.Buf.Data + TitleOffset; }
  962. inline ImPlotAxis& XAxis(int i) { return Axes[ImAxis_X1 + i]; }
  963. inline const ImPlotAxis& XAxis(int i) const { return Axes[ImAxis_X1 + i]; }
  964. inline ImPlotAxis& YAxis(int i) { return Axes[ImAxis_Y1 + i]; }
  965. inline const ImPlotAxis& YAxis(int i) const { return Axes[ImAxis_Y1 + i]; }
  966. inline int EnabledAxesX() {
  967. int cnt = 0;
  968. for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i)
  969. cnt += XAxis(i).Enabled;
  970. return cnt;
  971. }
  972. inline int EnabledAxesY() {
  973. int cnt = 0;
  974. for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i)
  975. cnt += YAxis(i).Enabled;
  976. return cnt;
  977. }
  978. inline void SetAxisLabel(ImPlotAxis& axis, const char* label) {
  979. if (label && ImGui::FindRenderedTextEnd(label, nullptr) != label) {
  980. axis.LabelOffset = TextBuffer.size();
  981. TextBuffer.append(label, label + strlen(label) + 1);
  982. }
  983. else {
  984. axis.LabelOffset = -1;
  985. }
  986. }
  987. inline const char* GetAxisLabel(const ImPlotAxis& axis) const { return TextBuffer.Buf.Data + axis.LabelOffset; }
  988. };
  989. // Holds subplot data that must persist after EndSubplot
  990. struct ImPlotSubplot {
  991. ImGuiID ID;
  992. ImPlotSubplotFlags Flags;
  993. ImPlotSubplotFlags PreviousFlags;
  994. ImPlotItemGroup Items;
  995. int Rows;
  996. int Cols;
  997. int CurrentIdx;
  998. ImRect FrameRect;
  999. ImRect GridRect;
  1000. ImVec2 CellSize;
  1001. ImVector<ImPlotAlignmentData> RowAlignmentData;
  1002. ImVector<ImPlotAlignmentData> ColAlignmentData;
  1003. ImVector<float> RowRatios;
  1004. ImVector<float> ColRatios;
  1005. ImVector<ImPlotRange> RowLinkData;
  1006. ImVector<ImPlotRange> ColLinkData;
  1007. float TempSizes[2];
  1008. bool FrameHovered;
  1009. bool HasTitle;
  1010. ImPlotSubplot() {
  1011. ID = 0;
  1012. Flags = PreviousFlags = ImPlotSubplotFlags_None;
  1013. Rows = Cols = CurrentIdx = 0;
  1014. Items.Legend.Location = ImPlotLocation_North;
  1015. Items.Legend.Flags = ImPlotLegendFlags_Horizontal|ImPlotLegendFlags_Outside;
  1016. Items.Legend.CanGoInside = false;
  1017. TempSizes[0] = TempSizes[1] = 0;
  1018. FrameHovered = false;
  1019. HasTitle = false;
  1020. }
  1021. };
  1022. // Temporary data storage for upcoming plot
  1023. struct ImPlotNextPlotData
  1024. {
  1025. ImPlotCond RangeCond[ImAxis_COUNT];
  1026. ImPlotRange Range[ImAxis_COUNT];
  1027. bool HasRange[ImAxis_COUNT];
  1028. bool Fit[ImAxis_COUNT];
  1029. double* LinkedMin[ImAxis_COUNT];
  1030. double* LinkedMax[ImAxis_COUNT];
  1031. ImPlotNextPlotData() { Reset(); }
  1032. void Reset() {
  1033. for (int i = 0; i < ImAxis_COUNT; ++i) {
  1034. HasRange[i] = false;
  1035. Fit[i] = false;
  1036. LinkedMin[i] = LinkedMax[i] = nullptr;
  1037. }
  1038. }
  1039. };
  1040. // Temporary data storage for upcoming item
  1041. struct ImPlotNextItemData {
  1042. ImVec4 Colors[5]; // ImPlotCol_Line, ImPlotCol_Fill, ImPlotCol_MarkerOutline, ImPlotCol_MarkerFill, ImPlotCol_ErrorBar
  1043. float LineWeight;
  1044. ImPlotMarker Marker;
  1045. float MarkerSize;
  1046. float MarkerWeight;
  1047. float FillAlpha;
  1048. float ErrorBarSize;
  1049. float ErrorBarWeight;
  1050. float DigitalBitHeight;
  1051. float DigitalBitGap;
  1052. bool RenderLine;
  1053. bool RenderFill;
  1054. bool RenderMarkerLine;
  1055. bool RenderMarkerFill;
  1056. bool HasHidden;
  1057. bool Hidden;
  1058. ImPlotCond HiddenCond;
  1059. ImPlotNextItemData() { Reset(); }
  1060. void Reset() {
  1061. for (int i = 0; i < 5; ++i)
  1062. Colors[i] = IMPLOT_AUTO_COL;
  1063. LineWeight = MarkerSize = MarkerWeight = FillAlpha = ErrorBarSize = ErrorBarWeight = DigitalBitHeight = DigitalBitGap = IMPLOT_AUTO;
  1064. Marker = IMPLOT_AUTO;
  1065. HasHidden = Hidden = false;
  1066. }
  1067. };
  1068. // Holds state information that must persist between calls to BeginPlot()/EndPlot()
  1069. struct ImPlotContext {
  1070. // Plot States
  1071. ImPool<ImPlotPlot> Plots;
  1072. ImPool<ImPlotSubplot> Subplots;
  1073. ImPlotPlot* CurrentPlot;
  1074. ImPlotSubplot* CurrentSubplot;
  1075. ImPlotItemGroup* CurrentItems;
  1076. ImPlotItem* CurrentItem;
  1077. ImPlotItem* PreviousItem;
  1078. // Tick Marks and Labels
  1079. ImPlotTicker CTicker;
  1080. // Annotation and Tabs
  1081. ImPlotAnnotationCollection Annotations;
  1082. ImPlotTagCollection Tags;
  1083. // Flags
  1084. bool ChildWindowMade;
  1085. // Style and Colormaps
  1086. ImPlotStyle Style;
  1087. ImVector<ImGuiColorMod> ColorModifiers;
  1088. ImVector<ImGuiStyleMod> StyleModifiers;
  1089. ImPlotColormapData ColormapData;
  1090. ImVector<ImPlotColormap> ColormapModifiers;
  1091. // Time
  1092. tm Tm;
  1093. // Temp data for general use
  1094. ImVector<double> TempDouble1, TempDouble2;
  1095. ImVector<int> TempInt1;
  1096. // Misc
  1097. int DigitalPlotItemCnt;
  1098. int DigitalPlotOffset;
  1099. ImPlotNextPlotData NextPlotData;
  1100. ImPlotNextItemData NextItemData;
  1101. ImPlotInputMap InputMap;
  1102. bool OpenContextThisFrame;
  1103. ImGuiTextBuffer MousePosStringBuilder;
  1104. ImPlotItemGroup* SortItems;
  1105. // Align plots
  1106. ImPool<ImPlotAlignmentData> AlignmentData;
  1107. ImPlotAlignmentData* CurrentAlignmentH;
  1108. ImPlotAlignmentData* CurrentAlignmentV;
  1109. };
  1110. //-----------------------------------------------------------------------------
  1111. // [SECTION] Internal API
  1112. // No guarantee of forward compatibility here!
  1113. //-----------------------------------------------------------------------------
  1114. namespace ImPlot {
  1115. //-----------------------------------------------------------------------------
  1116. // [SECTION] Context Utils
  1117. //-----------------------------------------------------------------------------
  1118. // Initializes an ImPlotContext
  1119. IMPLOT_API void Initialize(ImPlotContext* ctx);
  1120. // Resets an ImPlot context for the next call to BeginPlot
  1121. IMPLOT_API void ResetCtxForNextPlot(ImPlotContext* ctx);
  1122. // Resets an ImPlot context for the next call to BeginAlignedPlots
  1123. IMPLOT_API void ResetCtxForNextAlignedPlots(ImPlotContext* ctx);
  1124. // Resets an ImPlot context for the next call to BeginSubplot
  1125. IMPLOT_API void ResetCtxForNextSubplot(ImPlotContext* ctx);
  1126. //-----------------------------------------------------------------------------
  1127. // [SECTION] Plot Utils
  1128. //-----------------------------------------------------------------------------
  1129. // Gets a plot from the current ImPlotContext
  1130. IMPLOT_API ImPlotPlot* GetPlot(const char* title);
  1131. // Gets the current plot from the current ImPlotContext
  1132. IMPLOT_API ImPlotPlot* GetCurrentPlot();
  1133. // Busts the cache for every plot in the current context
  1134. IMPLOT_API void BustPlotCache();
  1135. // Shows a plot's context menu.
  1136. IMPLOT_API void ShowPlotContextMenu(ImPlotPlot& plot);
  1137. //-----------------------------------------------------------------------------
  1138. // [SECTION] Setup Utils
  1139. //-----------------------------------------------------------------------------
  1140. // Lock Setup and call SetupFinish if necessary.
  1141. static inline void SetupLock() {
  1142. ImPlotContext& gp = *GImPlot;
  1143. if (!gp.CurrentPlot->SetupLocked)
  1144. SetupFinish();
  1145. gp.CurrentPlot->SetupLocked = true;
  1146. }
  1147. //-----------------------------------------------------------------------------
  1148. // [SECTION] Subplot Utils
  1149. //-----------------------------------------------------------------------------
  1150. // Advances to next subplot
  1151. IMPLOT_API void SubplotNextCell();
  1152. // Shows a subplot's context menu.
  1153. IMPLOT_API void ShowSubplotsContextMenu(ImPlotSubplot& subplot);
  1154. //-----------------------------------------------------------------------------
  1155. // [SECTION] Item Utils
  1156. //-----------------------------------------------------------------------------
  1157. // Begins a new item. Returns false if the item should not be plotted. Pushes PlotClipRect.
  1158. IMPLOT_API bool BeginItem(const char* label_id, ImPlotItemFlags flags=0, ImPlotCol recolor_from=IMPLOT_AUTO);
  1159. // Same as above but with fitting functionality.
  1160. template <typename _Fitter>
  1161. bool BeginItemEx(const char* label_id, const _Fitter& fitter, ImPlotItemFlags flags=0, ImPlotCol recolor_from=IMPLOT_AUTO) {
  1162. if (BeginItem(label_id, flags, recolor_from)) {
  1163. ImPlotPlot& plot = *GetCurrentPlot();
  1164. if (plot.FitThisFrame && !ImHasFlag(flags, ImPlotItemFlags_NoFit))
  1165. fitter.Fit(plot.Axes[plot.CurrentX], plot.Axes[plot.CurrentY]);
  1166. return true;
  1167. }
  1168. return false;
  1169. }
  1170. // Ends an item (call only if BeginItem returns true). Pops PlotClipRect.
  1171. IMPLOT_API void EndItem();
  1172. // Register or get an existing item from the current plot.
  1173. IMPLOT_API ImPlotItem* RegisterOrGetItem(const char* label_id, ImPlotItemFlags flags, bool* just_created = nullptr);
  1174. // Get a plot item from the current plot.
  1175. IMPLOT_API ImPlotItem* GetItem(const char* label_id);
  1176. // Gets the current item.
  1177. IMPLOT_API ImPlotItem* GetCurrentItem();
  1178. // Busts the cache for every item for every plot in the current context.
  1179. IMPLOT_API void BustItemCache();
  1180. //-----------------------------------------------------------------------------
  1181. // [SECTION] Axis Utils
  1182. //-----------------------------------------------------------------------------
  1183. // Returns true if any enabled axis is locked from user input.
  1184. static inline bool AnyAxesInputLocked(ImPlotAxis* axes, int count) {
  1185. for (int i = 0; i < count; ++i) {
  1186. if (axes[i].Enabled && axes[i].IsInputLocked())
  1187. return true;
  1188. }
  1189. return false;
  1190. }
  1191. // Returns true if all enabled axes are locked from user input.
  1192. static inline bool AllAxesInputLocked(ImPlotAxis* axes, int count) {
  1193. for (int i = 0; i < count; ++i) {
  1194. if (axes[i].Enabled && !axes[i].IsInputLocked())
  1195. return false;
  1196. }
  1197. return true;
  1198. }
  1199. static inline bool AnyAxesHeld(ImPlotAxis* axes, int count) {
  1200. for (int i = 0; i < count; ++i) {
  1201. if (axes[i].Enabled && axes[i].Held)
  1202. return true;
  1203. }
  1204. return false;
  1205. }
  1206. static inline bool AnyAxesHovered(ImPlotAxis* axes, int count) {
  1207. for (int i = 0; i < count; ++i) {
  1208. if (axes[i].Enabled && axes[i].Hovered)
  1209. return true;
  1210. }
  1211. return false;
  1212. }
  1213. // Returns true if the user has requested data to be fit.
  1214. static inline bool FitThisFrame() {
  1215. return GImPlot->CurrentPlot->FitThisFrame;
  1216. }
  1217. // Extends the current plot's axes so that it encompasses a vertical line at x
  1218. static inline void FitPointX(double x) {
  1219. ImPlotPlot& plot = *GetCurrentPlot();
  1220. ImPlotAxis& x_axis = plot.Axes[plot.CurrentX];
  1221. x_axis.ExtendFit(x);
  1222. }
  1223. // Extends the current plot's axes so that it encompasses a horizontal line at y
  1224. static inline void FitPointY(double y) {
  1225. ImPlotPlot& plot = *GetCurrentPlot();
  1226. ImPlotAxis& y_axis = plot.Axes[plot.CurrentY];
  1227. y_axis.ExtendFit(y);
  1228. }
  1229. // Extends the current plot's axes so that it encompasses point p
  1230. static inline void FitPoint(const ImPlotPoint& p) {
  1231. ImPlotPlot& plot = *GetCurrentPlot();
  1232. ImPlotAxis& x_axis = plot.Axes[plot.CurrentX];
  1233. ImPlotAxis& y_axis = plot.Axes[plot.CurrentY];
  1234. x_axis.ExtendFitWith(y_axis, p.x, p.y);
  1235. y_axis.ExtendFitWith(x_axis, p.y, p.x);
  1236. }
  1237. // Returns true if two ranges overlap
  1238. static inline bool RangesOverlap(const ImPlotRange& r1, const ImPlotRange& r2)
  1239. { return r1.Min <= r2.Max && r2.Min <= r1.Max; }
  1240. // Shows an axis's context menu.
  1241. IMPLOT_API void ShowAxisContextMenu(ImPlotAxis& axis, ImPlotAxis* equal_axis, bool time_allowed = false);
  1242. //-----------------------------------------------------------------------------
  1243. // [SECTION] Legend Utils
  1244. //-----------------------------------------------------------------------------
  1245. // Gets the position of an inner rect that is located inside of an outer rect according to an ImPlotLocation and padding amount.
  1246. IMPLOT_API ImVec2 GetLocationPos(const ImRect& outer_rect, const ImVec2& inner_size, ImPlotLocation location, const ImVec2& pad = ImVec2(0,0));
  1247. // Calculates the bounding box size of a legend
  1248. IMPLOT_API ImVec2 CalcLegendSize(ImPlotItemGroup& items, const ImVec2& pad, const ImVec2& spacing, bool vertical);
  1249. // Renders legend entries into a bounding box
  1250. IMPLOT_API bool ShowLegendEntries(ImPlotItemGroup& items, const ImRect& legend_bb, bool interactable, const ImVec2& pad, const ImVec2& spacing, bool vertical, ImDrawList& DrawList);
  1251. // Shows an alternate legend for the plot identified by #title_id, outside of the plot frame (can be called before or after of Begin/EndPlot but must occur in the same ImGui window!).
  1252. IMPLOT_API void ShowAltLegend(const char* title_id, bool vertical = true, const ImVec2 size = ImVec2(0,0), bool interactable = true);
  1253. // Shows an legends's context menu.
  1254. IMPLOT_API bool ShowLegendContextMenu(ImPlotLegend& legend, bool visible);
  1255. //-----------------------------------------------------------------------------
  1256. // [SECTION] Label Utils
  1257. //-----------------------------------------------------------------------------
  1258. // Create a a string label for a an axis value
  1259. IMPLOT_API void LabelAxisValue(const ImPlotAxis& axis, double value, char* buff, int size, bool round = false);
  1260. //-----------------------------------------------------------------------------
  1261. // [SECTION] Styling Utils
  1262. //-----------------------------------------------------------------------------
  1263. // Get styling data for next item (call between Begin/EndItem)
  1264. static inline const ImPlotNextItemData& GetItemData() { return GImPlot->NextItemData; }
  1265. // Returns true if a color is set to be automatically determined
  1266. static inline bool IsColorAuto(const ImVec4& col) { return col.w == -1; }
  1267. // Returns true if a style color is set to be automatically determined
  1268. static inline bool IsColorAuto(ImPlotCol idx) { return IsColorAuto(GImPlot->Style.Colors[idx]); }
  1269. // Returns the automatically deduced style color
  1270. IMPLOT_API ImVec4 GetAutoColor(ImPlotCol idx);
  1271. // Returns the style color whether it is automatic or custom set
  1272. static inline ImVec4 GetStyleColorVec4(ImPlotCol idx) { return IsColorAuto(idx) ? GetAutoColor(idx) : GImPlot->Style.Colors[idx]; }
  1273. static inline ImU32 GetStyleColorU32(ImPlotCol idx) { return ImGui::ColorConvertFloat4ToU32(GetStyleColorVec4(idx)); }
  1274. // Draws vertical text. The position is the bottom left of the text rect.
  1275. IMPLOT_API void AddTextVertical(ImDrawList *DrawList, ImVec2 pos, ImU32 col, const char* text_begin, const char* text_end = nullptr);
  1276. // Draws multiline horizontal text centered.
  1277. IMPLOT_API void AddTextCentered(ImDrawList* DrawList, ImVec2 top_center, ImU32 col, const char* text_begin, const char* text_end = nullptr);
  1278. // Calculates the size of vertical text
  1279. static inline ImVec2 CalcTextSizeVertical(const char *text) {
  1280. ImVec2 sz = ImGui::CalcTextSize(text);
  1281. return ImVec2(sz.y, sz.x);
  1282. }
  1283. // Returns white or black text given background color
  1284. static inline ImU32 CalcTextColor(const ImVec4& bg) { return (bg.x * 0.299f + bg.y * 0.587f + bg.z * 0.114f) > 0.5f ? IM_COL32_BLACK : IM_COL32_WHITE; }
  1285. static inline ImU32 CalcTextColor(ImU32 bg) { return CalcTextColor(ImGui::ColorConvertU32ToFloat4(bg)); }
  1286. // Lightens or darkens a color for hover
  1287. static inline ImU32 CalcHoverColor(ImU32 col) { return ImMixU32(col, CalcTextColor(col), 32); }
  1288. // Clamps a label position so that it fits a rect defined by Min/Max
  1289. static inline ImVec2 ClampLabelPos(ImVec2 pos, const ImVec2& size, const ImVec2& Min, const ImVec2& Max) {
  1290. if (pos.x < Min.x) pos.x = Min.x;
  1291. if (pos.y < Min.y) pos.y = Min.y;
  1292. if ((pos.x + size.x) > Max.x) pos.x = Max.x - size.x;
  1293. if ((pos.y + size.y) > Max.y) pos.y = Max.y - size.y;
  1294. return pos;
  1295. }
  1296. // Returns a color from the Color map given an index >= 0 (modulo will be performed).
  1297. IMPLOT_API ImU32 GetColormapColorU32(int idx, ImPlotColormap cmap);
  1298. // Returns the next unused colormap color and advances the colormap. Can be used to skip colors if desired.
  1299. IMPLOT_API ImU32 NextColormapColorU32();
  1300. // Linearly interpolates a color from the current colormap given t between 0 and 1.
  1301. IMPLOT_API ImU32 SampleColormapU32(float t, ImPlotColormap cmap);
  1302. // Render a colormap bar
  1303. IMPLOT_API void RenderColorBar(const ImU32* colors, int size, ImDrawList& DrawList, const ImRect& bounds, bool vert, bool reversed, bool continuous);
  1304. //-----------------------------------------------------------------------------
  1305. // [SECTION] Math and Misc Utils
  1306. //-----------------------------------------------------------------------------
  1307. // Rounds x to powers of 2,5 and 10 for generating axis labels (from Graphics Gems 1 Chapter 11.2)
  1308. IMPLOT_API double NiceNum(double x, bool round);
  1309. // Computes order of magnitude of double.
  1310. static inline int OrderOfMagnitude(double val) { return val == 0 ? 0 : (int)(floor(log10(fabs(val)))); }
  1311. // Returns the precision required for a order of magnitude.
  1312. static inline int OrderToPrecision(int order) { return order > 0 ? 0 : 1 - order; }
  1313. // Returns a floating point precision to use given a value
  1314. static inline int Precision(double val) { return OrderToPrecision(OrderOfMagnitude(val)); }
  1315. // Round a value to a given precision
  1316. static inline double RoundTo(double val, int prec) { double p = pow(10,(double)prec); return floor(val*p+0.5)/p; }
  1317. // Returns the intersection point of two lines A and B (assumes they are not parallel!)
  1318. static inline ImVec2 Intersection(const ImVec2& a1, const ImVec2& a2, const ImVec2& b1, const ImVec2& b2) {
  1319. float v1 = (a1.x * a2.y - a1.y * a2.x); float v2 = (b1.x * b2.y - b1.y * b2.x);
  1320. float v3 = ((a1.x - a2.x) * (b1.y - b2.y) - (a1.y - a2.y) * (b1.x - b2.x));
  1321. return ImVec2((v1 * (b1.x - b2.x) - v2 * (a1.x - a2.x)) / v3, (v1 * (b1.y - b2.y) - v2 * (a1.y - a2.y)) / v3);
  1322. }
  1323. // Fills a buffer with n samples linear interpolated from vmin to vmax
  1324. template <typename T>
  1325. void FillRange(ImVector<T>& buffer, int n, T vmin, T vmax) {
  1326. buffer.resize(n);
  1327. T step = (vmax - vmin) / (n - 1);
  1328. for (int i = 0; i < n; ++i) {
  1329. buffer[i] = vmin + i * step;
  1330. }
  1331. }
  1332. // Calculate histogram bin counts and widths
  1333. template <typename T>
  1334. static inline void CalculateBins(const T* values, int count, ImPlotBin meth, const ImPlotRange& range, int& bins_out, double& width_out) {
  1335. switch (meth) {
  1336. case ImPlotBin_Sqrt:
  1337. bins_out = (int)ceil(sqrt(count));
  1338. break;
  1339. case ImPlotBin_Sturges:
  1340. bins_out = (int)ceil(1.0 + log2(count));
  1341. break;
  1342. case ImPlotBin_Rice:
  1343. bins_out = (int)ceil(2 * cbrt(count));
  1344. break;
  1345. case ImPlotBin_Scott:
  1346. width_out = 3.49 * ImStdDev(values, count) / cbrt(count);
  1347. bins_out = (int)round(range.Size() / width_out);
  1348. break;
  1349. }
  1350. width_out = range.Size() / bins_out;
  1351. }
  1352. //-----------------------------------------------------------------------------
  1353. // Time Utils
  1354. //-----------------------------------------------------------------------------
  1355. // Returns true if year is leap year (366 days long)
  1356. static inline bool IsLeapYear(int year) {
  1357. return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
  1358. }
  1359. // Returns the number of days in a month, accounting for Feb. leap years. #month is zero indexed.
  1360. static inline int GetDaysInMonth(int year, int month) {
  1361. static const int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  1362. return days[month] + (int)(month == 1 && IsLeapYear(year));
  1363. }
  1364. // Make a UNIX timestamp from a tm struct expressed in UTC time (i.e. GMT timezone).
  1365. IMPLOT_API ImPlotTime MkGmtTime(struct tm *ptm);
  1366. // Make a tm struct expressed in UTC time (i.e. GMT timezone) from a UNIX timestamp.
  1367. IMPLOT_API tm* GetGmtTime(const ImPlotTime& t, tm* ptm);
  1368. // Make a UNIX timestamp from a tm struct expressed in local time.
  1369. IMPLOT_API ImPlotTime MkLocTime(struct tm *ptm);
  1370. // Make a tm struct expressed in local time from a UNIX timestamp.
  1371. IMPLOT_API tm* GetLocTime(const ImPlotTime& t, tm* ptm);
  1372. // NB: The following functions only work if there is a current ImPlotContext because the
  1373. // internal tm struct is owned by the context! They are aware of ImPlotStyle.UseLocalTime.
  1374. // Make a timestamp from time components.
  1375. // year[1970-3000], month[0-11], day[1-31], hour[0-23], min[0-59], sec[0-59], us[0,999999]
  1376. IMPLOT_API ImPlotTime MakeTime(int year, int month = 0, int day = 1, int hour = 0, int min = 0, int sec = 0, int us = 0);
  1377. // Get year component from timestamp [1970-3000]
  1378. IMPLOT_API int GetYear(const ImPlotTime& t);
  1379. // Adds or subtracts time from a timestamp. #count > 0 to add, < 0 to subtract.
  1380. IMPLOT_API ImPlotTime AddTime(const ImPlotTime& t, ImPlotTimeUnit unit, int count);
  1381. // Rounds a timestamp down to nearest unit.
  1382. IMPLOT_API ImPlotTime FloorTime(const ImPlotTime& t, ImPlotTimeUnit unit);
  1383. // Rounds a timestamp up to the nearest unit.
  1384. IMPLOT_API ImPlotTime CeilTime(const ImPlotTime& t, ImPlotTimeUnit unit);
  1385. // Rounds a timestamp up or down to the nearest unit.
  1386. IMPLOT_API ImPlotTime RoundTime(const ImPlotTime& t, ImPlotTimeUnit unit);
  1387. // Combines the date of one timestamp with the time-of-day of another timestamp.
  1388. IMPLOT_API ImPlotTime CombineDateTime(const ImPlotTime& date_part, const ImPlotTime& time_part);
  1389. // Formats the time part of timestamp t into a buffer according to #fmt
  1390. IMPLOT_API int FormatTime(const ImPlotTime& t, char* buffer, int size, ImPlotTimeFmt fmt, bool use_24_hr_clk);
  1391. // Formats the date part of timestamp t into a buffer according to #fmt
  1392. IMPLOT_API int FormatDate(const ImPlotTime& t, char* buffer, int size, ImPlotDateFmt fmt, bool use_iso_8601);
  1393. // Formats the time and/or date parts of a timestamp t into a buffer according to #fmt
  1394. IMPLOT_API int FormatDateTime(const ImPlotTime& t, char* buffer, int size, ImPlotDateTimeSpec fmt);
  1395. // Shows a date picker widget block (year/month/day).
  1396. // #level = 0 for day, 1 for month, 2 for year. Modified by user interaction.
  1397. // #t will be set when a day is clicked and the function will return true.
  1398. // #t1 and #t2 are optional dates to highlight.
  1399. IMPLOT_API bool ShowDatePicker(const char* id, int* level, ImPlotTime* t, const ImPlotTime* t1 = nullptr, const ImPlotTime* t2 = nullptr);
  1400. // Shows a time picker widget block (hour/min/sec).
  1401. // #t will be set when a new hour, minute, or sec is selected or am/pm is toggled, and the function will return true.
  1402. IMPLOT_API bool ShowTimePicker(const char* id, ImPlotTime* t);
  1403. //-----------------------------------------------------------------------------
  1404. // [SECTION] Transforms
  1405. //-----------------------------------------------------------------------------
  1406. static inline double TransformForward_Log10(double v, void*) {
  1407. v = v <= 0.0 ? DBL_MIN : v;
  1408. return ImLog10(v);
  1409. }
  1410. static inline double TransformInverse_Log10(double v, void*) {
  1411. return ImPow(10, v);
  1412. }
  1413. static inline double TransformForward_SymLog(double v, void*) {
  1414. return 2.0 * ImAsinh(v / 2.0);
  1415. }
  1416. static inline double TransformInverse_SymLog(double v, void*) {
  1417. return 2.0 * ImSinh(v / 2.0);
  1418. }
  1419. static inline double TransformForward_Logit(double v, void*) {
  1420. v = ImClamp(v, DBL_MIN, 1.0 - DBL_EPSILON);
  1421. return ImLog10(v / (1 - v));
  1422. }
  1423. static inline double TransformInverse_Logit(double v, void*) {
  1424. return 1.0 / (1.0 + ImPow(10,-v));
  1425. }
  1426. //-----------------------------------------------------------------------------
  1427. // [SECTION] Formatters
  1428. //-----------------------------------------------------------------------------
  1429. static inline int Formatter_Default(double value, char* buff, int size, void* data) {
  1430. char* fmt = (char*)data;
  1431. return ImFormatString(buff, size, fmt, value);
  1432. }
  1433. static inline int Formatter_Logit(double value, char* buff, int size, void*) {
  1434. if (value == 0.5)
  1435. return ImFormatString(buff,size,"1/2");
  1436. else if (value < 0.5)
  1437. return ImFormatString(buff,size,"%g", value);
  1438. else
  1439. return ImFormatString(buff,size,"1 - %g", 1 - value);
  1440. }
  1441. struct Formatter_Time_Data {
  1442. ImPlotTime Time;
  1443. ImPlotDateTimeSpec Spec;
  1444. ImPlotFormatter UserFormatter;
  1445. void* UserFormatterData;
  1446. };
  1447. static inline int Formatter_Time(double, char* buff, int size, void* data) {
  1448. Formatter_Time_Data* ftd = (Formatter_Time_Data*)data;
  1449. return FormatDateTime(ftd->Time, buff, size, ftd->Spec);
  1450. }
  1451. //------------------------------------------------------------------------------
  1452. // [SECTION] Locator
  1453. //------------------------------------------------------------------------------
  1454. void Locator_Default(ImPlotTicker& ticker, const ImPlotRange& range, float pixels, bool vertical, ImPlotFormatter formatter, void* formatter_data);
  1455. void Locator_Time(ImPlotTicker& ticker, const ImPlotRange& range, float pixels, bool vertical, ImPlotFormatter formatter, void* formatter_data);
  1456. void Locator_Log10(ImPlotTicker& ticker, const ImPlotRange& range, float pixels, bool vertical, ImPlotFormatter formatter, void* formatter_data);
  1457. void Locator_SymLog(ImPlotTicker& ticker, const ImPlotRange& range, float pixels, bool vertical, ImPlotFormatter formatter, void* formatter_data);
  1458. } // namespace ImPlot