implot.cpp 260 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761
  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. /*
  20. API BREAKING CHANGES
  21. ====================
  22. Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
  23. Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
  24. When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all implot files.
  25. You can read releases logs https://github.com/epezent/implot/releases for more details.
  26. - 2023/06/26 (0.15) - Various build fixes related to updates in Dear ImGui internals.
  27. - 2022/11/25 (0.15) - Make PlotText honor ImPlotItemFlags_NoFit.
  28. - 2022/06/19 (0.14) - The signature of ColormapScale has changed to accommodate a new ImPlotColormapScaleFlags parameter
  29. - 2022/06/17 (0.14) - **IMPORTANT** All PlotX functions now take an ImPlotX_Flags `flags` parameter. Where applicable, it is located before the existing `offset` and `stride` parameters.
  30. If you were providing offset and stride values, you will need to update your function call to include a `flags` value. If you fail to do this, you will likely see
  31. unexpected results or crashes without a compiler warning since these three are all default args. We apologize for the inconvenience, but this was a necessary evil.
  32. - PlotBarsH has been removed; use PlotBars + ImPlotBarsFlags_Horizontal instead
  33. - PlotErrorBarsH has been removed; use PlotErrorBars + ImPlotErrorBarsFlags_Horizontal
  34. - PlotHistogram/PlotHistogram2D signatures changed; `cumulative`, `density`, and `outliers` options now specified via ImPlotHistogramFlags
  35. - PlotPieChart signature changed; `normalize` option now specified via ImPlotPieChartFlags
  36. - PlotText signature changes; `vertical` option now specified via `ImPlotTextFlags_Vertical`
  37. - `PlotVLines` and `PlotHLines` replaced with `PlotInfLines` (+ ImPlotInfLinesFlags_Horizontal )
  38. - arguments of ImPlotGetter have been reversed to be consistent with other API callbacks
  39. - SetupAxisScale + ImPlotScale have replaced ImPlotAxisFlags_LogScale and ImPlotAxisFlags_Time flags
  40. - ImPlotFormatters should now return an int indicating the size written
  41. - the signature of ImPlotGetter has been reversed so that void* user_data is the last argument and consistent with other callbacks
  42. - 2021/10/19 (0.13) - MAJOR API OVERHAUL! See #168 and #272
  43. - TRIVIAL RENAME:
  44. - ImPlotLimits -> ImPlotRect
  45. - ImPlotYAxis_ -> ImAxis_
  46. - SetPlotYAxis -> SetAxis
  47. - BeginDragDropTarget -> BeginDragDropTargetPlot
  48. - BeginDragDropSource -> BeginDragDropSourcePlot
  49. - ImPlotFlags_NoMousePos -> ImPlotFlags_NoMouseText
  50. - SetNextPlotLimits -> SetNextAxesLimits
  51. - SetMouseTextLocation -> SetupMouseText
  52. - SIGNATURE MODIFIED:
  53. - PixelsToPlot/PlotToPixels -> added optional X-Axis arg
  54. - GetPlotMousePos -> added optional X-Axis arg
  55. - GetPlotLimits -> added optional X-Axis arg
  56. - GetPlotSelection -> added optional X-Axis arg
  57. - DragLineX/Y/DragPoint -> now takes int id; removed labels (render with Annotation/Tag instead)
  58. - REPLACED:
  59. - IsPlotXAxisHovered/IsPlotXYAxisHovered -> IsAxisHovered(ImAxis)
  60. - BeginDragDropTargetX/BeginDragDropTargetY -> BeginDragDropTargetAxis(ImAxis)
  61. - BeginDragDropSourceX/BeginDragDropSourceY -> BeginDragDropSourceAxis(ImAxis)
  62. - ImPlotCol_XAxis, ImPlotCol_YAxis1, etc. -> ImPlotCol_AxisText (push/pop this around SetupAxis to style individual axes)
  63. - ImPlotCol_XAxisGrid, ImPlotCol_Y1AxisGrid -> ImPlotCol_AxisGrid (push/pop this around SetupAxis to style individual axes)
  64. - SetNextPlotLimitsX/Y -> SetNextAxisLimits(ImAxis)
  65. - LinkNextPlotLimits -> SetNextAxisLinks(ImAxis)
  66. - FitNextPlotAxes -> SetNextAxisToFit(ImAxis)/SetNextAxesToFit
  67. - SetLegendLocation -> SetupLegend
  68. - ImPlotFlags_NoHighlight -> ImPlotLegendFlags_NoHighlight
  69. - ImPlotOrientation -> ImPlotLegendFlags_Horizontal
  70. - Annotate -> Annotation
  71. - REMOVED:
  72. - GetPlotQuery, SetPlotQuery, IsPlotQueried -> use DragRect
  73. - SetNextPlotTicksX, SetNextPlotTicksY -> use SetupAxisTicks
  74. - SetNextPlotFormatX, SetNextPlotFormatY -> use SetupAxisFormat
  75. - AnnotateClamped -> use Annotation(bool clamp = true)
  76. - OBSOLETED:
  77. - BeginPlot (original signature) -> use simplified signature + Setup API
  78. - 2021/07/30 (0.12) - The offset argument of `PlotXG` functions was been removed. Implement offsetting in your getter callback instead.
  79. - 2021/03/08 (0.9) - SetColormap and PushColormap(ImVec4*) were removed. Use AddColormap for custom colormap support. LerpColormap was changed to SampleColormap.
  80. ShowColormapScale was changed to ColormapScale and requires additional arguments.
  81. - 2021/03/07 (0.9) - The signature of ShowColormapScale was modified to accept a ImVec2 size.
  82. - 2021/02/28 (0.9) - BeginLegendDragDropSource was changed to BeginDragDropSourceItem with a number of other drag and drop improvements.
  83. - 2021/01/18 (0.9) - The default behavior for opening context menus was change from double right-click to single right-click. ImPlotInputMap and related functions were moved
  84. to implot_internal.h due to its immaturity.
  85. - 2020/10/16 (0.8) - ImPlotStyleVar_InfoPadding was changed to ImPlotStyleVar_MousePosPadding
  86. - 2020/09/10 (0.8) - The single array versions of PlotLine, PlotScatter, PlotStems, and PlotShaded were given additional arguments for x-scale and x0.
  87. - 2020/09/07 (0.8) - Plotting functions which accept a custom getter function pointer have been post-fixed with a G (e.g. PlotLineG)
  88. - 2020/09/06 (0.7) - Several flags under ImPlotFlags and ImPlotAxisFlags were inverted (e.g. ImPlotFlags_Legend -> ImPlotFlags_NoLegend) so that the default flagset
  89. is simply 0. This more closely matches ImGui's style and makes it easier to enable non-default but commonly used flags (e.g. ImPlotAxisFlags_Time).
  90. - 2020/08/28 (0.5) - ImPlotMarker_ can no longer be combined with bitwise OR, |. This features caused unecessary slow-down, and almost no one used it.
  91. - 2020/08/25 (0.5) - ImPlotAxisFlags_Scientific was removed. Logarithmic axes automatically uses scientific notation.
  92. - 2020/08/17 (0.5) - PlotText was changed so that text is centered horizontally and vertically about the desired point.
  93. - 2020/08/16 (0.5) - An ImPlotContext must be explicitly created and destroyed now with `CreateContext` and `DestroyContext`. Previously, the context was statically initialized in this source file.
  94. - 2020/06/13 (0.4) - The flags `ImPlotAxisFlag_Adaptive` and `ImPlotFlags_Cull` were removed. Both are now done internally by default.
  95. - 2020/06/03 (0.3) - The signature and behavior of PlotPieChart was changed so that data with sum less than 1 can optionally be normalized. The label format can now be specified as well.
  96. - 2020/06/01 (0.3) - SetPalette was changed to `SetColormap` for consistency with other plotting libraries. `RestorePalette` was removed. Use `SetColormap(ImPlotColormap_Default)`.
  97. - 2020/05/31 (0.3) - Plot functions taking custom ImVec2* getters were removed. Use the ImPlotPoint* getter versions instead.
  98. - 2020/05/29 (0.3) - The signature of ImPlotLimits::Contains was changed to take two doubles instead of ImVec2
  99. - 2020/05/16 (0.2) - All plotting functions were reverted to being prefixed with "Plot" to maintain a consistent VerbNoun style. `Plot` was split into `PlotLine`
  100. and `PlotScatter` (however, `PlotLine` can still be used to plot scatter points as `Plot` did before.). `Bar` is not `PlotBars`, to indicate
  101. that multiple bars will be plotted.
  102. - 2020/05/13 (0.2) - `ImMarker` was change to `ImPlotMarker` and `ImAxisFlags` was changed to `ImPlotAxisFlags`.
  103. - 2020/05/11 (0.2) - `ImPlotFlags_Selection` was changed to `ImPlotFlags_BoxSelect`
  104. - 2020/05/11 (0.2) - The namespace ImGui:: was replaced with ImPlot::. As a result, the following additional changes were made:
  105. - Functions that were prefixed or decorated with the word "Plot" have been truncated. E.g., `ImGui::PlotBars` is now just `ImPlot::Bar`.
  106. It should be fairly obvious what was what.
  107. - Some functions have been given names that would have otherwise collided with the ImGui namespace. This has been done to maintain a consistent
  108. style with ImGui. E.g., 'ImGui::PushPlotStyleVar` is now 'ImPlot::PushStyleVar'.
  109. - 2020/05/10 (0.2) - The following function/struct names were changes:
  110. - ImPlotRange -> ImPlotLimits
  111. - GetPlotRange() -> GetPlotLimits()
  112. - SetNextPlotRange -> SetNextPlotLimits
  113. - SetNextPlotRangeX -> SetNextPlotLimitsX
  114. - SetNextPlotRangeY -> SetNextPlotLimitsY
  115. - 2020/05/10 (0.2) - Plot queries are pixel based by default. Query rects that maintain relative plot position have been removed. This was done to support multi-y-axis.
  116. */
  117. #define IMGUI_DEFINE_MATH_OPERATORS
  118. #include "implot.h"
  119. #include "implot_internal.h"
  120. #include <stdlib.h>
  121. // Support for pre-1.82 versions. Users on 1.82+ can use 0 (default) flags to mean "all corners" but in order to support older versions we are more explicit.
  122. #if (IMGUI_VERSION_NUM < 18102) && !defined(ImDrawFlags_RoundCornersAll)
  123. #define ImDrawFlags_RoundCornersAll ImDrawCornerFlags_All
  124. #endif
  125. // Support for pre-1.89.7 versions.
  126. #if (IMGUI_VERSION_NUM < 18966)
  127. #define ImGuiButtonFlags_AllowOverlap ImGuiButtonFlags_AllowItemOverlap
  128. #endif
  129. // Visual Studio warnings
  130. #ifdef _MSC_VER
  131. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  132. #endif
  133. // Clang/GCC warnings with -Weverything
  134. #if defined(__clang__)
  135. #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal
  136. #elif defined(__GNUC__)
  137. #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
  138. #endif
  139. // Global plot context
  140. #ifndef GImPlot
  141. ImPlotContext* GImPlot = nullptr;
  142. #endif
  143. //-----------------------------------------------------------------------------
  144. // Struct Implementations
  145. //-----------------------------------------------------------------------------
  146. ImPlotInputMap::ImPlotInputMap() {
  147. ImPlot::MapInputDefault(this);
  148. }
  149. ImPlotStyle::ImPlotStyle() {
  150. LineWeight = 1;
  151. Marker = ImPlotMarker_None;
  152. MarkerSize = 4;
  153. MarkerWeight = 1;
  154. FillAlpha = 1;
  155. ErrorBarSize = 5;
  156. ErrorBarWeight = 1.5f;
  157. DigitalBitHeight = 8;
  158. DigitalBitGap = 4;
  159. PlotBorderSize = 1;
  160. MinorAlpha = 0.25f;
  161. MajorTickLen = ImVec2(10,10);
  162. MinorTickLen = ImVec2(5,5);
  163. MajorTickSize = ImVec2(1,1);
  164. MinorTickSize = ImVec2(1,1);
  165. MajorGridSize = ImVec2(1,1);
  166. MinorGridSize = ImVec2(1,1);
  167. PlotPadding = ImVec2(10,10);
  168. LabelPadding = ImVec2(5,5);
  169. LegendPadding = ImVec2(10,10);
  170. LegendInnerPadding = ImVec2(5,5);
  171. LegendSpacing = ImVec2(5,0);
  172. MousePosPadding = ImVec2(10,10);
  173. AnnotationPadding = ImVec2(2,2);
  174. FitPadding = ImVec2(0,0);
  175. PlotDefaultSize = ImVec2(400,300);
  176. PlotMinSize = ImVec2(200,150);
  177. ImPlot::StyleColorsAuto(this);
  178. Colormap = ImPlotColormap_Deep;
  179. UseLocalTime = false;
  180. Use24HourClock = false;
  181. UseISO8601 = false;
  182. }
  183. //-----------------------------------------------------------------------------
  184. // Style
  185. //-----------------------------------------------------------------------------
  186. namespace ImPlot {
  187. const char* GetStyleColorName(ImPlotCol col) {
  188. static const char* col_names[ImPlotCol_COUNT] = {
  189. "Line",
  190. "Fill",
  191. "MarkerOutline",
  192. "MarkerFill",
  193. "ErrorBar",
  194. "FrameBg",
  195. "PlotBg",
  196. "PlotBorder",
  197. "LegendBg",
  198. "LegendBorder",
  199. "LegendText",
  200. "TitleText",
  201. "InlayText",
  202. "AxisText",
  203. "AxisGrid",
  204. "AxisTick",
  205. "AxisBg",
  206. "AxisBgHovered",
  207. "AxisBgActive",
  208. "Selection",
  209. "Crosshairs"
  210. };
  211. return col_names[col];
  212. }
  213. const char* GetMarkerName(ImPlotMarker marker) {
  214. switch (marker) {
  215. case ImPlotMarker_None: return "None";
  216. case ImPlotMarker_Circle: return "Circle";
  217. case ImPlotMarker_Square: return "Square";
  218. case ImPlotMarker_Diamond: return "Diamond";
  219. case ImPlotMarker_Up: return "Up";
  220. case ImPlotMarker_Down: return "Down";
  221. case ImPlotMarker_Left: return "Left";
  222. case ImPlotMarker_Right: return "Right";
  223. case ImPlotMarker_Cross: return "Cross";
  224. case ImPlotMarker_Plus: return "Plus";
  225. case ImPlotMarker_Asterisk: return "Asterisk";
  226. default: return "";
  227. }
  228. }
  229. ImVec4 GetAutoColor(ImPlotCol idx) {
  230. ImVec4 col(0,0,0,1);
  231. switch(idx) {
  232. case ImPlotCol_Line: return col; // these are plot dependent!
  233. case ImPlotCol_Fill: return col; // these are plot dependent!
  234. case ImPlotCol_MarkerOutline: return col; // these are plot dependent!
  235. case ImPlotCol_MarkerFill: return col; // these are plot dependent!
  236. case ImPlotCol_ErrorBar: return ImGui::GetStyleColorVec4(ImGuiCol_Text);
  237. case ImPlotCol_FrameBg: return ImGui::GetStyleColorVec4(ImGuiCol_FrameBg);
  238. case ImPlotCol_PlotBg: return ImGui::GetStyleColorVec4(ImGuiCol_WindowBg);
  239. case ImPlotCol_PlotBorder: return ImGui::GetStyleColorVec4(ImGuiCol_Border);
  240. case ImPlotCol_LegendBg: return ImGui::GetStyleColorVec4(ImGuiCol_PopupBg);
  241. case ImPlotCol_LegendBorder: return GetStyleColorVec4(ImPlotCol_PlotBorder);
  242. case ImPlotCol_LegendText: return GetStyleColorVec4(ImPlotCol_InlayText);
  243. case ImPlotCol_TitleText: return ImGui::GetStyleColorVec4(ImGuiCol_Text);
  244. case ImPlotCol_InlayText: return ImGui::GetStyleColorVec4(ImGuiCol_Text);
  245. case ImPlotCol_AxisText: return ImGui::GetStyleColorVec4(ImGuiCol_Text);
  246. case ImPlotCol_AxisGrid: return GetStyleColorVec4(ImPlotCol_AxisText) * ImVec4(1,1,1,0.25f);
  247. case ImPlotCol_AxisTick: return GetStyleColorVec4(ImPlotCol_AxisGrid);
  248. case ImPlotCol_AxisBg: return ImVec4(0,0,0,0);
  249. case ImPlotCol_AxisBgHovered: return ImGui::GetStyleColorVec4(ImGuiCol_ButtonHovered);
  250. case ImPlotCol_AxisBgActive: return ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive);
  251. case ImPlotCol_Selection: return ImVec4(1,1,0,1);
  252. case ImPlotCol_Crosshairs: return GetStyleColorVec4(ImPlotCol_PlotBorder);
  253. default: return col;
  254. }
  255. }
  256. struct ImPlotStyleVarInfo {
  257. ImGuiDataType Type;
  258. ImU32 Count;
  259. ImU32 Offset;
  260. void* GetVarPtr(ImPlotStyle* style) const { return (void*)((unsigned char*)style + Offset); }
  261. };
  262. static const ImPlotStyleVarInfo GPlotStyleVarInfo[] =
  263. {
  264. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, LineWeight) }, // ImPlotStyleVar_LineWeight
  265. { ImGuiDataType_S32, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, Marker) }, // ImPlotStyleVar_Marker
  266. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, MarkerSize) }, // ImPlotStyleVar_MarkerSize
  267. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, MarkerWeight) }, // ImPlotStyleVar_MarkerWeight
  268. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, FillAlpha) }, // ImPlotStyleVar_FillAlpha
  269. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, ErrorBarSize) }, // ImPlotStyleVar_ErrorBarSize
  270. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, ErrorBarWeight) }, // ImPlotStyleVar_ErrorBarWeight
  271. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, DigitalBitHeight) }, // ImPlotStyleVar_DigitalBitHeight
  272. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, DigitalBitGap) }, // ImPlotStyleVar_DigitalBitGap
  273. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, PlotBorderSize) }, // ImPlotStyleVar_PlotBorderSize
  274. { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorAlpha) }, // ImPlotStyleVar_MinorAlpha
  275. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MajorTickLen) }, // ImPlotStyleVar_MajorTickLen
  276. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorTickLen) }, // ImPlotStyleVar_MinorTickLen
  277. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MajorTickSize) }, // ImPlotStyleVar_MajorTickSize
  278. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorTickSize) }, // ImPlotStyleVar_MinorTickSize
  279. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MajorGridSize) }, // ImPlotStyleVar_MajorGridSize
  280. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorGridSize) }, // ImPlotStyleVar_MinorGridSize
  281. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, PlotPadding) }, // ImPlotStyleVar_PlotPadding
  282. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, LabelPadding) }, // ImPlotStyleVar_LabelPaddine
  283. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, LegendPadding) }, // ImPlotStyleVar_LegendPadding
  284. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, LegendInnerPadding) }, // ImPlotStyleVar_LegendInnerPadding
  285. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, LegendSpacing) }, // ImPlotStyleVar_LegendSpacing
  286. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MousePosPadding) }, // ImPlotStyleVar_MousePosPadding
  287. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, AnnotationPadding) }, // ImPlotStyleVar_AnnotationPadding
  288. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, FitPadding) }, // ImPlotStyleVar_FitPadding
  289. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, PlotDefaultSize) }, // ImPlotStyleVar_PlotDefaultSize
  290. { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, PlotMinSize) } // ImPlotStyleVar_PlotMinSize
  291. };
  292. static const ImPlotStyleVarInfo* GetPlotStyleVarInfo(ImPlotStyleVar idx) {
  293. IM_ASSERT(idx >= 0 && idx < ImPlotStyleVar_COUNT);
  294. IM_ASSERT(IM_ARRAYSIZE(GPlotStyleVarInfo) == ImPlotStyleVar_COUNT);
  295. return &GPlotStyleVarInfo[idx];
  296. }
  297. //-----------------------------------------------------------------------------
  298. // Generic Helpers
  299. //-----------------------------------------------------------------------------
  300. void AddTextVertical(ImDrawList *DrawList, ImVec2 pos, ImU32 col, const char *text_begin, const char* text_end) {
  301. // the code below is based loosely on ImFont::RenderText
  302. if (!text_end)
  303. text_end = text_begin + strlen(text_begin);
  304. ImGuiContext& g = *GImGui;
  305. ImFont* font = g.Font;
  306. // Align to be pixel perfect
  307. pos.x = IM_FLOOR(pos.x);
  308. pos.y = IM_FLOOR(pos.y);
  309. const float scale = g.FontSize / font->FontSize;
  310. const char* s = text_begin;
  311. int chars_exp = (int)(text_end - s);
  312. int chars_rnd = 0;
  313. const int vtx_count_max = chars_exp * 4;
  314. const int idx_count_max = chars_exp * 6;
  315. DrawList->PrimReserve(idx_count_max, vtx_count_max);
  316. while (s < text_end) {
  317. unsigned int c = (unsigned int)*s;
  318. if (c < 0x80) {
  319. s += 1;
  320. }
  321. else {
  322. s += ImTextCharFromUtf8(&c, s, text_end);
  323. if (c == 0) // Malformed UTF-8?
  324. break;
  325. }
  326. const ImFontGlyph * glyph = font->FindGlyph((ImWchar)c);
  327. if (glyph == nullptr) {
  328. continue;
  329. }
  330. DrawList->PrimQuadUV(pos + ImVec2(glyph->Y0, -glyph->X0) * scale, pos + ImVec2(glyph->Y0, -glyph->X1) * scale,
  331. pos + ImVec2(glyph->Y1, -glyph->X1) * scale, pos + ImVec2(glyph->Y1, -glyph->X0) * scale,
  332. ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V0),
  333. ImVec2(glyph->U1, glyph->V1), ImVec2(glyph->U0, glyph->V1),
  334. col);
  335. pos.y -= glyph->AdvanceX * scale;
  336. chars_rnd++;
  337. }
  338. // Give back unused vertices
  339. int chars_skp = chars_exp-chars_rnd;
  340. DrawList->PrimUnreserve(chars_skp*6, chars_skp*4);
  341. }
  342. void AddTextCentered(ImDrawList* DrawList, ImVec2 top_center, ImU32 col, const char* text_begin, const char* text_end) {
  343. float txt_ht = ImGui::GetTextLineHeight();
  344. const char* title_end = ImGui::FindRenderedTextEnd(text_begin, text_end);
  345. ImVec2 text_size;
  346. float y = 0;
  347. while (const char* tmp = (const char*)memchr(text_begin, '\n', title_end-text_begin)) {
  348. text_size = ImGui::CalcTextSize(text_begin,tmp,true);
  349. DrawList->AddText(ImVec2(top_center.x - text_size.x * 0.5f, top_center.y+y),col,text_begin,tmp);
  350. text_begin = tmp + 1;
  351. y += txt_ht;
  352. }
  353. text_size = ImGui::CalcTextSize(text_begin,title_end,true);
  354. DrawList->AddText(ImVec2(top_center.x - text_size.x * 0.5f, top_center.y+y),col,text_begin,title_end);
  355. }
  356. double NiceNum(double x, bool round) {
  357. double f;
  358. double nf;
  359. int expv = (int)floor(ImLog10(x));
  360. f = x / ImPow(10.0, (double)expv);
  361. if (round)
  362. if (f < 1.5)
  363. nf = 1;
  364. else if (f < 3)
  365. nf = 2;
  366. else if (f < 7)
  367. nf = 5;
  368. else
  369. nf = 10;
  370. else if (f <= 1)
  371. nf = 1;
  372. else if (f <= 2)
  373. nf = 2;
  374. else if (f <= 5)
  375. nf = 5;
  376. else
  377. nf = 10;
  378. return nf * ImPow(10.0, expv);
  379. }
  380. //-----------------------------------------------------------------------------
  381. // Context Utils
  382. //-----------------------------------------------------------------------------
  383. void SetImGuiContext(ImGuiContext* ctx) {
  384. ImGui::SetCurrentContext(ctx);
  385. }
  386. ImPlotContext* CreateContext() {
  387. ImPlotContext* ctx = IM_NEW(ImPlotContext)();
  388. Initialize(ctx);
  389. if (GImPlot == nullptr)
  390. SetCurrentContext(ctx);
  391. return ctx;
  392. }
  393. void DestroyContext(ImPlotContext* ctx) {
  394. if (ctx == nullptr)
  395. ctx = GImPlot;
  396. if (GImPlot == ctx)
  397. SetCurrentContext(nullptr);
  398. IM_DELETE(ctx);
  399. }
  400. ImPlotContext* GetCurrentContext() {
  401. return GImPlot;
  402. }
  403. void SetCurrentContext(ImPlotContext* ctx) {
  404. GImPlot = ctx;
  405. }
  406. #define IMPLOT_APPEND_CMAP(name, qual) ctx->ColormapData.Append(#name, name, sizeof(name)/sizeof(ImU32), qual)
  407. #define IM_RGB(r,g,b) IM_COL32(r,g,b,255)
  408. void Initialize(ImPlotContext* ctx) {
  409. ResetCtxForNextPlot(ctx);
  410. ResetCtxForNextAlignedPlots(ctx);
  411. ResetCtxForNextSubplot(ctx);
  412. const ImU32 Deep[] = {4289753676, 4283598045, 4285048917, 4283584196, 4289950337, 4284512403, 4291005402, 4287401100, 4285839820, 4291671396 };
  413. const ImU32 Dark[] = {4280031972, 4290281015, 4283084621, 4288892568, 4278222847, 4281597951, 4280833702, 4290740727, 4288256409 };
  414. const ImU32 Pastel[] = {4289639675, 4293119411, 4291161036, 4293184478, 4289124862, 4291624959, 4290631909, 4293712637, 4294111986 };
  415. const ImU32 Paired[] = {4293119554, 4290017311, 4287291314, 4281114675, 4288256763, 4280031971, 4285513725, 4278222847, 4292260554, 4288298346, 4288282623, 4280834481};
  416. const ImU32 Viridis[] = {4283695428, 4285867080, 4287054913, 4287455029, 4287526954, 4287402273, 4286883874, 4285579076, 4283552122, 4280737725, 4280674301 };
  417. const ImU32 Plasma[] = {4287039501, 4288480321, 4289200234, 4288941455, 4287638193, 4286072780, 4284638433, 4283139314, 4281771772, 4280667900, 4280416752 };
  418. const ImU32 Hot[] = {4278190144, 4278190208, 4278190271, 4278190335, 4278206719, 4278223103, 4278239231, 4278255615, 4283826175, 4289396735, 4294967295 };
  419. const ImU32 Cool[] = {4294967040, 4294960666, 4294954035, 4294947661, 4294941030, 4294934656, 4294928025, 4294921651, 4294915020, 4294908646, 4294902015 };
  420. const ImU32 Pink[] = {4278190154, 4282532475, 4284308894, 4285690554, 4286879686, 4287870160, 4288794330, 4289651940, 4291685869, 4293392118, 4294967295 };
  421. const ImU32 Jet[] = {4289331200, 4294901760, 4294923520, 4294945280, 4294967040, 4289396565, 4283826090, 4278255615, 4278233855, 4278212095, 4278190335 };
  422. 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)};
  423. 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)};
  424. 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)};
  425. 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)};
  426. 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)};
  427. const ImU32 Greys[] = {IM_COL32_WHITE, IM_COL32_BLACK };
  428. IMPLOT_APPEND_CMAP(Deep, true);
  429. IMPLOT_APPEND_CMAP(Dark, true);
  430. IMPLOT_APPEND_CMAP(Pastel, true);
  431. IMPLOT_APPEND_CMAP(Paired, true);
  432. IMPLOT_APPEND_CMAP(Viridis, false);
  433. IMPLOT_APPEND_CMAP(Plasma, false);
  434. IMPLOT_APPEND_CMAP(Hot, false);
  435. IMPLOT_APPEND_CMAP(Cool, false);
  436. IMPLOT_APPEND_CMAP(Pink, false);
  437. IMPLOT_APPEND_CMAP(Jet, false);
  438. IMPLOT_APPEND_CMAP(Twilight, false);
  439. IMPLOT_APPEND_CMAP(RdBu, false);
  440. IMPLOT_APPEND_CMAP(BrBG, false);
  441. IMPLOT_APPEND_CMAP(PiYG, false);
  442. IMPLOT_APPEND_CMAP(Spectral, false);
  443. IMPLOT_APPEND_CMAP(Greys, false);
  444. }
  445. void ResetCtxForNextPlot(ImPlotContext* ctx) {
  446. // end child window if it was made
  447. if (ctx->ChildWindowMade)
  448. ImGui::EndChild();
  449. ctx->ChildWindowMade = false;
  450. // reset the next plot/item data
  451. ctx->NextPlotData.Reset();
  452. ctx->NextItemData.Reset();
  453. // reset labels
  454. ctx->Annotations.Reset();
  455. ctx->Tags.Reset();
  456. // reset extents/fit
  457. ctx->OpenContextThisFrame = false;
  458. // reset digital plot items count
  459. ctx->DigitalPlotItemCnt = 0;
  460. ctx->DigitalPlotOffset = 0;
  461. // nullify plot
  462. ctx->CurrentPlot = nullptr;
  463. ctx->CurrentItem = nullptr;
  464. ctx->PreviousItem = nullptr;
  465. }
  466. void ResetCtxForNextAlignedPlots(ImPlotContext* ctx) {
  467. ctx->CurrentAlignmentH = nullptr;
  468. ctx->CurrentAlignmentV = nullptr;
  469. }
  470. void ResetCtxForNextSubplot(ImPlotContext* ctx) {
  471. ctx->CurrentSubplot = nullptr;
  472. ctx->CurrentAlignmentH = nullptr;
  473. ctx->CurrentAlignmentV = nullptr;
  474. }
  475. //-----------------------------------------------------------------------------
  476. // Plot Utils
  477. //-----------------------------------------------------------------------------
  478. ImPlotPlot* GetPlot(const char* title) {
  479. ImGuiWindow* Window = GImGui->CurrentWindow;
  480. const ImGuiID ID = Window->GetID(title);
  481. return GImPlot->Plots.GetByKey(ID);
  482. }
  483. ImPlotPlot* GetCurrentPlot() {
  484. return GImPlot->CurrentPlot;
  485. }
  486. void BustPlotCache() {
  487. ImPlotContext& gp = *GImPlot;
  488. gp.Plots.Clear();
  489. gp.Subplots.Clear();
  490. }
  491. //-----------------------------------------------------------------------------
  492. // Legend Utils
  493. //-----------------------------------------------------------------------------
  494. ImVec2 GetLocationPos(const ImRect& outer_rect, const ImVec2& inner_size, ImPlotLocation loc, const ImVec2& pad) {
  495. ImVec2 pos;
  496. if (ImHasFlag(loc, ImPlotLocation_West) && !ImHasFlag(loc, ImPlotLocation_East))
  497. pos.x = outer_rect.Min.x + pad.x;
  498. else if (!ImHasFlag(loc, ImPlotLocation_West) && ImHasFlag(loc, ImPlotLocation_East))
  499. pos.x = outer_rect.Max.x - pad.x - inner_size.x;
  500. else
  501. pos.x = outer_rect.GetCenter().x - inner_size.x * 0.5f;
  502. // legend reference point y
  503. if (ImHasFlag(loc, ImPlotLocation_North) && !ImHasFlag(loc, ImPlotLocation_South))
  504. pos.y = outer_rect.Min.y + pad.y;
  505. else if (!ImHasFlag(loc, ImPlotLocation_North) && ImHasFlag(loc, ImPlotLocation_South))
  506. pos.y = outer_rect.Max.y - pad.y - inner_size.y;
  507. else
  508. pos.y = outer_rect.GetCenter().y - inner_size.y * 0.5f;
  509. pos.x = IM_ROUND(pos.x);
  510. pos.y = IM_ROUND(pos.y);
  511. return pos;
  512. }
  513. ImVec2 CalcLegendSize(ImPlotItemGroup& items, const ImVec2& pad, const ImVec2& spacing, bool vertical) {
  514. // vars
  515. const int nItems = items.GetLegendCount();
  516. const float txt_ht = ImGui::GetTextLineHeight();
  517. const float icon_size = txt_ht;
  518. // get label max width
  519. float max_label_width = 0;
  520. float sum_label_width = 0;
  521. for (int i = 0; i < nItems; ++i) {
  522. const char* label = items.GetLegendLabel(i);
  523. const float label_width = ImGui::CalcTextSize(label, nullptr, true).x;
  524. max_label_width = label_width > max_label_width ? label_width : max_label_width;
  525. sum_label_width += label_width;
  526. }
  527. // calc legend size
  528. const ImVec2 legend_size = vertical ?
  529. ImVec2(pad.x * 2 + icon_size + max_label_width, pad.y * 2 + nItems * txt_ht + (nItems - 1) * spacing.y) :
  530. ImVec2(pad.x * 2 + icon_size * nItems + sum_label_width + (nItems - 1) * spacing.x, pad.y * 2 + txt_ht);
  531. return legend_size;
  532. }
  533. int LegendSortingComp(const void* _a, const void* _b) {
  534. ImPlotItemGroup* items = GImPlot->SortItems;
  535. const int a = *(const int*)_a;
  536. const int b = *(const int*)_b;
  537. const char* label_a = items->GetLegendLabel(a);
  538. const char* label_b = items->GetLegendLabel(b);
  539. return strcmp(label_a,label_b);
  540. }
  541. bool ShowLegendEntries(ImPlotItemGroup& items, const ImRect& legend_bb, bool hovered, const ImVec2& pad, const ImVec2& spacing, bool vertical, ImDrawList& DrawList) {
  542. // vars
  543. const float txt_ht = ImGui::GetTextLineHeight();
  544. const float icon_size = txt_ht;
  545. const float icon_shrink = 2;
  546. ImU32 col_txt = GetStyleColorU32(ImPlotCol_LegendText);
  547. ImU32 col_txt_dis = ImAlphaU32(col_txt, 0.25f);
  548. // render each legend item
  549. float sum_label_width = 0;
  550. bool any_item_hovered = false;
  551. const int num_items = items.GetLegendCount();
  552. if (num_items < 1)
  553. return hovered;
  554. // build render order
  555. ImPlotContext& gp = *GImPlot;
  556. ImVector<int>& indices = gp.TempInt1;
  557. indices.resize(num_items);
  558. for (int i = 0; i < num_items; ++i)
  559. indices[i] = i;
  560. if (ImHasFlag(items.Legend.Flags, ImPlotLegendFlags_Sort) && num_items > 1) {
  561. gp.SortItems = &items;
  562. qsort(indices.Data, num_items, sizeof(int), LegendSortingComp);
  563. }
  564. // render
  565. for (int i = 0; i < num_items; ++i) {
  566. const int idx = indices[i];
  567. ImPlotItem* item = items.GetLegendItem(idx);
  568. const char* label = items.GetLegendLabel(idx);
  569. const float label_width = ImGui::CalcTextSize(label, nullptr, true).x;
  570. const ImVec2 top_left = vertical ?
  571. legend_bb.Min + pad + ImVec2(0, i * (txt_ht + spacing.y)) :
  572. legend_bb.Min + pad + ImVec2(i * (icon_size + spacing.x) + sum_label_width, 0);
  573. sum_label_width += label_width;
  574. ImRect icon_bb;
  575. icon_bb.Min = top_left + ImVec2(icon_shrink,icon_shrink);
  576. icon_bb.Max = top_left + ImVec2(icon_size - icon_shrink, icon_size - icon_shrink);
  577. ImRect label_bb;
  578. label_bb.Min = top_left;
  579. label_bb.Max = top_left + ImVec2(label_width + icon_size, icon_size);
  580. ImU32 col_txt_hl;
  581. ImU32 col_item = ImAlphaU32(item->Color,1);
  582. ImRect button_bb(icon_bb.Min, label_bb.Max);
  583. ImGui::KeepAliveID(item->ID);
  584. bool item_hov = false;
  585. bool item_hld = false;
  586. bool item_clk = ImHasFlag(items.Legend.Flags, ImPlotLegendFlags_NoButtons)
  587. ? false
  588. : ImGui::ButtonBehavior(button_bb, item->ID, &item_hov, &item_hld);
  589. if (item_clk)
  590. item->Show = !item->Show;
  591. const bool can_hover = (item_hov)
  592. && (!ImHasFlag(items.Legend.Flags, ImPlotLegendFlags_NoHighlightItem)
  593. || !ImHasFlag(items.Legend.Flags, ImPlotLegendFlags_NoHighlightAxis));
  594. if (can_hover) {
  595. item->LegendHoverRect.Min = icon_bb.Min;
  596. item->LegendHoverRect.Max = label_bb.Max;
  597. item->LegendHovered = true;
  598. col_txt_hl = ImMixU32(col_txt, col_item, 64);
  599. any_item_hovered = true;
  600. }
  601. else {
  602. col_txt_hl = ImGui::GetColorU32(col_txt);
  603. }
  604. ImU32 col_icon;
  605. if (item_hld)
  606. col_icon = item->Show ? ImAlphaU32(col_item,0.5f) : ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.5f);
  607. else if (item_hov)
  608. col_icon = item->Show ? ImAlphaU32(col_item,0.75f) : ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.75f);
  609. else
  610. col_icon = item->Show ? col_item : col_txt_dis;
  611. DrawList.AddRectFilled(icon_bb.Min, icon_bb.Max, col_icon);
  612. const char* text_display_end = ImGui::FindRenderedTextEnd(label, nullptr);
  613. if (label != text_display_end)
  614. DrawList.AddText(top_left + ImVec2(icon_size, 0), item->Show ? col_txt_hl : col_txt_dis, label, text_display_end);
  615. }
  616. return hovered && !any_item_hovered;
  617. }
  618. //-----------------------------------------------------------------------------
  619. // Locators
  620. //-----------------------------------------------------------------------------
  621. static const float TICK_FILL_X = 0.8f;
  622. static const float TICK_FILL_Y = 1.0f;
  623. void Locator_Default(ImPlotTicker& ticker, const ImPlotRange& range, float pixels, bool vertical, ImPlotFormatter formatter, void* formatter_data) {
  624. if (range.Min == range.Max)
  625. return;
  626. const int nMinor = 10;
  627. const int nMajor = ImMax(2, (int)IM_ROUND(pixels / (vertical ? 300.0f : 400.0f)));
  628. const double nice_range = NiceNum(range.Size() * 0.99, false);
  629. const double interval = NiceNum(nice_range / (nMajor - 1), true);
  630. const double graphmin = floor(range.Min / interval) * interval;
  631. const double graphmax = ceil(range.Max / interval) * interval;
  632. bool first_major_set = false;
  633. int first_major_idx = 0;
  634. const int idx0 = ticker.TickCount(); // ticker may have user custom ticks
  635. ImVec2 total_size(0,0);
  636. for (double major = graphmin; major < graphmax + 0.5 * interval; major += interval) {
  637. // is this zero? combat zero formatting issues
  638. if (major-interval < 0 && major+interval > 0)
  639. major = 0;
  640. if (range.Contains(major)) {
  641. if (!first_major_set) {
  642. first_major_idx = ticker.TickCount();
  643. first_major_set = true;
  644. }
  645. total_size += ticker.AddTick(major, true, 0, true, formatter, formatter_data).LabelSize;
  646. }
  647. for (int i = 1; i < nMinor; ++i) {
  648. double minor = major + i * interval / nMinor;
  649. if (range.Contains(minor)) {
  650. total_size += ticker.AddTick(minor, false, 0, true, formatter, formatter_data).LabelSize;
  651. }
  652. }
  653. }
  654. // prune if necessary
  655. if ((!vertical && total_size.x > pixels*TICK_FILL_X) || (vertical && total_size.y > pixels*TICK_FILL_Y)) {
  656. for (int i = first_major_idx-1; i >= idx0; i -= 2)
  657. ticker.Ticks[i].ShowLabel = false;
  658. for (int i = first_major_idx+1; i < ticker.TickCount(); i += 2)
  659. ticker.Ticks[i].ShowLabel = false;
  660. }
  661. }
  662. bool CalcLogarithmicExponents(const ImPlotRange& range, float pix, bool vertical, int& exp_min, int& exp_max, int& exp_step) {
  663. if (range.Min * range.Max > 0) {
  664. const int nMajor = vertical ? ImMax(2, (int)IM_ROUND(pix * 0.02f)) : ImMax(2, (int)IM_ROUND(pix * 0.01f)); // TODO: magic numbers
  665. double log_min = ImLog10(ImAbs(range.Min));
  666. double log_max = ImLog10(ImAbs(range.Max));
  667. double log_a = ImMin(log_min,log_max);
  668. double log_b = ImMax(log_min,log_max);
  669. exp_step = ImMax(1,(int)(log_b - log_a) / nMajor);
  670. exp_min = (int)log_a;
  671. exp_max = (int)log_b;
  672. if (exp_step != 1) {
  673. while(exp_step % 3 != 0) exp_step++; // make step size multiple of three
  674. while(exp_min % exp_step != 0) exp_min--; // decrease exp_min until exp_min + N * exp_step will be 0
  675. }
  676. return true;
  677. }
  678. return false;
  679. }
  680. void AddTicksLogarithmic(const ImPlotRange& range, int exp_min, int exp_max, int exp_step, ImPlotTicker& ticker, ImPlotFormatter formatter, void* data) {
  681. const double sign = ImSign(range.Max);
  682. for (int e = exp_min - exp_step; e < (exp_max + exp_step); e += exp_step) {
  683. double major1 = sign*ImPow(10, (double)(e));
  684. double major2 = sign*ImPow(10, (double)(e + 1));
  685. double interval = (major2 - major1) / 9;
  686. if (major1 >= (range.Min - DBL_EPSILON) && major1 <= (range.Max + DBL_EPSILON))
  687. ticker.AddTick(major1, true, 0, true, formatter, data);
  688. for (int j = 0; j < exp_step; ++j) {
  689. major1 = sign*ImPow(10, (double)(e+j));
  690. major2 = sign*ImPow(10, (double)(e+j+1));
  691. interval = (major2 - major1) / 9;
  692. for (int i = 1; i < (9 + (int)(j < (exp_step - 1))); ++i) {
  693. double minor = major1 + i * interval;
  694. if (minor >= (range.Min - DBL_EPSILON) && minor <= (range.Max + DBL_EPSILON))
  695. ticker.AddTick(minor, false, 0, false, formatter, data);
  696. }
  697. }
  698. }
  699. }
  700. void Locator_Log10(ImPlotTicker& ticker, const ImPlotRange& range, float pixels, bool vertical, ImPlotFormatter formatter, void* formatter_data) {
  701. int exp_min, exp_max, exp_step;
  702. if (CalcLogarithmicExponents(range, pixels, vertical, exp_min, exp_max, exp_step))
  703. AddTicksLogarithmic(range, exp_min, exp_max, exp_step, ticker, formatter, formatter_data);
  704. }
  705. float CalcSymLogPixel(double plt, const ImPlotRange& range, float pixels) {
  706. double scaleToPixels = pixels / range.Size();
  707. double scaleMin = TransformForward_SymLog(range.Min,nullptr);
  708. double scaleMax = TransformForward_SymLog(range.Max,nullptr);
  709. double s = TransformForward_SymLog(plt, nullptr);
  710. double t = (s - scaleMin) / (scaleMax - scaleMin);
  711. plt = range.Min + range.Size() * t;
  712. return (float)(0 + scaleToPixels * (plt - range.Min));
  713. }
  714. void Locator_SymLog(ImPlotTicker& ticker, const ImPlotRange& range, float pixels, bool vertical, ImPlotFormatter formatter, void* formatter_data) {
  715. if (range.Min >= -1 && range.Max <= 1) {
  716. Locator_Default(ticker, range, pixels, vertical, formatter, formatter_data);
  717. }
  718. else if (range.Min * range.Max < 0) { // cross zero
  719. const float pix_min = 0;
  720. const float pix_max = pixels;
  721. const float pix_p1 = CalcSymLogPixel(1, range, pixels);
  722. const float pix_n1 = CalcSymLogPixel(-1, range, pixels);
  723. int exp_min_p, exp_max_p, exp_step_p;
  724. int exp_min_n, exp_max_n, exp_step_n;
  725. CalcLogarithmicExponents(ImPlotRange(1,range.Max), ImAbs(pix_max-pix_p1),vertical,exp_min_p,exp_max_p,exp_step_p);
  726. CalcLogarithmicExponents(ImPlotRange(range.Min,-1),ImAbs(pix_n1-pix_min),vertical,exp_min_n,exp_max_n,exp_step_n);
  727. int exp_step = ImMax(exp_step_n, exp_step_p);
  728. ticker.AddTick(0,true,0,true,formatter,formatter_data);
  729. AddTicksLogarithmic(ImPlotRange(1,range.Max), exp_min_p,exp_max_p,exp_step,ticker,formatter,formatter_data);
  730. AddTicksLogarithmic(ImPlotRange(range.Min,-1),exp_min_n,exp_max_n,exp_step,ticker,formatter,formatter_data);
  731. }
  732. else {
  733. Locator_Log10(ticker, range, pixels, vertical, formatter, formatter_data);
  734. }
  735. }
  736. void AddTicksCustom(const double* values, const char* const labels[], int n, ImPlotTicker& ticker, ImPlotFormatter formatter, void* data) {
  737. for (int i = 0; i < n; ++i) {
  738. if (labels != nullptr)
  739. ticker.AddTick(values[i], false, 0, true, labels[i]);
  740. else
  741. ticker.AddTick(values[i], false, 0, true, formatter, data);
  742. }
  743. }
  744. //-----------------------------------------------------------------------------
  745. // Time Ticks and Utils
  746. //-----------------------------------------------------------------------------
  747. // this may not be thread safe?
  748. static const double TimeUnitSpans[ImPlotTimeUnit_COUNT] = {
  749. 0.000001,
  750. 0.001,
  751. 1,
  752. 60,
  753. 3600,
  754. 86400,
  755. 2629800,
  756. 31557600
  757. };
  758. inline ImPlotTimeUnit GetUnitForRange(double range) {
  759. static double cutoffs[ImPlotTimeUnit_COUNT] = {0.001, 1, 60, 3600, 86400, 2629800, 31557600, IMPLOT_MAX_TIME};
  760. for (int i = 0; i < ImPlotTimeUnit_COUNT; ++i) {
  761. if (range <= cutoffs[i])
  762. return (ImPlotTimeUnit)i;
  763. }
  764. return ImPlotTimeUnit_Yr;
  765. }
  766. inline int LowerBoundStep(int max_divs, const int* divs, const int* step, int size) {
  767. if (max_divs < divs[0])
  768. return 0;
  769. for (int i = 1; i < size; ++i) {
  770. if (max_divs < divs[i])
  771. return step[i-1];
  772. }
  773. return step[size-1];
  774. }
  775. inline int GetTimeStep(int max_divs, ImPlotTimeUnit unit) {
  776. if (unit == ImPlotTimeUnit_Ms || unit == ImPlotTimeUnit_Us) {
  777. static const int step[] = {500,250,200,100,50,25,20,10,5,2,1};
  778. static const int divs[] = {2,4,5,10,20,40,50,100,200,500,1000};
  779. return LowerBoundStep(max_divs, divs, step, 11);
  780. }
  781. if (unit == ImPlotTimeUnit_S || unit == ImPlotTimeUnit_Min) {
  782. static const int step[] = {30,15,10,5,1};
  783. static const int divs[] = {2,4,6,12,60};
  784. return LowerBoundStep(max_divs, divs, step, 5);
  785. }
  786. else if (unit == ImPlotTimeUnit_Hr) {
  787. static const int step[] = {12,6,3,2,1};
  788. static const int divs[] = {2,4,8,12,24};
  789. return LowerBoundStep(max_divs, divs, step, 5);
  790. }
  791. else if (unit == ImPlotTimeUnit_Day) {
  792. static const int step[] = {14,7,2,1};
  793. static const int divs[] = {2,4,14,28};
  794. return LowerBoundStep(max_divs, divs, step, 4);
  795. }
  796. else if (unit == ImPlotTimeUnit_Mo) {
  797. static const int step[] = {6,3,2,1};
  798. static const int divs[] = {2,4,6,12};
  799. return LowerBoundStep(max_divs, divs, step, 4);
  800. }
  801. return 0;
  802. }
  803. ImPlotTime MkGmtTime(struct tm *ptm) {
  804. ImPlotTime t;
  805. #ifdef _WIN32
  806. t.S = _mkgmtime(ptm);
  807. #else
  808. t.S = timegm(ptm);
  809. #endif
  810. if (t.S < 0)
  811. t.S = 0;
  812. return t;
  813. }
  814. tm* GetGmtTime(const ImPlotTime& t, tm* ptm)
  815. {
  816. #ifdef _WIN32
  817. if (gmtime_s(ptm, &t.S) == 0)
  818. return ptm;
  819. else
  820. return nullptr;
  821. #else
  822. return gmtime_r(&t.S, ptm);
  823. #endif
  824. }
  825. ImPlotTime MkLocTime(struct tm *ptm) {
  826. ImPlotTime t;
  827. t.S = mktime(ptm);
  828. if (t.S < 0)
  829. t.S = 0;
  830. return t;
  831. }
  832. tm* GetLocTime(const ImPlotTime& t, tm* ptm) {
  833. #ifdef _WIN32
  834. if (localtime_s(ptm, &t.S) == 0)
  835. return ptm;
  836. else
  837. return nullptr;
  838. #else
  839. return localtime_r(&t.S, ptm);
  840. #endif
  841. }
  842. inline ImPlotTime MkTime(struct tm *ptm) {
  843. if (GetStyle().UseLocalTime)
  844. return MkLocTime(ptm);
  845. else
  846. return MkGmtTime(ptm);
  847. }
  848. inline tm* GetTime(const ImPlotTime& t, tm* ptm) {
  849. if (GetStyle().UseLocalTime)
  850. return GetLocTime(t,ptm);
  851. else
  852. return GetGmtTime(t,ptm);
  853. }
  854. ImPlotTime MakeTime(int year, int month, int day, int hour, int min, int sec, int us) {
  855. tm& Tm = GImPlot->Tm;
  856. int yr = year - 1900;
  857. if (yr < 0)
  858. yr = 0;
  859. sec = sec + us / 1000000;
  860. us = us % 1000000;
  861. Tm.tm_sec = sec;
  862. Tm.tm_min = min;
  863. Tm.tm_hour = hour;
  864. Tm.tm_mday = day;
  865. Tm.tm_mon = month;
  866. Tm.tm_year = yr;
  867. ImPlotTime t = MkTime(&Tm);
  868. t.Us = us;
  869. return t;
  870. }
  871. int GetYear(const ImPlotTime& t) {
  872. tm& Tm = GImPlot->Tm;
  873. GetTime(t, &Tm);
  874. return Tm.tm_year + 1900;
  875. }
  876. ImPlotTime AddTime(const ImPlotTime& t, ImPlotTimeUnit unit, int count) {
  877. tm& Tm = GImPlot->Tm;
  878. ImPlotTime t_out = t;
  879. switch(unit) {
  880. case ImPlotTimeUnit_Us: t_out.Us += count; break;
  881. case ImPlotTimeUnit_Ms: t_out.Us += count * 1000; break;
  882. case ImPlotTimeUnit_S: t_out.S += count; break;
  883. case ImPlotTimeUnit_Min: t_out.S += count * 60; break;
  884. case ImPlotTimeUnit_Hr: t_out.S += count * 3600; break;
  885. case ImPlotTimeUnit_Day: t_out.S += count * 86400; break;
  886. case ImPlotTimeUnit_Mo: for (int i = 0; i < abs(count); ++i) {
  887. GetTime(t_out, &Tm);
  888. if (count > 0)
  889. t_out.S += 86400 * GetDaysInMonth(Tm.tm_year + 1900, Tm.tm_mon);
  890. else if (count < 0)
  891. t_out.S -= 86400 * GetDaysInMonth(Tm.tm_year + 1900 - (Tm.tm_mon == 0 ? 1 : 0), Tm.tm_mon == 0 ? 11 : Tm.tm_mon - 1); // NOT WORKING
  892. }
  893. break;
  894. case ImPlotTimeUnit_Yr: for (int i = 0; i < abs(count); ++i) {
  895. if (count > 0)
  896. t_out.S += 86400 * (365 + (int)IsLeapYear(GetYear(t_out)));
  897. else if (count < 0)
  898. t_out.S -= 86400 * (365 + (int)IsLeapYear(GetYear(t_out) - 1));
  899. // this is incorrect if leap year and we are past Feb 28
  900. }
  901. break;
  902. default: break;
  903. }
  904. t_out.RollOver();
  905. return t_out;
  906. }
  907. ImPlotTime FloorTime(const ImPlotTime& t, ImPlotTimeUnit unit) {
  908. ImPlotContext& gp = *GImPlot;
  909. GetTime(t, &gp.Tm);
  910. switch (unit) {
  911. case ImPlotTimeUnit_S: return ImPlotTime(t.S, 0);
  912. case ImPlotTimeUnit_Ms: return ImPlotTime(t.S, (t.Us / 1000) * 1000);
  913. case ImPlotTimeUnit_Us: return t;
  914. case ImPlotTimeUnit_Yr: gp.Tm.tm_mon = 0; // fall-through
  915. case ImPlotTimeUnit_Mo: gp.Tm.tm_mday = 1; // fall-through
  916. case ImPlotTimeUnit_Day: gp.Tm.tm_hour = 0; // fall-through
  917. case ImPlotTimeUnit_Hr: gp.Tm.tm_min = 0; // fall-through
  918. case ImPlotTimeUnit_Min: gp.Tm.tm_sec = 0; break;
  919. default: return t;
  920. }
  921. return MkTime(&gp.Tm);
  922. }
  923. ImPlotTime CeilTime(const ImPlotTime& t, ImPlotTimeUnit unit) {
  924. return AddTime(FloorTime(t, unit), unit, 1);
  925. }
  926. ImPlotTime RoundTime(const ImPlotTime& t, ImPlotTimeUnit unit) {
  927. ImPlotTime t1 = FloorTime(t, unit);
  928. ImPlotTime t2 = AddTime(t1,unit,1);
  929. if (t1.S == t2.S)
  930. return t.Us - t1.Us < t2.Us - t.Us ? t1 : t2;
  931. return t.S - t1.S < t2.S - t.S ? t1 : t2;
  932. }
  933. ImPlotTime CombineDateTime(const ImPlotTime& date_part, const ImPlotTime& tod_part) {
  934. ImPlotContext& gp = *GImPlot;
  935. tm& Tm = gp.Tm;
  936. GetTime(date_part, &gp.Tm);
  937. int y = Tm.tm_year;
  938. int m = Tm.tm_mon;
  939. int d = Tm.tm_mday;
  940. GetTime(tod_part, &gp.Tm);
  941. Tm.tm_year = y;
  942. Tm.tm_mon = m;
  943. Tm.tm_mday = d;
  944. ImPlotTime t = MkTime(&Tm);
  945. t.Us = tod_part.Us;
  946. return t;
  947. }
  948. // TODO: allow users to define these
  949. static const char* MONTH_NAMES[] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
  950. static const char* WD_ABRVS[] = {"Su","Mo","Tu","We","Th","Fr","Sa"};
  951. static const char* MONTH_ABRVS[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
  952. int FormatTime(const ImPlotTime& t, char* buffer, int size, ImPlotTimeFmt fmt, bool use_24_hr_clk) {
  953. tm& Tm = GImPlot->Tm;
  954. GetTime(t, &Tm);
  955. const int us = t.Us % 1000;
  956. const int ms = t.Us / 1000;
  957. const int sec = Tm.tm_sec;
  958. const int min = Tm.tm_min;
  959. if (use_24_hr_clk) {
  960. const int hr = Tm.tm_hour;
  961. switch(fmt) {
  962. case ImPlotTimeFmt_Us: return ImFormatString(buffer, size, ".%03d %03d", ms, us);
  963. case ImPlotTimeFmt_SUs: return ImFormatString(buffer, size, ":%02d.%03d %03d", sec, ms, us);
  964. case ImPlotTimeFmt_SMs: return ImFormatString(buffer, size, ":%02d.%03d", sec, ms);
  965. case ImPlotTimeFmt_S: return ImFormatString(buffer, size, ":%02d", sec);
  966. case ImPlotTimeFmt_MinSMs: return ImFormatString(buffer, size, ":%02d:%02d.%03d", min, sec, ms);
  967. case ImPlotTimeFmt_HrMinSMs: return ImFormatString(buffer, size, "%02d:%02d:%02d.%03d", hr, min, sec, ms);
  968. case ImPlotTimeFmt_HrMinS: return ImFormatString(buffer, size, "%02d:%02d:%02d", hr, min, sec);
  969. case ImPlotTimeFmt_HrMin: return ImFormatString(buffer, size, "%02d:%02d", hr, min);
  970. case ImPlotTimeFmt_Hr: return ImFormatString(buffer, size, "%02d:00", hr);
  971. default: return 0;
  972. }
  973. }
  974. else {
  975. const char* ap = Tm.tm_hour < 12 ? "am" : "pm";
  976. const int hr = (Tm.tm_hour == 0 || Tm.tm_hour == 12) ? 12 : Tm.tm_hour % 12;
  977. switch(fmt) {
  978. case ImPlotTimeFmt_Us: return ImFormatString(buffer, size, ".%03d %03d", ms, us);
  979. case ImPlotTimeFmt_SUs: return ImFormatString(buffer, size, ":%02d.%03d %03d", sec, ms, us);
  980. case ImPlotTimeFmt_SMs: return ImFormatString(buffer, size, ":%02d.%03d", sec, ms);
  981. case ImPlotTimeFmt_S: return ImFormatString(buffer, size, ":%02d", sec);
  982. case ImPlotTimeFmt_MinSMs: return ImFormatString(buffer, size, ":%02d:%02d.%03d", min, sec, ms);
  983. case ImPlotTimeFmt_HrMinSMs: return ImFormatString(buffer, size, "%d:%02d:%02d.%03d%s", hr, min, sec, ms, ap);
  984. case ImPlotTimeFmt_HrMinS: return ImFormatString(buffer, size, "%d:%02d:%02d%s", hr, min, sec, ap);
  985. case ImPlotTimeFmt_HrMin: return ImFormatString(buffer, size, "%d:%02d%s", hr, min, ap);
  986. case ImPlotTimeFmt_Hr: return ImFormatString(buffer, size, "%d%s", hr, ap);
  987. default: return 0;
  988. }
  989. }
  990. }
  991. int FormatDate(const ImPlotTime& t, char* buffer, int size, ImPlotDateFmt fmt, bool use_iso_8601) {
  992. tm& Tm = GImPlot->Tm;
  993. GetTime(t, &Tm);
  994. const int day = Tm.tm_mday;
  995. const int mon = Tm.tm_mon + 1;
  996. const int year = Tm.tm_year + 1900;
  997. const int yr = year % 100;
  998. if (use_iso_8601) {
  999. switch (fmt) {
  1000. case ImPlotDateFmt_DayMo: return ImFormatString(buffer, size, "--%02d-%02d", mon, day);
  1001. case ImPlotDateFmt_DayMoYr: return ImFormatString(buffer, size, "%d-%02d-%02d", year, mon, day);
  1002. case ImPlotDateFmt_MoYr: return ImFormatString(buffer, size, "%d-%02d", year, mon);
  1003. case ImPlotDateFmt_Mo: return ImFormatString(buffer, size, "--%02d", mon);
  1004. case ImPlotDateFmt_Yr: return ImFormatString(buffer, size, "%d", year);
  1005. default: return 0;
  1006. }
  1007. }
  1008. else {
  1009. switch (fmt) {
  1010. case ImPlotDateFmt_DayMo: return ImFormatString(buffer, size, "%d/%d", mon, day);
  1011. case ImPlotDateFmt_DayMoYr: return ImFormatString(buffer, size, "%d/%d/%02d", mon, day, yr);
  1012. case ImPlotDateFmt_MoYr: return ImFormatString(buffer, size, "%s %d", MONTH_ABRVS[Tm.tm_mon], year);
  1013. case ImPlotDateFmt_Mo: return ImFormatString(buffer, size, "%s", MONTH_ABRVS[Tm.tm_mon]);
  1014. case ImPlotDateFmt_Yr: return ImFormatString(buffer, size, "%d", year);
  1015. default: return 0;
  1016. }
  1017. }
  1018. }
  1019. int FormatDateTime(const ImPlotTime& t, char* buffer, int size, ImPlotDateTimeSpec fmt) {
  1020. int written = 0;
  1021. if (fmt.Date != ImPlotDateFmt_None)
  1022. written += FormatDate(t, buffer, size, fmt.Date, fmt.UseISO8601);
  1023. if (fmt.Time != ImPlotTimeFmt_None) {
  1024. if (fmt.Date != ImPlotDateFmt_None)
  1025. buffer[written++] = ' ';
  1026. written += FormatTime(t, &buffer[written], size - written, fmt.Time, fmt.Use24HourClock);
  1027. }
  1028. return written;
  1029. }
  1030. inline float GetDateTimeWidth(ImPlotDateTimeSpec fmt) {
  1031. static const ImPlotTime t_max_width = MakeTime(2888, 12, 22, 12, 58, 58, 888888); // best guess at time that maximizes pixel width
  1032. char buffer[32];
  1033. FormatDateTime(t_max_width, buffer, 32, fmt);
  1034. return ImGui::CalcTextSize(buffer).x;
  1035. }
  1036. inline bool TimeLabelSame(const char* l1, const char* l2) {
  1037. size_t len1 = strlen(l1);
  1038. size_t len2 = strlen(l2);
  1039. size_t n = len1 < len2 ? len1 : len2;
  1040. return strcmp(l1 + len1 - n, l2 + len2 - n) == 0;
  1041. }
  1042. static const ImPlotDateTimeSpec TimeFormatLevel0[ImPlotTimeUnit_COUNT] = {
  1043. ImPlotDateTimeSpec(ImPlotDateFmt_None, ImPlotTimeFmt_Us),
  1044. ImPlotDateTimeSpec(ImPlotDateFmt_None, ImPlotTimeFmt_SMs),
  1045. ImPlotDateTimeSpec(ImPlotDateFmt_None, ImPlotTimeFmt_S),
  1046. ImPlotDateTimeSpec(ImPlotDateFmt_None, ImPlotTimeFmt_HrMin),
  1047. ImPlotDateTimeSpec(ImPlotDateFmt_None, ImPlotTimeFmt_Hr),
  1048. ImPlotDateTimeSpec(ImPlotDateFmt_DayMo, ImPlotTimeFmt_None),
  1049. ImPlotDateTimeSpec(ImPlotDateFmt_Mo, ImPlotTimeFmt_None),
  1050. ImPlotDateTimeSpec(ImPlotDateFmt_Yr, ImPlotTimeFmt_None)
  1051. };
  1052. static const ImPlotDateTimeSpec TimeFormatLevel1[ImPlotTimeUnit_COUNT] = {
  1053. ImPlotDateTimeSpec(ImPlotDateFmt_None, ImPlotTimeFmt_HrMin),
  1054. ImPlotDateTimeSpec(ImPlotDateFmt_None, ImPlotTimeFmt_HrMinS),
  1055. ImPlotDateTimeSpec(ImPlotDateFmt_None, ImPlotTimeFmt_HrMin),
  1056. ImPlotDateTimeSpec(ImPlotDateFmt_None, ImPlotTimeFmt_HrMin),
  1057. ImPlotDateTimeSpec(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_None),
  1058. ImPlotDateTimeSpec(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_None),
  1059. ImPlotDateTimeSpec(ImPlotDateFmt_Yr, ImPlotTimeFmt_None),
  1060. ImPlotDateTimeSpec(ImPlotDateFmt_Yr, ImPlotTimeFmt_None)
  1061. };
  1062. static const ImPlotDateTimeSpec TimeFormatLevel1First[ImPlotTimeUnit_COUNT] = {
  1063. ImPlotDateTimeSpec(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_HrMinS),
  1064. ImPlotDateTimeSpec(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_HrMinS),
  1065. ImPlotDateTimeSpec(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_HrMin),
  1066. ImPlotDateTimeSpec(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_HrMin),
  1067. ImPlotDateTimeSpec(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_None),
  1068. ImPlotDateTimeSpec(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_None),
  1069. ImPlotDateTimeSpec(ImPlotDateFmt_Yr, ImPlotTimeFmt_None),
  1070. ImPlotDateTimeSpec(ImPlotDateFmt_Yr, ImPlotTimeFmt_None)
  1071. };
  1072. static const ImPlotDateTimeSpec TimeFormatMouseCursor[ImPlotTimeUnit_COUNT] = {
  1073. ImPlotDateTimeSpec(ImPlotDateFmt_None, ImPlotTimeFmt_Us),
  1074. ImPlotDateTimeSpec(ImPlotDateFmt_None, ImPlotTimeFmt_SUs),
  1075. ImPlotDateTimeSpec(ImPlotDateFmt_None, ImPlotTimeFmt_SMs),
  1076. ImPlotDateTimeSpec(ImPlotDateFmt_None, ImPlotTimeFmt_HrMinS),
  1077. ImPlotDateTimeSpec(ImPlotDateFmt_None, ImPlotTimeFmt_HrMin),
  1078. ImPlotDateTimeSpec(ImPlotDateFmt_DayMo, ImPlotTimeFmt_Hr),
  1079. ImPlotDateTimeSpec(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_None),
  1080. ImPlotDateTimeSpec(ImPlotDateFmt_MoYr, ImPlotTimeFmt_None)
  1081. };
  1082. inline ImPlotDateTimeSpec GetDateTimeFmt(const ImPlotDateTimeSpec* ctx, ImPlotTimeUnit idx) {
  1083. ImPlotStyle& style = GetStyle();
  1084. ImPlotDateTimeSpec fmt = ctx[idx];
  1085. fmt.UseISO8601 = style.UseISO8601;
  1086. fmt.Use24HourClock = style.Use24HourClock;
  1087. return fmt;
  1088. }
  1089. void Locator_Time(ImPlotTicker& ticker, const ImPlotRange& range, float pixels, bool vertical, ImPlotFormatter formatter, void* formatter_data) {
  1090. IM_ASSERT_USER_ERROR(vertical == false, "Cannot locate Time ticks on vertical axis!");
  1091. (void)vertical;
  1092. // get units for level 0 and level 1 labels
  1093. const ImPlotTimeUnit unit0 = GetUnitForRange(range.Size() / (pixels / 100)); // level = 0 (top)
  1094. const ImPlotTimeUnit unit1 = ImClamp(unit0 + 1, 0, ImPlotTimeUnit_COUNT-1); // level = 1 (bottom)
  1095. // get time format specs
  1096. const ImPlotDateTimeSpec fmt0 = GetDateTimeFmt(TimeFormatLevel0, unit0);
  1097. const ImPlotDateTimeSpec fmt1 = GetDateTimeFmt(TimeFormatLevel1, unit1);
  1098. const ImPlotDateTimeSpec fmtf = GetDateTimeFmt(TimeFormatLevel1First, unit1);
  1099. // min max times
  1100. const ImPlotTime t_min = ImPlotTime::FromDouble(range.Min);
  1101. const ImPlotTime t_max = ImPlotTime::FromDouble(range.Max);
  1102. // maximum allowable density of labels
  1103. const float max_density = 0.5f;
  1104. // book keeping
  1105. int last_major_offset = -1;
  1106. // formatter data
  1107. Formatter_Time_Data ftd;
  1108. ftd.UserFormatter = formatter;
  1109. ftd.UserFormatterData = formatter_data;
  1110. if (unit0 != ImPlotTimeUnit_Yr) {
  1111. // pixels per major (level 1) division
  1112. const float pix_per_major_div = pixels / (float)(range.Size() / TimeUnitSpans[unit1]);
  1113. // nominal pixels taken up by labels
  1114. const float fmt0_width = GetDateTimeWidth(fmt0);
  1115. const float fmt1_width = GetDateTimeWidth(fmt1);
  1116. const float fmtf_width = GetDateTimeWidth(fmtf);
  1117. // the maximum number of minor (level 0) labels that can fit between major (level 1) divisions
  1118. const int minor_per_major = (int)(max_density * pix_per_major_div / fmt0_width);
  1119. // the minor step size (level 0)
  1120. const int step = GetTimeStep(minor_per_major, unit0);
  1121. // generate ticks
  1122. ImPlotTime t1 = FloorTime(ImPlotTime::FromDouble(range.Min), unit1);
  1123. while (t1 < t_max) {
  1124. // get next major
  1125. const ImPlotTime t2 = AddTime(t1, unit1, 1);
  1126. // add major tick
  1127. if (t1 >= t_min && t1 <= t_max) {
  1128. // minor level 0 tick
  1129. ftd.Time = t1; ftd.Spec = fmt0;
  1130. ticker.AddTick(t1.ToDouble(), true, 0, true, Formatter_Time, &ftd);
  1131. // major level 1 tick
  1132. ftd.Time = t1; ftd.Spec = last_major_offset < 0 ? fmtf : fmt1;
  1133. ImPlotTick& tick_maj = ticker.AddTick(t1.ToDouble(), true, 1, true, Formatter_Time, &ftd);
  1134. const char* this_major = ticker.GetText(tick_maj);
  1135. if (last_major_offset >= 0 && TimeLabelSame(ticker.TextBuffer.Buf.Data + last_major_offset, this_major))
  1136. tick_maj.ShowLabel = false;
  1137. last_major_offset = tick_maj.TextOffset;
  1138. }
  1139. // add minor ticks up until next major
  1140. if (minor_per_major > 1 && (t_min <= t2 && t1 <= t_max)) {
  1141. ImPlotTime t12 = AddTime(t1, unit0, step);
  1142. while (t12 < t2) {
  1143. float px_to_t2 = (float)((t2 - t12).ToDouble()/range.Size()) * pixels;
  1144. if (t12 >= t_min && t12 <= t_max) {
  1145. ftd.Time = t12; ftd.Spec = fmt0;
  1146. ticker.AddTick(t12.ToDouble(), false, 0, px_to_t2 >= fmt0_width, Formatter_Time, &ftd);
  1147. if (last_major_offset < 0 && px_to_t2 >= fmt0_width && px_to_t2 >= (fmt1_width + fmtf_width) / 2) {
  1148. ftd.Time = t12; ftd.Spec = fmtf;
  1149. ImPlotTick& tick_maj = ticker.AddTick(t12.ToDouble(), true, 1, true, Formatter_Time, &ftd);
  1150. last_major_offset = tick_maj.TextOffset;
  1151. }
  1152. }
  1153. t12 = AddTime(t12, unit0, step);
  1154. }
  1155. }
  1156. t1 = t2;
  1157. }
  1158. }
  1159. else {
  1160. const ImPlotDateTimeSpec fmty = GetDateTimeFmt(TimeFormatLevel0, ImPlotTimeUnit_Yr);
  1161. const float label_width = GetDateTimeWidth(fmty);
  1162. const int max_labels = (int)(max_density * pixels / label_width);
  1163. const int year_min = GetYear(t_min);
  1164. const int year_max = GetYear(CeilTime(t_max, ImPlotTimeUnit_Yr));
  1165. const double nice_range = NiceNum((year_max - year_min)*0.99,false);
  1166. const double interval = NiceNum(nice_range / (max_labels - 1), true);
  1167. const int graphmin = (int)(floor(year_min / interval) * interval);
  1168. const int graphmax = (int)(ceil(year_max / interval) * interval);
  1169. const int step = (int)interval <= 0 ? 1 : (int)interval;
  1170. for (int y = graphmin; y < graphmax; y += step) {
  1171. ImPlotTime t = MakeTime(y);
  1172. if (t >= t_min && t <= t_max) {
  1173. ftd.Time = t; ftd.Spec = fmty;
  1174. ticker.AddTick(t.ToDouble(), true, 0, true, Formatter_Time, &ftd);
  1175. }
  1176. }
  1177. }
  1178. }
  1179. //-----------------------------------------------------------------------------
  1180. // Context Menu
  1181. //-----------------------------------------------------------------------------
  1182. template <typename F>
  1183. bool DragFloat(const char*, F*, float, F, F) {
  1184. return false;
  1185. }
  1186. template <>
  1187. bool DragFloat<double>(const char* label, double* v, float v_speed, double v_min, double v_max) {
  1188. return ImGui::DragScalar(label, ImGuiDataType_Double, v, v_speed, &v_min, &v_max, "%.3g", 1);
  1189. }
  1190. template <>
  1191. bool DragFloat<float>(const char* label, float* v, float v_speed, float v_min, float v_max) {
  1192. return ImGui::DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, "%.3g", 1);
  1193. }
  1194. inline void BeginDisabledControls(bool cond) {
  1195. if (cond) {
  1196. ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);
  1197. ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.25f);
  1198. }
  1199. }
  1200. inline void EndDisabledControls(bool cond) {
  1201. if (cond) {
  1202. ImGui::PopItemFlag();
  1203. ImGui::PopStyleVar();
  1204. }
  1205. }
  1206. void ShowAxisContextMenu(ImPlotAxis& axis, ImPlotAxis* equal_axis, bool /*time_allowed*/) {
  1207. ImGui::PushItemWidth(75);
  1208. bool always_locked = axis.IsRangeLocked() || axis.IsAutoFitting();
  1209. bool label = axis.HasLabel();
  1210. bool grid = axis.HasGridLines();
  1211. bool ticks = axis.HasTickMarks();
  1212. bool labels = axis.HasTickLabels();
  1213. double drag_speed = (axis.Range.Size() <= DBL_EPSILON) ? DBL_EPSILON * 1.0e+13 : 0.01 * axis.Range.Size(); // recover from almost equal axis limits.
  1214. if (axis.Scale == ImPlotScale_Time) {
  1215. ImPlotTime tmin = ImPlotTime::FromDouble(axis.Range.Min);
  1216. ImPlotTime tmax = ImPlotTime::FromDouble(axis.Range.Max);
  1217. BeginDisabledControls(always_locked);
  1218. ImGui::CheckboxFlags("##LockMin", (unsigned int*)&axis.Flags, ImPlotAxisFlags_LockMin);
  1219. EndDisabledControls(always_locked);
  1220. ImGui::SameLine();
  1221. BeginDisabledControls(axis.IsLockedMin() || always_locked);
  1222. if (ImGui::BeginMenu("Min Time")) {
  1223. if (ShowTimePicker("mintime", &tmin)) {
  1224. if (tmin >= tmax)
  1225. tmax = AddTime(tmin, ImPlotTimeUnit_S, 1);
  1226. axis.SetRange(tmin.ToDouble(),tmax.ToDouble());
  1227. }
  1228. ImGui::Separator();
  1229. if (ShowDatePicker("mindate",&axis.PickerLevel,&axis.PickerTimeMin,&tmin,&tmax)) {
  1230. tmin = CombineDateTime(axis.PickerTimeMin, tmin);
  1231. if (tmin >= tmax)
  1232. tmax = AddTime(tmin, ImPlotTimeUnit_S, 1);
  1233. axis.SetRange(tmin.ToDouble(), tmax.ToDouble());
  1234. }
  1235. ImGui::EndMenu();
  1236. }
  1237. EndDisabledControls(axis.IsLockedMin() || always_locked);
  1238. BeginDisabledControls(always_locked);
  1239. ImGui::CheckboxFlags("##LockMax", (unsigned int*)&axis.Flags, ImPlotAxisFlags_LockMax);
  1240. EndDisabledControls(always_locked);
  1241. ImGui::SameLine();
  1242. BeginDisabledControls(axis.IsLockedMax() || always_locked);
  1243. if (ImGui::BeginMenu("Max Time")) {
  1244. if (ShowTimePicker("maxtime", &tmax)) {
  1245. if (tmax <= tmin)
  1246. tmin = AddTime(tmax, ImPlotTimeUnit_S, -1);
  1247. axis.SetRange(tmin.ToDouble(),tmax.ToDouble());
  1248. }
  1249. ImGui::Separator();
  1250. if (ShowDatePicker("maxdate",&axis.PickerLevel,&axis.PickerTimeMax,&tmin,&tmax)) {
  1251. tmax = CombineDateTime(axis.PickerTimeMax, tmax);
  1252. if (tmax <= tmin)
  1253. tmin = AddTime(tmax, ImPlotTimeUnit_S, -1);
  1254. axis.SetRange(tmin.ToDouble(), tmax.ToDouble());
  1255. }
  1256. ImGui::EndMenu();
  1257. }
  1258. EndDisabledControls(axis.IsLockedMax() || always_locked);
  1259. }
  1260. else {
  1261. BeginDisabledControls(always_locked);
  1262. ImGui::CheckboxFlags("##LockMin", (unsigned int*)&axis.Flags, ImPlotAxisFlags_LockMin);
  1263. EndDisabledControls(always_locked);
  1264. ImGui::SameLine();
  1265. BeginDisabledControls(axis.IsLockedMin() || always_locked);
  1266. double temp_min = axis.Range.Min;
  1267. if (DragFloat("Min", &temp_min, (float)drag_speed, -HUGE_VAL, axis.Range.Max - DBL_EPSILON)) {
  1268. axis.SetMin(temp_min,true);
  1269. if (equal_axis != nullptr)
  1270. equal_axis->SetAspect(axis.GetAspect());
  1271. }
  1272. EndDisabledControls(axis.IsLockedMin() || always_locked);
  1273. BeginDisabledControls(always_locked);
  1274. ImGui::CheckboxFlags("##LockMax", (unsigned int*)&axis.Flags, ImPlotAxisFlags_LockMax);
  1275. EndDisabledControls(always_locked);
  1276. ImGui::SameLine();
  1277. BeginDisabledControls(axis.IsLockedMax() || always_locked);
  1278. double temp_max = axis.Range.Max;
  1279. if (DragFloat("Max", &temp_max, (float)drag_speed, axis.Range.Min + DBL_EPSILON, HUGE_VAL)) {
  1280. axis.SetMax(temp_max,true);
  1281. if (equal_axis != nullptr)
  1282. equal_axis->SetAspect(axis.GetAspect());
  1283. }
  1284. EndDisabledControls(axis.IsLockedMax() || always_locked);
  1285. }
  1286. ImGui::Separator();
  1287. ImGui::CheckboxFlags("Auto-Fit",(unsigned int*)&axis.Flags, ImPlotAxisFlags_AutoFit);
  1288. // TODO
  1289. // BeginDisabledControls(axis.IsTime() && time_allowed);
  1290. // ImGui::CheckboxFlags("Log Scale",(unsigned int*)&axis.Flags, ImPlotAxisFlags_LogScale);
  1291. // EndDisabledControls(axis.IsTime() && time_allowed);
  1292. // if (time_allowed) {
  1293. // BeginDisabledControls(axis.IsLog() || axis.IsSymLog());
  1294. // ImGui::CheckboxFlags("Time",(unsigned int*)&axis.Flags, ImPlotAxisFlags_Time);
  1295. // EndDisabledControls(axis.IsLog() || axis.IsSymLog());
  1296. // }
  1297. ImGui::Separator();
  1298. ImGui::CheckboxFlags("Invert",(unsigned int*)&axis.Flags, ImPlotAxisFlags_Invert);
  1299. ImGui::CheckboxFlags("Opposite",(unsigned int*)&axis.Flags, ImPlotAxisFlags_Opposite);
  1300. ImGui::Separator();
  1301. BeginDisabledControls(axis.LabelOffset == -1);
  1302. if (ImGui::Checkbox("Label", &label))
  1303. ImFlipFlag(axis.Flags, ImPlotAxisFlags_NoLabel);
  1304. EndDisabledControls(axis.LabelOffset == -1);
  1305. if (ImGui::Checkbox("Grid Lines", &grid))
  1306. ImFlipFlag(axis.Flags, ImPlotAxisFlags_NoGridLines);
  1307. if (ImGui::Checkbox("Tick Marks", &ticks))
  1308. ImFlipFlag(axis.Flags, ImPlotAxisFlags_NoTickMarks);
  1309. if (ImGui::Checkbox("Tick Labels", &labels))
  1310. ImFlipFlag(axis.Flags, ImPlotAxisFlags_NoTickLabels);
  1311. }
  1312. bool ShowLegendContextMenu(ImPlotLegend& legend, bool visible) {
  1313. const float s = ImGui::GetFrameHeight();
  1314. bool ret = false;
  1315. if (ImGui::Checkbox("Show",&visible))
  1316. ret = true;
  1317. if (legend.CanGoInside)
  1318. ImGui::CheckboxFlags("Outside",(unsigned int*)&legend.Flags, ImPlotLegendFlags_Outside);
  1319. if (ImGui::RadioButton("H", ImHasFlag(legend.Flags, ImPlotLegendFlags_Horizontal)))
  1320. legend.Flags |= ImPlotLegendFlags_Horizontal;
  1321. ImGui::SameLine();
  1322. if (ImGui::RadioButton("V", !ImHasFlag(legend.Flags, ImPlotLegendFlags_Horizontal)))
  1323. legend.Flags &= ~ImPlotLegendFlags_Horizontal;
  1324. ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2,2));
  1325. if (ImGui::Button("NW",ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_NorthWest; } ImGui::SameLine();
  1326. if (ImGui::Button("N", ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_North; } ImGui::SameLine();
  1327. if (ImGui::Button("NE",ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_NorthEast; }
  1328. if (ImGui::Button("W", ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_West; } ImGui::SameLine();
  1329. if (ImGui::InvisibleButton("C", ImVec2(1.5f*s,s))) { } ImGui::SameLine();
  1330. if (ImGui::Button("E", ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_East; }
  1331. if (ImGui::Button("SW",ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_SouthWest; } ImGui::SameLine();
  1332. if (ImGui::Button("S", ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_South; } ImGui::SameLine();
  1333. if (ImGui::Button("SE",ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_SouthEast; }
  1334. ImGui::PopStyleVar();
  1335. return ret;
  1336. }
  1337. void ShowSubplotsContextMenu(ImPlotSubplot& subplot) {
  1338. if ((ImGui::BeginMenu("Linking"))) {
  1339. if (ImGui::MenuItem("Link Rows",nullptr,ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkRows)))
  1340. ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_LinkRows);
  1341. if (ImGui::MenuItem("Link Cols",nullptr,ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkCols)))
  1342. ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_LinkCols);
  1343. if (ImGui::MenuItem("Link All X",nullptr,ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkAllX)))
  1344. ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_LinkAllX);
  1345. if (ImGui::MenuItem("Link All Y",nullptr,ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkAllY)))
  1346. ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_LinkAllY);
  1347. ImGui::EndMenu();
  1348. }
  1349. if ((ImGui::BeginMenu("Settings"))) {
  1350. BeginDisabledControls(!subplot.HasTitle);
  1351. if (ImGui::MenuItem("Title",nullptr,subplot.HasTitle && !ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoTitle)))
  1352. ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_NoTitle);
  1353. EndDisabledControls(!subplot.HasTitle);
  1354. if (ImGui::MenuItem("Resizable",nullptr,!ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoResize)))
  1355. ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_NoResize);
  1356. if (ImGui::MenuItem("Align",nullptr,!ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoAlign)))
  1357. ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_NoAlign);
  1358. if (ImGui::MenuItem("Share Items",nullptr,ImHasFlag(subplot.Flags, ImPlotSubplotFlags_ShareItems)))
  1359. ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_ShareItems);
  1360. ImGui::EndMenu();
  1361. }
  1362. }
  1363. void ShowPlotContextMenu(ImPlotPlot& plot) {
  1364. ImPlotContext& gp = *GImPlot;
  1365. const bool owns_legend = gp.CurrentItems == &plot.Items;
  1366. const bool equal = ImHasFlag(plot.Flags, ImPlotFlags_Equal);
  1367. char buf[16] = {};
  1368. for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {
  1369. ImPlotAxis& x_axis = plot.XAxis(i);
  1370. if (!x_axis.Enabled || !x_axis.HasMenus())
  1371. continue;
  1372. ImGui::PushID(i);
  1373. ImFormatString(buf, sizeof(buf) - 1, i == 0 ? "X-Axis" : "X-Axis %d", i + 1);
  1374. if (ImGui::BeginMenu(x_axis.HasLabel() ? plot.GetAxisLabel(x_axis) : buf)) {
  1375. ShowAxisContextMenu(x_axis, equal ? x_axis.OrthoAxis : nullptr, false);
  1376. ImGui::EndMenu();
  1377. }
  1378. ImGui::PopID();
  1379. }
  1380. for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {
  1381. ImPlotAxis& y_axis = plot.YAxis(i);
  1382. if (!y_axis.Enabled || !y_axis.HasMenus())
  1383. continue;
  1384. ImGui::PushID(i);
  1385. ImFormatString(buf, sizeof(buf) - 1, i == 0 ? "Y-Axis" : "Y-Axis %d", i + 1);
  1386. if (ImGui::BeginMenu(y_axis.HasLabel() ? plot.GetAxisLabel(y_axis) : buf)) {
  1387. ShowAxisContextMenu(y_axis, equal ? y_axis.OrthoAxis : nullptr, false);
  1388. ImGui::EndMenu();
  1389. }
  1390. ImGui::PopID();
  1391. }
  1392. ImGui::Separator();
  1393. if (!ImHasFlag(gp.CurrentItems->Legend.Flags, ImPlotLegendFlags_NoMenus)) {
  1394. if ((ImGui::BeginMenu("Legend"))) {
  1395. if (owns_legend) {
  1396. if (ShowLegendContextMenu(plot.Items.Legend, !ImHasFlag(plot.Flags, ImPlotFlags_NoLegend)))
  1397. ImFlipFlag(plot.Flags, ImPlotFlags_NoLegend);
  1398. }
  1399. else if (gp.CurrentSubplot != nullptr) {
  1400. if (ShowLegendContextMenu(gp.CurrentSubplot->Items.Legend, !ImHasFlag(gp.CurrentSubplot->Flags, ImPlotSubplotFlags_NoLegend)))
  1401. ImFlipFlag(gp.CurrentSubplot->Flags, ImPlotSubplotFlags_NoLegend);
  1402. }
  1403. ImGui::EndMenu();
  1404. }
  1405. }
  1406. if ((ImGui::BeginMenu("Settings"))) {
  1407. if (ImGui::MenuItem("Equal", nullptr, ImHasFlag(plot.Flags, ImPlotFlags_Equal)))
  1408. ImFlipFlag(plot.Flags, ImPlotFlags_Equal);
  1409. if (ImGui::MenuItem("Box Select",nullptr,!ImHasFlag(plot.Flags, ImPlotFlags_NoBoxSelect)))
  1410. ImFlipFlag(plot.Flags, ImPlotFlags_NoBoxSelect);
  1411. BeginDisabledControls(plot.TitleOffset == -1);
  1412. if (ImGui::MenuItem("Title",nullptr,plot.HasTitle()))
  1413. ImFlipFlag(plot.Flags, ImPlotFlags_NoTitle);
  1414. EndDisabledControls(plot.TitleOffset == -1);
  1415. if (ImGui::MenuItem("Mouse Position",nullptr,!ImHasFlag(plot.Flags, ImPlotFlags_NoMouseText)))
  1416. ImFlipFlag(plot.Flags, ImPlotFlags_NoMouseText);
  1417. if (ImGui::MenuItem("Crosshairs",nullptr,ImHasFlag(plot.Flags, ImPlotFlags_Crosshairs)))
  1418. ImFlipFlag(plot.Flags, ImPlotFlags_Crosshairs);
  1419. ImGui::EndMenu();
  1420. }
  1421. if (gp.CurrentSubplot != nullptr && !ImHasFlag(gp.CurrentSubplot->Flags, ImPlotSubplotFlags_NoMenus)) {
  1422. ImGui::Separator();
  1423. if ((ImGui::BeginMenu("Subplots"))) {
  1424. ShowSubplotsContextMenu(*gp.CurrentSubplot);
  1425. ImGui::EndMenu();
  1426. }
  1427. }
  1428. }
  1429. //-----------------------------------------------------------------------------
  1430. // Axis Utils
  1431. //-----------------------------------------------------------------------------
  1432. static inline int AxisPrecision(const ImPlotAxis& axis) {
  1433. const double range = axis.Ticker.TickCount() > 1 ? (axis.Ticker.Ticks[1].PlotPos - axis.Ticker.Ticks[0].PlotPos) : axis.Range.Size();
  1434. return Precision(range);
  1435. }
  1436. static inline double RoundAxisValue(const ImPlotAxis& axis, double value) {
  1437. return RoundTo(value, AxisPrecision(axis));
  1438. }
  1439. void LabelAxisValue(const ImPlotAxis& axis, double value, char* buff, int size, bool round) {
  1440. ImPlotContext& gp = *GImPlot;
  1441. // TODO: We shouldn't explicitly check that the axis is Time here. Ideally,
  1442. // Formatter_Time would handle the formatting for us, but the code below
  1443. // needs additional arguments which are not currently available in ImPlotFormatter
  1444. if (axis.Locator == Locator_Time) {
  1445. ImPlotTimeUnit unit = axis.Vertical
  1446. ? GetUnitForRange(axis.Range.Size() / (gp.CurrentPlot->PlotRect.GetHeight() / 100)) // TODO: magic value!
  1447. : GetUnitForRange(axis.Range.Size() / (gp.CurrentPlot->PlotRect.GetWidth() / 100)); // TODO: magic value!
  1448. FormatDateTime(ImPlotTime::FromDouble(value), buff, size, GetDateTimeFmt(TimeFormatMouseCursor, unit));
  1449. }
  1450. else {
  1451. if (round)
  1452. value = RoundAxisValue(axis, value);
  1453. axis.Formatter(value, buff, size, axis.FormatterData);
  1454. }
  1455. }
  1456. void UpdateAxisColors(ImPlotAxis& axis) {
  1457. const ImVec4 col_grid = GetStyleColorVec4(ImPlotCol_AxisGrid);
  1458. axis.ColorMaj = ImGui::GetColorU32(col_grid);
  1459. axis.ColorMin = ImGui::GetColorU32(col_grid*ImVec4(1,1,1,GImPlot->Style.MinorAlpha));
  1460. axis.ColorTick = GetStyleColorU32(ImPlotCol_AxisTick);
  1461. axis.ColorTxt = GetStyleColorU32(ImPlotCol_AxisText);
  1462. axis.ColorBg = GetStyleColorU32(ImPlotCol_AxisBg);
  1463. axis.ColorHov = GetStyleColorU32(ImPlotCol_AxisBgHovered);
  1464. axis.ColorAct = GetStyleColorU32(ImPlotCol_AxisBgActive);
  1465. // axis.ColorHiLi = IM_COL32_BLACK_TRANS;
  1466. }
  1467. void PadAndDatumAxesX(ImPlotPlot& plot, float& pad_T, float& pad_B, ImPlotAlignmentData* align) {
  1468. ImPlotContext& gp = *GImPlot;
  1469. const float T = ImGui::GetTextLineHeight();
  1470. const float P = gp.Style.LabelPadding.y;
  1471. const float K = gp.Style.MinorTickLen.x;
  1472. int count_T = 0;
  1473. int count_B = 0;
  1474. float last_T = plot.AxesRect.Min.y;
  1475. float last_B = plot.AxesRect.Max.y;
  1476. for (int i = IMPLOT_NUM_X_AXES; i-- > 0;) { // FYI: can iterate forward
  1477. ImPlotAxis& axis = plot.XAxis(i);
  1478. if (!axis.Enabled)
  1479. continue;
  1480. const bool label = axis.HasLabel();
  1481. const bool ticks = axis.HasTickLabels();
  1482. const bool opp = axis.IsOpposite();
  1483. const bool time = axis.Scale == ImPlotScale_Time;
  1484. if (opp) {
  1485. if (count_T++ > 0)
  1486. pad_T += K + P;
  1487. if (label)
  1488. pad_T += T + P;
  1489. if (ticks)
  1490. pad_T += ImMax(T, axis.Ticker.MaxSize.y) + P + (time ? T + P : 0);
  1491. axis.Datum1 = plot.CanvasRect.Min.y + pad_T;
  1492. axis.Datum2 = last_T;
  1493. last_T = axis.Datum1;
  1494. }
  1495. else {
  1496. if (count_B++ > 0)
  1497. pad_B += K + P;
  1498. if (label)
  1499. pad_B += T + P;
  1500. if (ticks)
  1501. pad_B += ImMax(T, axis.Ticker.MaxSize.y) + P + (time ? T + P : 0);
  1502. axis.Datum1 = plot.CanvasRect.Max.y - pad_B;
  1503. axis.Datum2 = last_B;
  1504. last_B = axis.Datum1;
  1505. }
  1506. }
  1507. if (align) {
  1508. count_T = count_B = 0;
  1509. float delta_T, delta_B;
  1510. align->Update(pad_T,pad_B,delta_T,delta_B);
  1511. for (int i = IMPLOT_NUM_X_AXES; i-- > 0;) {
  1512. ImPlotAxis& axis = plot.XAxis(i);
  1513. if (!axis.Enabled)
  1514. continue;
  1515. if (axis.IsOpposite()) {
  1516. axis.Datum1 += delta_T;
  1517. axis.Datum2 += count_T++ > 1 ? delta_T : 0;
  1518. }
  1519. else {
  1520. axis.Datum1 -= delta_B;
  1521. axis.Datum2 -= count_B++ > 1 ? delta_B : 0;
  1522. }
  1523. }
  1524. }
  1525. }
  1526. void PadAndDatumAxesY(ImPlotPlot& plot, float& pad_L, float& pad_R, ImPlotAlignmentData* align) {
  1527. // [ pad_L ] [ pad_R ]
  1528. // .................CanvasRect................
  1529. // :TPWPK.PTPWP _____PlotRect____ PWPTP.KPWPT:
  1530. // :A # |- A # |- -| # A -| # A:
  1531. // :X | X | | X | x:
  1532. // :I # |- I # |- -| # I -| # I:
  1533. // :S | S | | S | S:
  1534. // :3 # |- 0 # |-_______________-| # 1 -| # 2:
  1535. // :.........................................:
  1536. //
  1537. // T = text height
  1538. // P = label padding
  1539. // K = minor tick length
  1540. // W = label width
  1541. ImPlotContext& gp = *GImPlot;
  1542. const float T = ImGui::GetTextLineHeight();
  1543. const float P = gp.Style.LabelPadding.x;
  1544. const float K = gp.Style.MinorTickLen.y;
  1545. int count_L = 0;
  1546. int count_R = 0;
  1547. float last_L = plot.AxesRect.Min.x;
  1548. float last_R = plot.AxesRect.Max.x;
  1549. for (int i = IMPLOT_NUM_Y_AXES; i-- > 0;) { // FYI: can iterate forward
  1550. ImPlotAxis& axis = plot.YAxis(i);
  1551. if (!axis.Enabled)
  1552. continue;
  1553. const bool label = axis.HasLabel();
  1554. const bool ticks = axis.HasTickLabels();
  1555. const bool opp = axis.IsOpposite();
  1556. if (opp) {
  1557. if (count_R++ > 0)
  1558. pad_R += K + P;
  1559. if (label)
  1560. pad_R += T + P;
  1561. if (ticks)
  1562. pad_R += axis.Ticker.MaxSize.x + P;
  1563. axis.Datum1 = plot.CanvasRect.Max.x - pad_R;
  1564. axis.Datum2 = last_R;
  1565. last_R = axis.Datum1;
  1566. }
  1567. else {
  1568. if (count_L++ > 0)
  1569. pad_L += K + P;
  1570. if (label)
  1571. pad_L += T + P;
  1572. if (ticks)
  1573. pad_L += axis.Ticker.MaxSize.x + P;
  1574. axis.Datum1 = plot.CanvasRect.Min.x + pad_L;
  1575. axis.Datum2 = last_L;
  1576. last_L = axis.Datum1;
  1577. }
  1578. }
  1579. plot.PlotRect.Min.x = plot.CanvasRect.Min.x + pad_L;
  1580. plot.PlotRect.Max.x = plot.CanvasRect.Max.x - pad_R;
  1581. if (align) {
  1582. count_L = count_R = 0;
  1583. float delta_L, delta_R;
  1584. align->Update(pad_L,pad_R,delta_L,delta_R);
  1585. for (int i = IMPLOT_NUM_Y_AXES; i-- > 0;) {
  1586. ImPlotAxis& axis = plot.YAxis(i);
  1587. if (!axis.Enabled)
  1588. continue;
  1589. if (axis.IsOpposite()) {
  1590. axis.Datum1 -= delta_R;
  1591. axis.Datum2 -= count_R++ > 1 ? delta_R : 0;
  1592. }
  1593. else {
  1594. axis.Datum1 += delta_L;
  1595. axis.Datum2 += count_L++ > 1 ? delta_L : 0;
  1596. }
  1597. }
  1598. }
  1599. }
  1600. //-----------------------------------------------------------------------------
  1601. // RENDERING
  1602. //-----------------------------------------------------------------------------
  1603. static inline void RenderGridLinesX(ImDrawList& DrawList, const ImPlotTicker& ticker, const ImRect& rect, ImU32 col_maj, ImU32 col_min, float size_maj, float size_min) {
  1604. const float density = ticker.TickCount() / rect.GetWidth();
  1605. ImVec4 col_min4 = ImGui::ColorConvertU32ToFloat4(col_min);
  1606. col_min4.w *= ImClamp(ImRemap(density, 0.1f, 0.2f, 1.0f, 0.0f), 0.0f, 1.0f);
  1607. col_min = ImGui::ColorConvertFloat4ToU32(col_min4);
  1608. for (int t = 0; t < ticker.TickCount(); t++) {
  1609. const ImPlotTick& xt = ticker.Ticks[t];
  1610. if (xt.PixelPos < rect.Min.x || xt.PixelPos > rect.Max.x)
  1611. continue;
  1612. if (xt.Level == 0) {
  1613. if (xt.Major)
  1614. DrawList.AddLine(ImVec2(xt.PixelPos, rect.Min.y), ImVec2(xt.PixelPos, rect.Max.y), col_maj, size_maj);
  1615. else if (density < 0.2f)
  1616. DrawList.AddLine(ImVec2(xt.PixelPos, rect.Min.y), ImVec2(xt.PixelPos, rect.Max.y), col_min, size_min);
  1617. }
  1618. }
  1619. }
  1620. static inline void RenderGridLinesY(ImDrawList& DrawList, const ImPlotTicker& ticker, const ImRect& rect, ImU32 col_maj, ImU32 col_min, float size_maj, float size_min) {
  1621. const float density = ticker.TickCount() / rect.GetHeight();
  1622. ImVec4 col_min4 = ImGui::ColorConvertU32ToFloat4(col_min);
  1623. col_min4.w *= ImClamp(ImRemap(density, 0.1f, 0.2f, 1.0f, 0.0f), 0.0f, 1.0f);
  1624. col_min = ImGui::ColorConvertFloat4ToU32(col_min4);
  1625. for (int t = 0; t < ticker.TickCount(); t++) {
  1626. const ImPlotTick& yt = ticker.Ticks[t];
  1627. if (yt.PixelPos < rect.Min.y || yt.PixelPos > rect.Max.y)
  1628. continue;
  1629. if (yt.Major)
  1630. DrawList.AddLine(ImVec2(rect.Min.x, yt.PixelPos), ImVec2(rect.Max.x, yt.PixelPos), col_maj, size_maj);
  1631. else if (density < 0.2f)
  1632. DrawList.AddLine(ImVec2(rect.Min.x, yt.PixelPos), ImVec2(rect.Max.x, yt.PixelPos), col_min, size_min);
  1633. }
  1634. }
  1635. static inline void RenderSelectionRect(ImDrawList& DrawList, const ImVec2& p_min, const ImVec2& p_max, const ImVec4& col) {
  1636. const ImU32 col_bg = ImGui::GetColorU32(col * ImVec4(1,1,1,0.25f));
  1637. const ImU32 col_bd = ImGui::GetColorU32(col);
  1638. DrawList.AddRectFilled(p_min, p_max, col_bg);
  1639. DrawList.AddRect(p_min, p_max, col_bd);
  1640. }
  1641. //-----------------------------------------------------------------------------
  1642. // Input Handling
  1643. //-----------------------------------------------------------------------------
  1644. static const float MOUSE_CURSOR_DRAG_THRESHOLD = 5.0f;
  1645. static const float BOX_SELECT_DRAG_THRESHOLD = 4.0f;
  1646. bool UpdateInput(ImPlotPlot& plot) {
  1647. bool changed = false;
  1648. ImPlotContext& gp = *GImPlot;
  1649. ImGuiIO& IO = ImGui::GetIO();
  1650. // BUTTON STATE -----------------------------------------------------------
  1651. const ImGuiButtonFlags plot_button_flags = ImGuiButtonFlags_AllowOverlap
  1652. | ImGuiButtonFlags_PressedOnClick
  1653. | ImGuiButtonFlags_PressedOnDoubleClick
  1654. | ImGuiButtonFlags_MouseButtonLeft
  1655. | ImGuiButtonFlags_MouseButtonRight
  1656. | ImGuiButtonFlags_MouseButtonMiddle;
  1657. const ImGuiButtonFlags axis_button_flags = ImGuiButtonFlags_FlattenChildren
  1658. | plot_button_flags;
  1659. const bool plot_clicked = ImGui::ButtonBehavior(plot.PlotRect,plot.ID,&plot.Hovered,&plot.Held,plot_button_flags);
  1660. #if (IMGUI_VERSION_NUM < 18966)
  1661. ImGui::SetItemAllowOverlap(); // Handled by ButtonBehavior()
  1662. #endif
  1663. if (plot_clicked) {
  1664. if (!ImHasFlag(plot.Flags, ImPlotFlags_NoBoxSelect) && IO.MouseClicked[gp.InputMap.Select] && ImHasFlag(IO.KeyMods, gp.InputMap.SelectMod)) {
  1665. plot.Selecting = true;
  1666. plot.SelectStart = IO.MousePos;
  1667. plot.SelectRect = ImRect(0,0,0,0);
  1668. }
  1669. if (IO.MouseDoubleClicked[gp.InputMap.Fit]) {
  1670. plot.FitThisFrame = true;
  1671. for (int i = 0; i < ImAxis_COUNT; ++i)
  1672. plot.Axes[i].FitThisFrame = true;
  1673. }
  1674. }
  1675. const bool can_pan = IO.MouseDown[gp.InputMap.Pan] && ImHasFlag(IO.KeyMods, gp.InputMap.PanMod);
  1676. plot.Held = plot.Held && can_pan;
  1677. bool x_click[IMPLOT_NUM_X_AXES] = {false};
  1678. bool x_held[IMPLOT_NUM_X_AXES] = {false};
  1679. bool x_hov[IMPLOT_NUM_X_AXES] = {false};
  1680. bool y_click[IMPLOT_NUM_Y_AXES] = {false};
  1681. bool y_held[IMPLOT_NUM_Y_AXES] = {false};
  1682. bool y_hov[IMPLOT_NUM_Y_AXES] = {false};
  1683. for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i) {
  1684. ImPlotAxis& xax = plot.XAxis(i);
  1685. if (xax.Enabled) {
  1686. ImGui::KeepAliveID(xax.ID);
  1687. x_click[i] = ImGui::ButtonBehavior(xax.HoverRect,xax.ID,&xax.Hovered,&xax.Held,axis_button_flags);
  1688. if (x_click[i] && IO.MouseDoubleClicked[gp.InputMap.Fit])
  1689. plot.FitThisFrame = xax.FitThisFrame = true;
  1690. xax.Held = xax.Held && can_pan;
  1691. x_hov[i] = xax.Hovered || plot.Hovered;
  1692. x_held[i] = xax.Held || plot.Held;
  1693. }
  1694. }
  1695. for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i) {
  1696. ImPlotAxis& yax = plot.YAxis(i);
  1697. if (yax.Enabled) {
  1698. ImGui::KeepAliveID(yax.ID);
  1699. y_click[i] = ImGui::ButtonBehavior(yax.HoverRect,yax.ID,&yax.Hovered,&yax.Held,axis_button_flags);
  1700. if (y_click[i] && IO.MouseDoubleClicked[gp.InputMap.Fit])
  1701. plot.FitThisFrame = yax.FitThisFrame = true;
  1702. yax.Held = yax.Held && can_pan;
  1703. y_hov[i] = yax.Hovered || plot.Hovered;
  1704. y_held[i] = yax.Held || plot.Held;
  1705. }
  1706. }
  1707. // cancel due to DND activity
  1708. if (GImGui->DragDropActive || (IO.KeyMods == gp.InputMap.OverrideMod && gp.InputMap.OverrideMod != 0))
  1709. return false;
  1710. // STATE -------------------------------------------------------------------
  1711. const bool axis_equal = ImHasFlag(plot.Flags, ImPlotFlags_Equal);
  1712. const bool any_x_hov = plot.Hovered || AnyAxesHovered(&plot.Axes[ImAxis_X1], IMPLOT_NUM_X_AXES);
  1713. const bool any_x_held = plot.Held || AnyAxesHeld(&plot.Axes[ImAxis_X1], IMPLOT_NUM_X_AXES);
  1714. const bool any_y_hov = plot.Hovered || AnyAxesHovered(&plot.Axes[ImAxis_Y1], IMPLOT_NUM_Y_AXES);
  1715. const bool any_y_held = plot.Held || AnyAxesHeld(&plot.Axes[ImAxis_Y1], IMPLOT_NUM_Y_AXES);
  1716. const bool any_hov = any_x_hov || any_y_hov;
  1717. const bool any_held = any_x_held || any_y_held;
  1718. const ImVec2 select_drag = ImGui::GetMouseDragDelta(gp.InputMap.Select);
  1719. const ImVec2 pan_drag = ImGui::GetMouseDragDelta(gp.InputMap.Pan);
  1720. const float select_drag_sq = ImLengthSqr(select_drag);
  1721. const float pan_drag_sq = ImLengthSqr(pan_drag);
  1722. const bool selecting = plot.Selecting && select_drag_sq > MOUSE_CURSOR_DRAG_THRESHOLD;
  1723. const bool panning = any_held && pan_drag_sq > MOUSE_CURSOR_DRAG_THRESHOLD;
  1724. // CONTEXT MENU -----------------------------------------------------------
  1725. if (IO.MouseReleased[gp.InputMap.Menu] && !plot.ContextLocked)
  1726. gp.OpenContextThisFrame = true;
  1727. if (selecting || panning)
  1728. plot.ContextLocked = true;
  1729. else if (!(IO.MouseDown[gp.InputMap.Menu] || IO.MouseReleased[gp.InputMap.Menu]))
  1730. plot.ContextLocked = false;
  1731. // DRAG INPUT -------------------------------------------------------------
  1732. if (any_held && !plot.Selecting) {
  1733. int drag_direction = 0;
  1734. for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {
  1735. ImPlotAxis& x_axis = plot.XAxis(i);
  1736. if (x_held[i] && !x_axis.IsInputLocked()) {
  1737. drag_direction |= (1 << 1);
  1738. bool increasing = x_axis.IsInverted() ? IO.MouseDelta.x > 0 : IO.MouseDelta.x < 0;
  1739. if (IO.MouseDelta.x != 0 && !x_axis.IsPanLocked(increasing)) {
  1740. const double plot_l = x_axis.PixelsToPlot(plot.PlotRect.Min.x - IO.MouseDelta.x);
  1741. const double plot_r = x_axis.PixelsToPlot(plot.PlotRect.Max.x - IO.MouseDelta.x);
  1742. x_axis.SetMin(x_axis.IsInverted() ? plot_r : plot_l);
  1743. x_axis.SetMax(x_axis.IsInverted() ? plot_l : plot_r);
  1744. if (axis_equal && x_axis.OrthoAxis != nullptr)
  1745. x_axis.OrthoAxis->SetAspect(x_axis.GetAspect());
  1746. changed = true;
  1747. }
  1748. }
  1749. }
  1750. for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {
  1751. ImPlotAxis& y_axis = plot.YAxis(i);
  1752. if (y_held[i] && !y_axis.IsInputLocked()) {
  1753. drag_direction |= (1 << 2);
  1754. bool increasing = y_axis.IsInverted() ? IO.MouseDelta.y < 0 : IO.MouseDelta.y > 0;
  1755. if (IO.MouseDelta.y != 0 && !y_axis.IsPanLocked(increasing)) {
  1756. const double plot_t = y_axis.PixelsToPlot(plot.PlotRect.Min.y - IO.MouseDelta.y);
  1757. const double plot_b = y_axis.PixelsToPlot(plot.PlotRect.Max.y - IO.MouseDelta.y);
  1758. y_axis.SetMin(y_axis.IsInverted() ? plot_t : plot_b);
  1759. y_axis.SetMax(y_axis.IsInverted() ? plot_b : plot_t);
  1760. if (axis_equal && y_axis.OrthoAxis != nullptr)
  1761. y_axis.OrthoAxis->SetAspect(y_axis.GetAspect());
  1762. changed = true;
  1763. }
  1764. }
  1765. }
  1766. if (IO.MouseDragMaxDistanceSqr[gp.InputMap.Pan] > MOUSE_CURSOR_DRAG_THRESHOLD) {
  1767. switch (drag_direction) {
  1768. case 0 : ImGui::SetMouseCursor(ImGuiMouseCursor_NotAllowed); break;
  1769. case (1 << 1) : ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW); break;
  1770. case (1 << 2) : ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS); break;
  1771. default : ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeAll); break;
  1772. }
  1773. }
  1774. }
  1775. // SCROLL INPUT -----------------------------------------------------------
  1776. if (any_hov && IO.MouseWheel != 0 && ImHasFlag(IO.KeyMods, gp.InputMap.ZoomMod)) {
  1777. float zoom_rate = gp.InputMap.ZoomRate;
  1778. if (IO.MouseWheel > 0)
  1779. zoom_rate = (-zoom_rate) / (1.0f + (2.0f * zoom_rate));
  1780. ImVec2 rect_size = plot.PlotRect.GetSize();
  1781. float tx = ImRemap(IO.MousePos.x, plot.PlotRect.Min.x, plot.PlotRect.Max.x, 0.0f, 1.0f);
  1782. float ty = ImRemap(IO.MousePos.y, plot.PlotRect.Min.y, plot.PlotRect.Max.y, 0.0f, 1.0f);
  1783. for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {
  1784. ImPlotAxis& x_axis = plot.XAxis(i);
  1785. const bool equal_zoom = axis_equal && x_axis.OrthoAxis != nullptr;
  1786. const bool equal_locked = (equal_zoom != false) && x_axis.OrthoAxis->IsInputLocked();
  1787. if (x_hov[i] && !x_axis.IsInputLocked() && !equal_locked) {
  1788. float correction = (plot.Hovered && equal_zoom) ? 0.5f : 1.0f;
  1789. const double plot_l = x_axis.PixelsToPlot(plot.PlotRect.Min.x - rect_size.x * tx * zoom_rate * correction);
  1790. const double plot_r = x_axis.PixelsToPlot(plot.PlotRect.Max.x + rect_size.x * (1 - tx) * zoom_rate * correction);
  1791. x_axis.SetMin(x_axis.IsInverted() ? plot_r : plot_l);
  1792. x_axis.SetMax(x_axis.IsInverted() ? plot_l : plot_r);
  1793. if (axis_equal && x_axis.OrthoAxis != nullptr)
  1794. x_axis.OrthoAxis->SetAspect(x_axis.GetAspect());
  1795. changed = true;
  1796. }
  1797. }
  1798. for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {
  1799. ImPlotAxis& y_axis = plot.YAxis(i);
  1800. const bool equal_zoom = axis_equal && y_axis.OrthoAxis != nullptr;
  1801. const bool equal_locked = equal_zoom && y_axis.OrthoAxis->IsInputLocked();
  1802. if (y_hov[i] && !y_axis.IsInputLocked() && !equal_locked) {
  1803. float correction = (plot.Hovered && equal_zoom) ? 0.5f : 1.0f;
  1804. const double plot_t = y_axis.PixelsToPlot(plot.PlotRect.Min.y - rect_size.y * ty * zoom_rate * correction);
  1805. const double plot_b = y_axis.PixelsToPlot(plot.PlotRect.Max.y + rect_size.y * (1 - ty) * zoom_rate * correction);
  1806. y_axis.SetMin(y_axis.IsInverted() ? plot_t : plot_b);
  1807. y_axis.SetMax(y_axis.IsInverted() ? plot_b : plot_t);
  1808. if (axis_equal && y_axis.OrthoAxis != nullptr)
  1809. y_axis.OrthoAxis->SetAspect(y_axis.GetAspect());
  1810. changed = true;
  1811. }
  1812. }
  1813. }
  1814. // BOX-SELECTION ----------------------------------------------------------
  1815. if (plot.Selecting) {
  1816. const ImVec2 d = plot.SelectStart - IO.MousePos;
  1817. const bool x_can_change = !ImHasFlag(IO.KeyMods,gp.InputMap.SelectHorzMod) && ImFabs(d.x) > 2;
  1818. const bool y_can_change = !ImHasFlag(IO.KeyMods,gp.InputMap.SelectVertMod) && ImFabs(d.y) > 2;
  1819. // confirm
  1820. if (IO.MouseReleased[gp.InputMap.Select]) {
  1821. for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {
  1822. ImPlotAxis& x_axis = plot.XAxis(i);
  1823. if (!x_axis.IsInputLocked() && x_can_change) {
  1824. const double p1 = x_axis.PixelsToPlot(plot.SelectStart.x);
  1825. const double p2 = x_axis.PixelsToPlot(IO.MousePos.x);
  1826. x_axis.SetMin(ImMin(p1, p2));
  1827. x_axis.SetMax(ImMax(p1, p2));
  1828. changed = true;
  1829. }
  1830. }
  1831. for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {
  1832. ImPlotAxis& y_axis = plot.YAxis(i);
  1833. if (!y_axis.IsInputLocked() && y_can_change) {
  1834. const double p1 = y_axis.PixelsToPlot(plot.SelectStart.y);
  1835. const double p2 = y_axis.PixelsToPlot(IO.MousePos.y);
  1836. y_axis.SetMin(ImMin(p1, p2));
  1837. y_axis.SetMax(ImMax(p1, p2));
  1838. changed = true;
  1839. }
  1840. }
  1841. if (x_can_change || y_can_change || (ImHasFlag(IO.KeyMods,gp.InputMap.SelectHorzMod) && ImHasFlag(IO.KeyMods,gp.InputMap.SelectVertMod)))
  1842. gp.OpenContextThisFrame = false;
  1843. plot.Selected = plot.Selecting = false;
  1844. }
  1845. // cancel
  1846. else if (IO.MouseReleased[gp.InputMap.SelectCancel]) {
  1847. plot.Selected = plot.Selecting = false;
  1848. gp.OpenContextThisFrame = false;
  1849. }
  1850. else if (ImLengthSqr(d) > BOX_SELECT_DRAG_THRESHOLD) {
  1851. // bad selection
  1852. if (plot.IsInputLocked()) {
  1853. ImGui::SetMouseCursor(ImGuiMouseCursor_NotAllowed);
  1854. gp.OpenContextThisFrame = false;
  1855. plot.Selected = false;
  1856. }
  1857. else {
  1858. // TODO: Handle only min or max locked cases
  1859. const bool full_width = ImHasFlag(IO.KeyMods, gp.InputMap.SelectHorzMod) || AllAxesInputLocked(&plot.Axes[ImAxis_X1], IMPLOT_NUM_X_AXES);
  1860. const bool full_height = ImHasFlag(IO.KeyMods, gp.InputMap.SelectVertMod) || AllAxesInputLocked(&plot.Axes[ImAxis_Y1], IMPLOT_NUM_Y_AXES);
  1861. plot.SelectRect.Min.x = full_width ? plot.PlotRect.Min.x : ImMin(plot.SelectStart.x, IO.MousePos.x);
  1862. plot.SelectRect.Max.x = full_width ? plot.PlotRect.Max.x : ImMax(plot.SelectStart.x, IO.MousePos.x);
  1863. plot.SelectRect.Min.y = full_height ? plot.PlotRect.Min.y : ImMin(plot.SelectStart.y, IO.MousePos.y);
  1864. plot.SelectRect.Max.y = full_height ? plot.PlotRect.Max.y : ImMax(plot.SelectStart.y, IO.MousePos.y);
  1865. plot.SelectRect.Min -= plot.PlotRect.Min;
  1866. plot.SelectRect.Max -= plot.PlotRect.Min;
  1867. plot.Selected = true;
  1868. }
  1869. }
  1870. else {
  1871. plot.Selected = false;
  1872. }
  1873. }
  1874. return changed;
  1875. }
  1876. //-----------------------------------------------------------------------------
  1877. // Next Plot Data (Legacy)
  1878. //-----------------------------------------------------------------------------
  1879. void ApplyNextPlotData(ImAxis idx) {
  1880. ImPlotContext& gp = *GImPlot;
  1881. ImPlotPlot& plot = *gp.CurrentPlot;
  1882. ImPlotAxis& axis = plot.Axes[idx];
  1883. if (!axis.Enabled)
  1884. return;
  1885. double* npd_lmin = gp.NextPlotData.LinkedMin[idx];
  1886. double* npd_lmax = gp.NextPlotData.LinkedMax[idx];
  1887. bool npd_rngh = gp.NextPlotData.HasRange[idx];
  1888. ImPlotCond npd_rngc = gp.NextPlotData.RangeCond[idx];
  1889. ImPlotRange npd_rngv = gp.NextPlotData.Range[idx];
  1890. axis.LinkedMin = npd_lmin;
  1891. axis.LinkedMax = npd_lmax;
  1892. axis.PullLinks();
  1893. if (npd_rngh) {
  1894. if (!plot.Initialized || npd_rngc == ImPlotCond_Always)
  1895. axis.SetRange(npd_rngv);
  1896. }
  1897. axis.HasRange = npd_rngh;
  1898. axis.RangeCond = npd_rngc;
  1899. }
  1900. //-----------------------------------------------------------------------------
  1901. // Setup
  1902. //-----------------------------------------------------------------------------
  1903. void SetupAxis(ImAxis idx, const char* label, ImPlotAxisFlags flags) {
  1904. ImPlotContext& gp = *GImPlot;
  1905. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  1906. "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
  1907. // get plot and axis
  1908. ImPlotPlot& plot = *gp.CurrentPlot;
  1909. ImPlotAxis& axis = plot.Axes[idx];
  1910. // set ID
  1911. axis.ID = plot.ID + idx + 1;
  1912. // check and set flags
  1913. if (plot.JustCreated || flags != axis.PreviousFlags)
  1914. axis.Flags = flags;
  1915. axis.PreviousFlags = flags;
  1916. // enable axis
  1917. axis.Enabled = true;
  1918. // set label
  1919. plot.SetAxisLabel(axis,label);
  1920. // cache colors
  1921. UpdateAxisColors(axis);
  1922. }
  1923. void SetupAxisLimits(ImAxis idx, double min_lim, double max_lim, ImPlotCond cond) {
  1924. ImPlotContext& gp = *GImPlot;
  1925. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  1926. "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); // get plot and axis
  1927. ImPlotPlot& plot = *gp.CurrentPlot;
  1928. ImPlotAxis& axis = plot.Axes[idx];
  1929. IM_ASSERT_USER_ERROR(axis.Enabled, "Axis is not enabled! Did you forget to call SetupAxis()?");
  1930. if (!plot.Initialized || cond == ImPlotCond_Always)
  1931. axis.SetRange(min_lim, max_lim);
  1932. axis.HasRange = true;
  1933. axis.RangeCond = cond;
  1934. }
  1935. void SetupAxisFormat(ImAxis idx, const char* fmt) {
  1936. ImPlotContext& gp = *GImPlot;
  1937. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  1938. "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
  1939. ImPlotPlot& plot = *gp.CurrentPlot;
  1940. ImPlotAxis& axis = plot.Axes[idx];
  1941. IM_ASSERT_USER_ERROR(axis.Enabled, "Axis is not enabled! Did you forget to call SetupAxis()?");
  1942. axis.HasFormatSpec = fmt != nullptr;
  1943. if (fmt != nullptr)
  1944. ImStrncpy(axis.FormatSpec,fmt,sizeof(axis.FormatSpec));
  1945. }
  1946. void SetupAxisLinks(ImAxis idx, double* min_lnk, double* max_lnk) {
  1947. ImPlotContext& gp = *GImPlot;
  1948. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  1949. "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
  1950. ImPlotPlot& plot = *gp.CurrentPlot;
  1951. ImPlotAxis& axis = plot.Axes[idx];
  1952. IM_ASSERT_USER_ERROR(axis.Enabled, "Axis is not enabled! Did you forget to call SetupAxis()?");
  1953. axis.LinkedMin = min_lnk;
  1954. axis.LinkedMax = max_lnk;
  1955. axis.PullLinks();
  1956. }
  1957. void SetupAxisFormat(ImAxis idx, ImPlotFormatter formatter, void* data) {
  1958. ImPlotContext& gp = *GImPlot;
  1959. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  1960. "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
  1961. ImPlotPlot& plot = *gp.CurrentPlot;
  1962. ImPlotAxis& axis = plot.Axes[idx];
  1963. IM_ASSERT_USER_ERROR(axis.Enabled, "Axis is not enabled! Did you forget to call SetupAxis()?");
  1964. axis.Formatter = formatter;
  1965. axis.FormatterData = data;
  1966. }
  1967. void SetupAxisTicks(ImAxis idx, const double* values, int n_ticks, const char* const labels[], bool show_default) {
  1968. ImPlotContext& gp = *GImPlot;
  1969. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  1970. "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
  1971. ImPlotPlot& plot = *gp.CurrentPlot;
  1972. ImPlotAxis& axis = plot.Axes[idx];
  1973. IM_ASSERT_USER_ERROR(axis.Enabled, "Axis is not enabled! Did you forget to call SetupAxis()?");
  1974. axis.ShowDefaultTicks = show_default;
  1975. AddTicksCustom(values,
  1976. labels,
  1977. n_ticks,
  1978. axis.Ticker,
  1979. axis.Formatter ? axis.Formatter : Formatter_Default,
  1980. (axis.Formatter && axis.FormatterData) ? axis.FormatterData : axis.HasFormatSpec ? axis.FormatSpec : (void*)IMPLOT_LABEL_FORMAT);
  1981. }
  1982. void SetupAxisTicks(ImAxis idx, double v_min, double v_max, int n_ticks, const char* const labels[], bool show_default) {
  1983. ImPlotContext& gp = *GImPlot;
  1984. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  1985. "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
  1986. n_ticks = n_ticks < 2 ? 2 : n_ticks;
  1987. FillRange(gp.TempDouble1, n_ticks, v_min, v_max);
  1988. SetupAxisTicks(idx, gp.TempDouble1.Data, n_ticks, labels, show_default);
  1989. }
  1990. void SetupAxisScale(ImAxis idx, ImPlotScale scale) {
  1991. ImPlotContext& gp = *GImPlot;
  1992. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  1993. "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
  1994. ImPlotPlot& plot = *gp.CurrentPlot;
  1995. ImPlotAxis& axis = plot.Axes[idx];
  1996. IM_ASSERT_USER_ERROR(axis.Enabled, "Axis is not enabled! Did you forget to call SetupAxis()?");
  1997. axis.Scale = scale;
  1998. switch (scale)
  1999. {
  2000. case ImPlotScale_Time:
  2001. axis.TransformForward = nullptr;
  2002. axis.TransformInverse = nullptr;
  2003. axis.TransformData = nullptr;
  2004. axis.Locator = Locator_Time;
  2005. axis.ConstraintRange = ImPlotRange(IMPLOT_MIN_TIME, IMPLOT_MAX_TIME);
  2006. axis.Ticker.Levels = 2;
  2007. break;
  2008. case ImPlotScale_Log10:
  2009. axis.TransformForward = TransformForward_Log10;
  2010. axis.TransformInverse = TransformInverse_Log10;
  2011. axis.TransformData = nullptr;
  2012. axis.Locator = Locator_Log10;
  2013. axis.ConstraintRange = ImPlotRange(DBL_MIN, INFINITY);
  2014. break;
  2015. case ImPlotScale_SymLog:
  2016. axis.TransformForward = TransformForward_SymLog;
  2017. axis.TransformInverse = TransformInverse_SymLog;
  2018. axis.TransformData = nullptr;
  2019. axis.Locator = Locator_SymLog;
  2020. axis.ConstraintRange = ImPlotRange(-INFINITY, INFINITY);
  2021. break;
  2022. default:
  2023. axis.TransformForward = nullptr;
  2024. axis.TransformInverse = nullptr;
  2025. axis.TransformData = nullptr;
  2026. axis.Locator = nullptr;
  2027. axis.ConstraintRange = ImPlotRange(-INFINITY, INFINITY);
  2028. break;
  2029. }
  2030. }
  2031. void SetupAxisScale(ImAxis idx, ImPlotTransform fwd, ImPlotTransform inv, void* data) {
  2032. ImPlotContext& gp = *GImPlot;
  2033. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  2034. "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
  2035. ImPlotPlot& plot = *gp.CurrentPlot;
  2036. ImPlotAxis& axis = plot.Axes[idx];
  2037. IM_ASSERT_USER_ERROR(axis.Enabled, "Axis is not enabled! Did you forget to call SetupAxis()?");
  2038. axis.Scale = IMPLOT_AUTO;
  2039. axis.TransformForward = fwd;
  2040. axis.TransformInverse = inv;
  2041. axis.TransformData = data;
  2042. }
  2043. void SetupAxisLimitsConstraints(ImAxis idx, double v_min, double v_max) {
  2044. ImPlotContext& gp = *GImPlot;
  2045. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  2046. "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
  2047. ImPlotPlot& plot = *gp.CurrentPlot;
  2048. ImPlotAxis& axis = plot.Axes[idx];
  2049. IM_ASSERT_USER_ERROR(axis.Enabled, "Axis is not enabled! Did you forget to call SetupAxis()?");
  2050. axis.ConstraintRange.Min = v_min;
  2051. axis.ConstraintRange.Max = v_max;
  2052. }
  2053. void SetupAxisZoomConstraints(ImAxis idx, double z_min, double z_max) {
  2054. ImPlotContext& gp = *GImPlot;
  2055. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  2056. "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
  2057. ImPlotPlot& plot = *gp.CurrentPlot;
  2058. ImPlotAxis& axis = plot.Axes[idx];
  2059. IM_ASSERT_USER_ERROR(axis.Enabled, "Axis is not enabled! Did you forget to call SetupAxis()?");
  2060. axis.ConstraintZoom.Min = z_min;
  2061. axis.ConstraintZoom.Max = z_max;
  2062. }
  2063. void SetupAxes(const char* x_label, const char* y_label, ImPlotAxisFlags x_flags, ImPlotAxisFlags y_flags) {
  2064. SetupAxis(ImAxis_X1, x_label, x_flags);
  2065. SetupAxis(ImAxis_Y1, y_label, y_flags);
  2066. }
  2067. void SetupAxesLimits(double x_min, double x_max, double y_min, double y_max, ImPlotCond cond) {
  2068. SetupAxisLimits(ImAxis_X1, x_min, x_max, cond);
  2069. SetupAxisLimits(ImAxis_Y1, y_min, y_max, cond);
  2070. }
  2071. void SetupLegend(ImPlotLocation location, ImPlotLegendFlags flags) {
  2072. ImPlotContext& gp = *GImPlot;
  2073. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  2074. "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
  2075. IM_ASSERT_USER_ERROR(gp.CurrentItems != nullptr,
  2076. "SetupLegend() needs to be called within an itemized context!");
  2077. ImPlotLegend& legend = gp.CurrentItems->Legend;
  2078. // check and set location
  2079. if (location != legend.PreviousLocation)
  2080. legend.Location = location;
  2081. legend.PreviousLocation = location;
  2082. // check and set flags
  2083. if (flags != legend.PreviousFlags)
  2084. legend.Flags = flags;
  2085. legend.PreviousFlags = flags;
  2086. }
  2087. void SetupMouseText(ImPlotLocation location, ImPlotMouseTextFlags flags) {
  2088. ImPlotContext& gp = *GImPlot;
  2089. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked,
  2090. "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!");
  2091. gp.CurrentPlot->MouseTextLocation = location;
  2092. gp.CurrentPlot->MouseTextFlags = flags;
  2093. }
  2094. //-----------------------------------------------------------------------------
  2095. // SetNext
  2096. //-----------------------------------------------------------------------------
  2097. void SetNextAxisLimits(ImAxis axis, double v_min, double v_max, ImPlotCond cond) {
  2098. ImPlotContext& gp = *GImPlot;
  2099. IM_ASSERT_USER_ERROR(gp.CurrentPlot == nullptr, "SetNextAxisLimits() needs to be called before BeginPlot()!");
  2100. IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
  2101. gp.NextPlotData.HasRange[axis] = true;
  2102. gp.NextPlotData.RangeCond[axis] = cond;
  2103. gp.NextPlotData.Range[axis].Min = v_min;
  2104. gp.NextPlotData.Range[axis].Max = v_max;
  2105. }
  2106. void SetNextAxisLinks(ImAxis axis, double* link_min, double* link_max) {
  2107. ImPlotContext& gp = *GImPlot;
  2108. IM_ASSERT_USER_ERROR(gp.CurrentPlot == nullptr, "SetNextAxisLinks() needs to be called before BeginPlot()!");
  2109. gp.NextPlotData.LinkedMin[axis] = link_min;
  2110. gp.NextPlotData.LinkedMax[axis] = link_max;
  2111. }
  2112. void SetNextAxisToFit(ImAxis axis) {
  2113. ImPlotContext& gp = *GImPlot;
  2114. IM_ASSERT_USER_ERROR(gp.CurrentPlot == nullptr, "SetNextAxisToFit() needs to be called before BeginPlot()!");
  2115. gp.NextPlotData.Fit[axis] = true;
  2116. }
  2117. void SetNextAxesLimits(double x_min, double x_max, double y_min, double y_max, ImPlotCond cond) {
  2118. SetNextAxisLimits(ImAxis_X1, x_min, x_max, cond);
  2119. SetNextAxisLimits(ImAxis_Y1, y_min, y_max, cond);
  2120. }
  2121. void SetNextAxesToFit() {
  2122. for (int i = 0; i < ImAxis_COUNT; ++i)
  2123. SetNextAxisToFit(i);
  2124. }
  2125. //-----------------------------------------------------------------------------
  2126. // BeginPlot
  2127. //-----------------------------------------------------------------------------
  2128. bool BeginPlot(const char* title_id, const ImVec2& size, ImPlotFlags flags) {
  2129. IM_ASSERT_USER_ERROR(GImPlot != nullptr, "No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?");
  2130. ImPlotContext& gp = *GImPlot;
  2131. IM_ASSERT_USER_ERROR(gp.CurrentPlot == nullptr, "Mismatched BeginPlot()/EndPlot()!");
  2132. // FRONT MATTER -----------------------------------------------------------
  2133. if (gp.CurrentSubplot != nullptr)
  2134. ImGui::PushID(gp.CurrentSubplot->CurrentIdx);
  2135. // get globals
  2136. ImGuiContext &G = *GImGui;
  2137. ImGuiWindow* Window = G.CurrentWindow;
  2138. // skip if needed
  2139. if (Window->SkipItems && !gp.CurrentSubplot) {
  2140. ResetCtxForNextPlot(GImPlot);
  2141. return false;
  2142. }
  2143. // ID and age (TODO: keep track of plot age in frames)
  2144. const ImGuiID ID = Window->GetID(title_id);
  2145. const bool just_created = gp.Plots.GetByKey(ID) == nullptr;
  2146. gp.CurrentPlot = gp.Plots.GetOrAddByKey(ID);
  2147. ImPlotPlot &plot = *gp.CurrentPlot;
  2148. plot.ID = ID;
  2149. plot.Items.ID = ID - 1;
  2150. plot.JustCreated = just_created;
  2151. plot.SetupLocked = false;
  2152. // check flags
  2153. if (plot.JustCreated)
  2154. plot.Flags = flags;
  2155. else if (flags != plot.PreviousFlags)
  2156. plot.Flags = flags;
  2157. plot.PreviousFlags = flags;
  2158. // setup default axes
  2159. if (plot.JustCreated) {
  2160. SetupAxis(ImAxis_X1);
  2161. SetupAxis(ImAxis_Y1);
  2162. }
  2163. // reset axes
  2164. for (int i = 0; i < ImAxis_COUNT; ++i) {
  2165. plot.Axes[i].Reset();
  2166. UpdateAxisColors(plot.Axes[i]);
  2167. }
  2168. // ensure first axes enabled
  2169. plot.Axes[ImAxis_X1].Enabled = true;
  2170. plot.Axes[ImAxis_Y1].Enabled = true;
  2171. // set initial axes
  2172. plot.CurrentX = ImAxis_X1;
  2173. plot.CurrentY = ImAxis_Y1;
  2174. // process next plot data (legacy)
  2175. for (int i = 0; i < ImAxis_COUNT; ++i)
  2176. ApplyNextPlotData(i);
  2177. // capture scroll with a child region
  2178. if (!ImHasFlag(plot.Flags, ImPlotFlags_NoChild)) {
  2179. ImVec2 child_size;
  2180. if (gp.CurrentSubplot != nullptr)
  2181. child_size = gp.CurrentSubplot->CellSize;
  2182. else
  2183. child_size = ImVec2(size.x == 0 ? gp.Style.PlotDefaultSize.x : size.x, size.y == 0 ? gp.Style.PlotDefaultSize.y : size.y);
  2184. ImGui::BeginChild(title_id, child_size, false, ImGuiWindowFlags_NoScrollbar);
  2185. Window = ImGui::GetCurrentWindow();
  2186. Window->ScrollMax.y = 1.0f;
  2187. gp.ChildWindowMade = true;
  2188. }
  2189. else {
  2190. gp.ChildWindowMade = false;
  2191. }
  2192. // clear text buffers
  2193. plot.ClearTextBuffer();
  2194. plot.SetTitle(title_id);
  2195. // set frame size
  2196. ImVec2 frame_size;
  2197. if (gp.CurrentSubplot != nullptr)
  2198. frame_size = gp.CurrentSubplot->CellSize;
  2199. else
  2200. frame_size = ImGui::CalcItemSize(size, gp.Style.PlotDefaultSize.x, gp.Style.PlotDefaultSize.y);
  2201. if (frame_size.x < gp.Style.PlotMinSize.x && (size.x < 0.0f || gp.CurrentSubplot != nullptr))
  2202. frame_size.x = gp.Style.PlotMinSize.x;
  2203. if (frame_size.y < gp.Style.PlotMinSize.y && (size.y < 0.0f || gp.CurrentSubplot != nullptr))
  2204. frame_size.y = gp.Style.PlotMinSize.y;
  2205. plot.FrameRect = ImRect(Window->DC.CursorPos, Window->DC.CursorPos + frame_size);
  2206. ImGui::ItemSize(plot.FrameRect);
  2207. if (!ImGui::ItemAdd(plot.FrameRect, plot.ID, &plot.FrameRect) && !gp.CurrentSubplot) {
  2208. ResetCtxForNextPlot(GImPlot);
  2209. return false;
  2210. }
  2211. // setup items (or dont)
  2212. if (gp.CurrentItems == nullptr)
  2213. gp.CurrentItems = &plot.Items;
  2214. return true;
  2215. }
  2216. //-----------------------------------------------------------------------------
  2217. // SetupFinish
  2218. //-----------------------------------------------------------------------------
  2219. void SetupFinish() {
  2220. IM_ASSERT_USER_ERROR(GImPlot != nullptr, "No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?");
  2221. ImPlotContext& gp = *GImPlot;
  2222. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "SetupFinish needs to be called after BeginPlot!");
  2223. ImGuiContext& G = *GImGui;
  2224. ImDrawList& DrawList = *G.CurrentWindow->DrawList;
  2225. const ImGuiStyle& Style = G.Style;
  2226. ImPlotPlot &plot = *gp.CurrentPlot;
  2227. // lock setup
  2228. plot.SetupLocked = true;
  2229. // finalize axes and set default formatter/locator
  2230. for (int i = 0; i < ImAxis_COUNT; ++i) {
  2231. ImPlotAxis& axis = plot.Axes[i];
  2232. if (axis.Enabled) {
  2233. axis.Constrain();
  2234. if (!plot.Initialized && axis.CanInitFit())
  2235. plot.FitThisFrame = axis.FitThisFrame = true;
  2236. }
  2237. if (axis.Formatter == nullptr) {
  2238. axis.Formatter = Formatter_Default;
  2239. if (axis.HasFormatSpec)
  2240. axis.FormatterData = axis.FormatSpec;
  2241. else
  2242. axis.FormatterData = (void*)IMPLOT_LABEL_FORMAT;
  2243. }
  2244. if (axis.Locator == nullptr) {
  2245. axis.Locator = Locator_Default;
  2246. }
  2247. }
  2248. // setup nullptr orthogonal axes
  2249. const bool axis_equal = ImHasFlag(plot.Flags, ImPlotFlags_Equal);
  2250. for (int ix = ImAxis_X1, iy = ImAxis_Y1; ix < ImAxis_Y1 || iy < ImAxis_COUNT; ++ix, ++iy) {
  2251. ImPlotAxis& x_axis = plot.Axes[ix];
  2252. ImPlotAxis& y_axis = plot.Axes[iy];
  2253. if (x_axis.Enabled && y_axis.Enabled) {
  2254. if (x_axis.OrthoAxis == nullptr)
  2255. x_axis.OrthoAxis = &y_axis;
  2256. if (y_axis.OrthoAxis == nullptr)
  2257. y_axis.OrthoAxis = &x_axis;
  2258. }
  2259. else if (x_axis.Enabled)
  2260. {
  2261. if (x_axis.OrthoAxis == nullptr && !axis_equal)
  2262. x_axis.OrthoAxis = &plot.Axes[ImAxis_Y1];
  2263. }
  2264. else if (y_axis.Enabled) {
  2265. if (y_axis.OrthoAxis == nullptr && !axis_equal)
  2266. y_axis.OrthoAxis = &plot.Axes[ImAxis_X1];
  2267. }
  2268. }
  2269. // canvas/axes bb
  2270. plot.CanvasRect = ImRect(plot.FrameRect.Min + gp.Style.PlotPadding, plot.FrameRect.Max - gp.Style.PlotPadding);
  2271. plot.AxesRect = plot.FrameRect;
  2272. // outside legend adjustments
  2273. if (!ImHasFlag(plot.Flags, ImPlotFlags_NoLegend) && plot.Items.GetLegendCount() > 0 && ImHasFlag(plot.Items.Legend.Flags, ImPlotLegendFlags_Outside)) {
  2274. ImPlotLegend& legend = plot.Items.Legend;
  2275. const bool horz = ImHasFlag(legend.Flags, ImPlotLegendFlags_Horizontal);
  2276. const ImVec2 legend_size = CalcLegendSize(plot.Items, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !horz);
  2277. const bool west = ImHasFlag(legend.Location, ImPlotLocation_West) && !ImHasFlag(legend.Location, ImPlotLocation_East);
  2278. const bool east = ImHasFlag(legend.Location, ImPlotLocation_East) && !ImHasFlag(legend.Location, ImPlotLocation_West);
  2279. const bool north = ImHasFlag(legend.Location, ImPlotLocation_North) && !ImHasFlag(legend.Location, ImPlotLocation_South);
  2280. const bool south = ImHasFlag(legend.Location, ImPlotLocation_South) && !ImHasFlag(legend.Location, ImPlotLocation_North);
  2281. if ((west && !horz) || (west && horz && !north && !south)) {
  2282. plot.CanvasRect.Min.x += (legend_size.x + gp.Style.LegendPadding.x);
  2283. plot.AxesRect.Min.x += (legend_size.x + gp.Style.PlotPadding.x);
  2284. }
  2285. if ((east && !horz) || (east && horz && !north && !south)) {
  2286. plot.CanvasRect.Max.x -= (legend_size.x + gp.Style.LegendPadding.x);
  2287. plot.AxesRect.Max.x -= (legend_size.x + gp.Style.PlotPadding.x);
  2288. }
  2289. if ((north && horz) || (north && !horz && !west && !east)) {
  2290. plot.CanvasRect.Min.y += (legend_size.y + gp.Style.LegendPadding.y);
  2291. plot.AxesRect.Min.y += (legend_size.y + gp.Style.PlotPadding.y);
  2292. }
  2293. if ((south && horz) || (south && !horz && !west && !east)) {
  2294. plot.CanvasRect.Max.y -= (legend_size.y + gp.Style.LegendPadding.y);
  2295. plot.AxesRect.Max.y -= (legend_size.y + gp.Style.PlotPadding.y);
  2296. }
  2297. }
  2298. // plot bb
  2299. float pad_top = 0, pad_bot = 0, pad_left = 0, pad_right = 0;
  2300. // (0) calc top padding form title
  2301. ImVec2 title_size(0.0f, 0.0f);
  2302. if (plot.HasTitle())
  2303. title_size = ImGui::CalcTextSize(plot.GetTitle(), nullptr, true);
  2304. if (title_size.x > 0) {
  2305. pad_top += title_size.y + gp.Style.LabelPadding.y;
  2306. plot.AxesRect.Min.y += gp.Style.PlotPadding.y + pad_top;
  2307. }
  2308. // (1) calc addition top padding and bot padding
  2309. PadAndDatumAxesX(plot,pad_top,pad_bot,gp.CurrentAlignmentH);
  2310. const float plot_height = plot.CanvasRect.GetHeight() - pad_top - pad_bot;
  2311. // (2) get y tick labels (needed for left/right pad)
  2312. for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {
  2313. ImPlotAxis& axis = plot.YAxis(i);
  2314. if (axis.WillRender() && axis.ShowDefaultTicks && plot_height > 0) {
  2315. axis.Locator(axis.Ticker, axis.Range, plot_height, true, axis.Formatter, axis.FormatterData);
  2316. }
  2317. }
  2318. // (3) calc left/right pad
  2319. PadAndDatumAxesY(plot,pad_left,pad_right,gp.CurrentAlignmentV);
  2320. const float plot_width = plot.CanvasRect.GetWidth() - pad_left - pad_right;
  2321. // (4) get x ticks
  2322. for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {
  2323. ImPlotAxis& axis = plot.XAxis(i);
  2324. if (axis.WillRender() && axis.ShowDefaultTicks && plot_width > 0) {
  2325. axis.Locator(axis.Ticker, axis.Range, plot_width, false, axis.Formatter, axis.FormatterData);
  2326. }
  2327. }
  2328. // (5) calc plot bb
  2329. plot.PlotRect = ImRect(plot.CanvasRect.Min + ImVec2(pad_left, pad_top), plot.CanvasRect.Max - ImVec2(pad_right, pad_bot));
  2330. // HOVER------------------------------------------------------------
  2331. // axes hover rect, pixel ranges
  2332. for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i) {
  2333. ImPlotAxis& xax = plot.XAxis(i);
  2334. xax.HoverRect = ImRect(ImVec2(plot.PlotRect.Min.x, ImMin(xax.Datum1,xax.Datum2)),
  2335. ImVec2(plot.PlotRect.Max.x, ImMax(xax.Datum1,xax.Datum2)));
  2336. xax.PixelMin = xax.IsInverted() ? plot.PlotRect.Max.x : plot.PlotRect.Min.x;
  2337. xax.PixelMax = xax.IsInverted() ? plot.PlotRect.Min.x : plot.PlotRect.Max.x;
  2338. xax.UpdateTransformCache();
  2339. }
  2340. for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i) {
  2341. ImPlotAxis& yax = plot.YAxis(i);
  2342. yax.HoverRect = ImRect(ImVec2(ImMin(yax.Datum1,yax.Datum2),plot.PlotRect.Min.y),
  2343. ImVec2(ImMax(yax.Datum1,yax.Datum2),plot.PlotRect.Max.y));
  2344. yax.PixelMin = yax.IsInverted() ? plot.PlotRect.Min.y : plot.PlotRect.Max.y;
  2345. yax.PixelMax = yax.IsInverted() ? plot.PlotRect.Max.y : plot.PlotRect.Min.y;
  2346. yax.UpdateTransformCache();
  2347. }
  2348. // Equal axis constraint. Must happen after we set Pixels
  2349. // constrain equal axes for primary x and y if not approximately equal
  2350. // constrains x to y since x pixel size depends on y labels width, and causes feedback loops in opposite case
  2351. if (axis_equal) {
  2352. for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i) {
  2353. ImPlotAxis& x_axis = plot.XAxis(i);
  2354. if (x_axis.OrthoAxis == nullptr)
  2355. continue;
  2356. double xar = x_axis.GetAspect();
  2357. double yar = x_axis.OrthoAxis->GetAspect();
  2358. // edge case: user has set x range this frame, so fit y to x so that we honor their request for x range
  2359. // NB: because of feedback across several frames, the user's x request may not be perfectly honored
  2360. if (x_axis.HasRange)
  2361. x_axis.OrthoAxis->SetAspect(xar);
  2362. else if (!ImAlmostEqual(xar,yar) && !x_axis.OrthoAxis->IsInputLocked())
  2363. x_axis.SetAspect(yar);
  2364. }
  2365. }
  2366. // INPUT ------------------------------------------------------------------
  2367. if (!ImHasFlag(plot.Flags, ImPlotFlags_NoInputs))
  2368. UpdateInput(plot);
  2369. // fit from FitNextPlotAxes or auto fit
  2370. for (int i = 0; i < ImAxis_COUNT; ++i) {
  2371. if (gp.NextPlotData.Fit[i] || plot.Axes[i].IsAutoFitting()) {
  2372. plot.FitThisFrame = true;
  2373. plot.Axes[i].FitThisFrame = true;
  2374. }
  2375. }
  2376. // RENDER -----------------------------------------------------------------
  2377. const float txt_height = ImGui::GetTextLineHeight();
  2378. // render frame
  2379. if (!ImHasFlag(plot.Flags, ImPlotFlags_NoFrame))
  2380. ImGui::RenderFrame(plot.FrameRect.Min, plot.FrameRect.Max, GetStyleColorU32(ImPlotCol_FrameBg), true, Style.FrameRounding);
  2381. // grid bg
  2382. DrawList.AddRectFilled(plot.PlotRect.Min, plot.PlotRect.Max, GetStyleColorU32(ImPlotCol_PlotBg));
  2383. // transform ticks
  2384. for (int i = 0; i < ImAxis_COUNT; i++) {
  2385. ImPlotAxis& axis = plot.Axes[i];
  2386. if (axis.WillRender()) {
  2387. for (int t = 0; t < axis.Ticker.TickCount(); t++) {
  2388. ImPlotTick& tk = axis.Ticker.Ticks[t];
  2389. tk.PixelPos = IM_ROUND(axis.PlotToPixels(tk.PlotPos));
  2390. }
  2391. }
  2392. }
  2393. // render grid (background)
  2394. for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {
  2395. ImPlotAxis& x_axis = plot.XAxis(i);
  2396. if (x_axis.Enabled && x_axis.HasGridLines() && !x_axis.IsForeground())
  2397. RenderGridLinesX(DrawList, x_axis.Ticker, plot.PlotRect, x_axis.ColorMaj, x_axis.ColorMin, gp.Style.MajorGridSize.x, gp.Style.MinorGridSize.x);
  2398. }
  2399. for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {
  2400. ImPlotAxis& y_axis = plot.YAxis(i);
  2401. if (y_axis.Enabled && y_axis.HasGridLines() && !y_axis.IsForeground())
  2402. RenderGridLinesY(DrawList, y_axis.Ticker, plot.PlotRect, y_axis.ColorMaj, y_axis.ColorMin, gp.Style.MajorGridSize.y, gp.Style.MinorGridSize.y);
  2403. }
  2404. // render x axis button, label, tick labels
  2405. for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {
  2406. ImPlotAxis& ax = plot.XAxis(i);
  2407. if (!ax.Enabled)
  2408. continue;
  2409. if ((ax.Hovered || ax.Held) && !plot.Held && !ImHasFlag(ax.Flags, ImPlotAxisFlags_NoHighlight))
  2410. DrawList.AddRectFilled(ax.HoverRect.Min, ax.HoverRect.Max, ax.Held ? ax.ColorAct : ax.ColorHov);
  2411. else if (ax.ColorHiLi != IM_COL32_BLACK_TRANS) {
  2412. DrawList.AddRectFilled(ax.HoverRect.Min, ax.HoverRect.Max, ax.ColorHiLi);
  2413. ax.ColorHiLi = IM_COL32_BLACK_TRANS;
  2414. }
  2415. else if (ax.ColorBg != IM_COL32_BLACK_TRANS) {
  2416. DrawList.AddRectFilled(ax.HoverRect.Min, ax.HoverRect.Max, ax.ColorBg);
  2417. }
  2418. const ImPlotTicker& tkr = ax.Ticker;
  2419. const bool opp = ax.IsOpposite();
  2420. if (ax.HasLabel()) {
  2421. const char* label = plot.GetAxisLabel(ax);
  2422. const ImVec2 label_size = ImGui::CalcTextSize(label);
  2423. const float label_offset = (ax.HasTickLabels() ? tkr.MaxSize.y + gp.Style.LabelPadding.y : 0.0f)
  2424. + (tkr.Levels - 1) * (txt_height + gp.Style.LabelPadding.y)
  2425. + gp.Style.LabelPadding.y;
  2426. const ImVec2 label_pos(plot.PlotRect.GetCenter().x - label_size.x * 0.5f,
  2427. opp ? ax.Datum1 - label_offset - label_size.y : ax.Datum1 + label_offset);
  2428. DrawList.AddText(label_pos, ax.ColorTxt, label);
  2429. }
  2430. if (ax.HasTickLabels()) {
  2431. for (int j = 0; j < tkr.TickCount(); ++j) {
  2432. const ImPlotTick& tk = tkr.Ticks[j];
  2433. const float datum = ax.Datum1 + (opp ? (-gp.Style.LabelPadding.y -txt_height -tk.Level * (txt_height + gp.Style.LabelPadding.y))
  2434. : gp.Style.LabelPadding.y + tk.Level * (txt_height + gp.Style.LabelPadding.y));
  2435. if (tk.ShowLabel && tk.PixelPos >= plot.PlotRect.Min.x - 1 && tk.PixelPos <= plot.PlotRect.Max.x + 1) {
  2436. ImVec2 start(tk.PixelPos - 0.5f * tk.LabelSize.x, datum);
  2437. DrawList.AddText(start, ax.ColorTxt, tkr.GetText(j));
  2438. }
  2439. }
  2440. }
  2441. }
  2442. // render y axis button, label, tick labels
  2443. for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {
  2444. ImPlotAxis& ax = plot.YAxis(i);
  2445. if (!ax.Enabled)
  2446. continue;
  2447. if ((ax.Hovered || ax.Held) && !plot.Held && !ImHasFlag(ax.Flags, ImPlotAxisFlags_NoHighlight))
  2448. DrawList.AddRectFilled(ax.HoverRect.Min, ax.HoverRect.Max, ax.Held ? ax.ColorAct : ax.ColorHov);
  2449. else if (ax.ColorHiLi != IM_COL32_BLACK_TRANS) {
  2450. DrawList.AddRectFilled(ax.HoverRect.Min, ax.HoverRect.Max, ax.ColorHiLi);
  2451. ax.ColorHiLi = IM_COL32_BLACK_TRANS;
  2452. }
  2453. else if (ax.ColorBg != IM_COL32_BLACK_TRANS) {
  2454. DrawList.AddRectFilled(ax.HoverRect.Min, ax.HoverRect.Max, ax.ColorBg);
  2455. }
  2456. const ImPlotTicker& tkr = ax.Ticker;
  2457. const bool opp = ax.IsOpposite();
  2458. if (ax.HasLabel()) {
  2459. const char* label = plot.GetAxisLabel(ax);
  2460. const ImVec2 label_size = CalcTextSizeVertical(label);
  2461. const float label_offset = (ax.HasTickLabels() ? tkr.MaxSize.x + gp.Style.LabelPadding.x : 0.0f)
  2462. + gp.Style.LabelPadding.x;
  2463. const ImVec2 label_pos(opp ? ax.Datum1 + label_offset : ax.Datum1 - label_offset - label_size.x,
  2464. plot.PlotRect.GetCenter().y + label_size.y * 0.5f);
  2465. AddTextVertical(&DrawList, label_pos, ax.ColorTxt, label);
  2466. }
  2467. if (ax.HasTickLabels()) {
  2468. for (int j = 0; j < tkr.TickCount(); ++j) {
  2469. const ImPlotTick& tk = tkr.Ticks[j];
  2470. const float datum = ax.Datum1 + (opp ? gp.Style.LabelPadding.x : (-gp.Style.LabelPadding.x - tk.LabelSize.x));
  2471. if (tk.ShowLabel && tk.PixelPos >= plot.PlotRect.Min.y - 1 && tk.PixelPos <= plot.PlotRect.Max.y + 1) {
  2472. ImVec2 start(datum, tk.PixelPos - 0.5f * tk.LabelSize.y);
  2473. DrawList.AddText(start, ax.ColorTxt, tkr.GetText(j));
  2474. }
  2475. }
  2476. }
  2477. }
  2478. // clear legend (TODO: put elsewhere)
  2479. plot.Items.Legend.Reset();
  2480. // push ID to set item hashes (NB: !!!THIS PROBABLY NEEDS TO BE IN BEGIN PLOT!!!!)
  2481. ImGui::PushOverrideID(gp.CurrentItems->ID);
  2482. }
  2483. //-----------------------------------------------------------------------------
  2484. // EndPlot()
  2485. //-----------------------------------------------------------------------------
  2486. void EndPlot() {
  2487. IM_ASSERT_USER_ERROR(GImPlot != nullptr, "No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?");
  2488. ImPlotContext& gp = *GImPlot;
  2489. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "Mismatched BeginPlot()/EndPlot()!");
  2490. SetupLock();
  2491. ImGuiContext &G = *GImGui;
  2492. ImPlotPlot &plot = *gp.CurrentPlot;
  2493. ImGuiWindow * Window = G.CurrentWindow;
  2494. ImDrawList & DrawList = *Window->DrawList;
  2495. const ImGuiIO & IO = ImGui::GetIO();
  2496. // FINAL RENDER -----------------------------------------------------------
  2497. const bool render_border = gp.Style.PlotBorderSize > 0 && gp.Style.Colors[ImPlotCol_PlotBorder].w > 0;
  2498. const bool any_x_held = plot.Held || AnyAxesHeld(&plot.Axes[ImAxis_X1], IMPLOT_NUM_X_AXES);
  2499. const bool any_y_held = plot.Held || AnyAxesHeld(&plot.Axes[ImAxis_Y1], IMPLOT_NUM_Y_AXES);
  2500. ImGui::PushClipRect(plot.FrameRect.Min, plot.FrameRect.Max, true);
  2501. // render grid (foreground)
  2502. for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {
  2503. ImPlotAxis& x_axis = plot.XAxis(i);
  2504. if (x_axis.Enabled && x_axis.HasGridLines() && x_axis.IsForeground())
  2505. RenderGridLinesX(DrawList, x_axis.Ticker, plot.PlotRect, x_axis.ColorMaj, x_axis.ColorMin, gp.Style.MajorGridSize.x, gp.Style.MinorGridSize.x);
  2506. }
  2507. for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {
  2508. ImPlotAxis& y_axis = plot.YAxis(i);
  2509. if (y_axis.Enabled && y_axis.HasGridLines() && y_axis.IsForeground())
  2510. RenderGridLinesY(DrawList, y_axis.Ticker, plot.PlotRect, y_axis.ColorMaj, y_axis.ColorMin, gp.Style.MajorGridSize.y, gp.Style.MinorGridSize.y);
  2511. }
  2512. // render title
  2513. if (plot.HasTitle()) {
  2514. ImU32 col = GetStyleColorU32(ImPlotCol_TitleText);
  2515. AddTextCentered(&DrawList,ImVec2(plot.PlotRect.GetCenter().x, plot.CanvasRect.Min.y),col,plot.GetTitle());
  2516. }
  2517. // render x ticks
  2518. int count_B = 0, count_T = 0;
  2519. for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {
  2520. const ImPlotAxis& ax = plot.XAxis(i);
  2521. if (!ax.Enabled)
  2522. continue;
  2523. const ImPlotTicker& tkr = ax.Ticker;
  2524. const bool opp = ax.IsOpposite();
  2525. const bool aux = ((opp && count_T > 0)||(!opp && count_B > 0));
  2526. if (ax.HasTickMarks()) {
  2527. const float direction = opp ? 1.0f : -1.0f;
  2528. for (int j = 0; j < tkr.TickCount(); ++j) {
  2529. const ImPlotTick& tk = tkr.Ticks[j];
  2530. if (tk.Level != 0 || tk.PixelPos < plot.PlotRect.Min.x || tk.PixelPos > plot.PlotRect.Max.x)
  2531. continue;
  2532. const ImVec2 start(tk.PixelPos, ax.Datum1);
  2533. const float len = (!aux && tk.Major) ? gp.Style.MajorTickLen.x : gp.Style.MinorTickLen.x;
  2534. const float thk = (!aux && tk.Major) ? gp.Style.MajorTickSize.x : gp.Style.MinorTickSize.x;
  2535. DrawList.AddLine(start, start + ImVec2(0,direction*len), ax.ColorTick, thk);
  2536. }
  2537. if (aux || !render_border)
  2538. DrawList.AddLine(ImVec2(plot.PlotRect.Min.x,ax.Datum1), ImVec2(plot.PlotRect.Max.x,ax.Datum1), ax.ColorTick, gp.Style.MinorTickSize.x);
  2539. }
  2540. count_B += !opp;
  2541. count_T += opp;
  2542. }
  2543. // render y ticks
  2544. int count_L = 0, count_R = 0;
  2545. for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {
  2546. const ImPlotAxis& ax = plot.YAxis(i);
  2547. if (!ax.Enabled)
  2548. continue;
  2549. const ImPlotTicker& tkr = ax.Ticker;
  2550. const bool opp = ax.IsOpposite();
  2551. const bool aux = ((opp && count_R > 0)||(!opp && count_L > 0));
  2552. if (ax.HasTickMarks()) {
  2553. const float direction = opp ? -1.0f : 1.0f;
  2554. for (int j = 0; j < tkr.TickCount(); ++j) {
  2555. const ImPlotTick& tk = tkr.Ticks[j];
  2556. if (tk.Level != 0 || tk.PixelPos < plot.PlotRect.Min.y || tk.PixelPos > plot.PlotRect.Max.y)
  2557. continue;
  2558. const ImVec2 start(ax.Datum1, tk.PixelPos);
  2559. const float len = (!aux && tk.Major) ? gp.Style.MajorTickLen.y : gp.Style.MinorTickLen.y;
  2560. const float thk = (!aux && tk.Major) ? gp.Style.MajorTickSize.y : gp.Style.MinorTickSize.y;
  2561. DrawList.AddLine(start, start + ImVec2(direction*len,0), ax.ColorTick, thk);
  2562. }
  2563. if (aux || !render_border)
  2564. DrawList.AddLine(ImVec2(ax.Datum1, plot.PlotRect.Min.y), ImVec2(ax.Datum1, plot.PlotRect.Max.y), ax.ColorTick, gp.Style.MinorTickSize.y);
  2565. }
  2566. count_L += !opp;
  2567. count_R += opp;
  2568. }
  2569. ImGui::PopClipRect();
  2570. // render annotations
  2571. PushPlotClipRect();
  2572. for (int i = 0; i < gp.Annotations.Size; ++i) {
  2573. const char* txt = gp.Annotations.GetText(i);
  2574. ImPlotAnnotation& an = gp.Annotations.Annotations[i];
  2575. const ImVec2 txt_size = ImGui::CalcTextSize(txt);
  2576. const ImVec2 size = txt_size + gp.Style.AnnotationPadding * 2;
  2577. ImVec2 pos = an.Pos;
  2578. if (an.Offset.x == 0)
  2579. pos.x -= size.x / 2;
  2580. else if (an.Offset.x > 0)
  2581. pos.x += an.Offset.x;
  2582. else
  2583. pos.x -= size.x - an.Offset.x;
  2584. if (an.Offset.y == 0)
  2585. pos.y -= size.y / 2;
  2586. else if (an.Offset.y > 0)
  2587. pos.y += an.Offset.y;
  2588. else
  2589. pos.y -= size.y - an.Offset.y;
  2590. if (an.Clamp)
  2591. pos = ClampLabelPos(pos, size, plot.PlotRect.Min, plot.PlotRect.Max);
  2592. ImRect rect(pos,pos+size);
  2593. if (an.Offset.x != 0 || an.Offset.y != 0) {
  2594. ImVec2 corners[4] = {rect.GetTL(), rect.GetTR(), rect.GetBR(), rect.GetBL()};
  2595. int min_corner = 0;
  2596. float min_len = FLT_MAX;
  2597. for (int c = 0; c < 4; ++c) {
  2598. float len = ImLengthSqr(an.Pos - corners[c]);
  2599. if (len < min_len) {
  2600. min_corner = c;
  2601. min_len = len;
  2602. }
  2603. }
  2604. DrawList.AddLine(an.Pos, corners[min_corner], an.ColorBg);
  2605. }
  2606. DrawList.AddRectFilled(rect.Min, rect.Max, an.ColorBg);
  2607. DrawList.AddText(pos + gp.Style.AnnotationPadding, an.ColorFg, txt);
  2608. }
  2609. // render selection
  2610. if (plot.Selected)
  2611. RenderSelectionRect(DrawList, plot.SelectRect.Min + plot.PlotRect.Min, plot.SelectRect.Max + plot.PlotRect.Min, GetStyleColorVec4(ImPlotCol_Selection));
  2612. // render crosshairs
  2613. if (ImHasFlag(plot.Flags, ImPlotFlags_Crosshairs) && plot.Hovered && !(any_x_held || any_y_held) && !plot.Selecting && !plot.Items.Legend.Hovered) {
  2614. ImGui::SetMouseCursor(ImGuiMouseCursor_None);
  2615. ImVec2 xy = IO.MousePos;
  2616. ImVec2 h1(plot.PlotRect.Min.x, xy.y);
  2617. ImVec2 h2(xy.x - 5, xy.y);
  2618. ImVec2 h3(xy.x + 5, xy.y);
  2619. ImVec2 h4(plot.PlotRect.Max.x, xy.y);
  2620. ImVec2 v1(xy.x, plot.PlotRect.Min.y);
  2621. ImVec2 v2(xy.x, xy.y - 5);
  2622. ImVec2 v3(xy.x, xy.y + 5);
  2623. ImVec2 v4(xy.x, plot.PlotRect.Max.y);
  2624. ImU32 col = GetStyleColorU32(ImPlotCol_Crosshairs);
  2625. DrawList.AddLine(h1, h2, col);
  2626. DrawList.AddLine(h3, h4, col);
  2627. DrawList.AddLine(v1, v2, col);
  2628. DrawList.AddLine(v3, v4, col);
  2629. }
  2630. // render mouse pos
  2631. if (!ImHasFlag(plot.Flags, ImPlotFlags_NoMouseText) && (plot.Hovered || ImHasFlag(plot.MouseTextFlags, ImPlotMouseTextFlags_ShowAlways))) {
  2632. const bool no_aux = ImHasFlag(plot.MouseTextFlags, ImPlotMouseTextFlags_NoAuxAxes);
  2633. const bool no_fmt = ImHasFlag(plot.MouseTextFlags, ImPlotMouseTextFlags_NoFormat);
  2634. ImGuiTextBuffer& builder = gp.MousePosStringBuilder;
  2635. builder.Buf.shrink(0);
  2636. char buff[IMPLOT_LABEL_MAX_SIZE];
  2637. const int num_x = no_aux ? 1 : IMPLOT_NUM_X_AXES;
  2638. for (int i = 0; i < num_x; ++i) {
  2639. ImPlotAxis& x_axis = plot.XAxis(i);
  2640. if (!x_axis.Enabled)
  2641. continue;
  2642. if (i > 0)
  2643. builder.append(", (");
  2644. double v = x_axis.PixelsToPlot(IO.MousePos.x);
  2645. if (no_fmt)
  2646. Formatter_Default(v,buff,IMPLOT_LABEL_MAX_SIZE,(void*)IMPLOT_LABEL_FORMAT);
  2647. else
  2648. LabelAxisValue(x_axis,v,buff,IMPLOT_LABEL_MAX_SIZE,true);
  2649. builder.append(buff);
  2650. if (i > 0)
  2651. builder.append(")");
  2652. }
  2653. builder.append(", ");
  2654. const int num_y = no_aux ? 1 : IMPLOT_NUM_Y_AXES;
  2655. for (int i = 0; i < num_y; ++i) {
  2656. ImPlotAxis& y_axis = plot.YAxis(i);
  2657. if (!y_axis.Enabled)
  2658. continue;
  2659. if (i > 0)
  2660. builder.append(", (");
  2661. double v = y_axis.PixelsToPlot(IO.MousePos.y);
  2662. if (no_fmt)
  2663. Formatter_Default(v,buff,IMPLOT_LABEL_MAX_SIZE,(void*)IMPLOT_LABEL_FORMAT);
  2664. else
  2665. LabelAxisValue(y_axis,v,buff,IMPLOT_LABEL_MAX_SIZE,true);
  2666. builder.append(buff);
  2667. if (i > 0)
  2668. builder.append(")");
  2669. }
  2670. if (!builder.empty()) {
  2671. const ImVec2 size = ImGui::CalcTextSize(builder.c_str());
  2672. const ImVec2 pos = GetLocationPos(plot.PlotRect, size, plot.MouseTextLocation, gp.Style.MousePosPadding);
  2673. DrawList.AddText(pos, GetStyleColorU32(ImPlotCol_InlayText), builder.c_str());
  2674. }
  2675. }
  2676. PopPlotClipRect();
  2677. // axis side switch
  2678. if (!plot.Held) {
  2679. ImVec2 mouse_pos = ImGui::GetIO().MousePos;
  2680. ImRect trigger_rect = plot.PlotRect;
  2681. trigger_rect.Expand(-10);
  2682. for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i) {
  2683. ImPlotAxis& x_axis = plot.XAxis(i);
  2684. if (ImHasFlag(x_axis.Flags, ImPlotAxisFlags_NoSideSwitch))
  2685. continue;
  2686. if (x_axis.Held && plot.PlotRect.Contains(mouse_pos)) {
  2687. const bool opp = ImHasFlag(x_axis.Flags, ImPlotAxisFlags_Opposite);
  2688. if (!opp) {
  2689. ImRect rect(plot.PlotRect.Min.x - 5, plot.PlotRect.Min.y - 5,
  2690. plot.PlotRect.Max.x + 5, plot.PlotRect.Min.y + 5);
  2691. if (mouse_pos.y < plot.PlotRect.Max.y - 10)
  2692. DrawList.AddRectFilled(rect.Min, rect.Max, x_axis.ColorHov);
  2693. if (rect.Contains(mouse_pos))
  2694. x_axis.Flags |= ImPlotAxisFlags_Opposite;
  2695. }
  2696. else {
  2697. ImRect rect(plot.PlotRect.Min.x - 5, plot.PlotRect.Max.y - 5,
  2698. plot.PlotRect.Max.x + 5, plot.PlotRect.Max.y + 5);
  2699. if (mouse_pos.y > plot.PlotRect.Min.y + 10)
  2700. DrawList.AddRectFilled(rect.Min, rect.Max, x_axis.ColorHov);
  2701. if (rect.Contains(mouse_pos))
  2702. x_axis.Flags &= ~ImPlotAxisFlags_Opposite;
  2703. }
  2704. }
  2705. }
  2706. for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i) {
  2707. ImPlotAxis& y_axis = plot.YAxis(i);
  2708. if (ImHasFlag(y_axis.Flags, ImPlotAxisFlags_NoSideSwitch))
  2709. continue;
  2710. if (y_axis.Held && plot.PlotRect.Contains(mouse_pos)) {
  2711. const bool opp = ImHasFlag(y_axis.Flags, ImPlotAxisFlags_Opposite);
  2712. if (!opp) {
  2713. ImRect rect(plot.PlotRect.Max.x - 5, plot.PlotRect.Min.y - 5,
  2714. plot.PlotRect.Max.x + 5, plot.PlotRect.Max.y + 5);
  2715. if (mouse_pos.x > plot.PlotRect.Min.x + 10)
  2716. DrawList.AddRectFilled(rect.Min, rect.Max, y_axis.ColorHov);
  2717. if (rect.Contains(mouse_pos))
  2718. y_axis.Flags |= ImPlotAxisFlags_Opposite;
  2719. }
  2720. else {
  2721. ImRect rect(plot.PlotRect.Min.x - 5, plot.PlotRect.Min.y - 5,
  2722. plot.PlotRect.Min.x + 5, plot.PlotRect.Max.y + 5);
  2723. if (mouse_pos.x < plot.PlotRect.Max.x - 10)
  2724. DrawList.AddRectFilled(rect.Min, rect.Max, y_axis.ColorHov);
  2725. if (rect.Contains(mouse_pos))
  2726. y_axis.Flags &= ~ImPlotAxisFlags_Opposite;
  2727. }
  2728. }
  2729. }
  2730. }
  2731. // reset legend hovers
  2732. plot.Items.Legend.Hovered = false;
  2733. for (int i = 0; i < plot.Items.GetItemCount(); ++i)
  2734. plot.Items.GetItemByIndex(i)->LegendHovered = false;
  2735. // render legend
  2736. if (!ImHasFlag(plot.Flags, ImPlotFlags_NoLegend) && plot.Items.GetLegendCount() > 0) {
  2737. ImPlotLegend& legend = plot.Items.Legend;
  2738. const bool legend_out = ImHasFlag(legend.Flags, ImPlotLegendFlags_Outside);
  2739. const bool legend_horz = ImHasFlag(legend.Flags, ImPlotLegendFlags_Horizontal);
  2740. const ImVec2 legend_size = CalcLegendSize(plot.Items, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !legend_horz);
  2741. const ImVec2 legend_pos = GetLocationPos(legend_out ? plot.FrameRect : plot.PlotRect,
  2742. legend_size,
  2743. legend.Location,
  2744. legend_out ? gp.Style.PlotPadding : gp.Style.LegendPadding);
  2745. legend.Rect = ImRect(legend_pos, legend_pos + legend_size);
  2746. // test hover
  2747. legend.Hovered = ImGui::IsWindowHovered() && legend.Rect.Contains(IO.MousePos);
  2748. if (legend_out)
  2749. ImGui::PushClipRect(plot.FrameRect.Min, plot.FrameRect.Max, true);
  2750. else
  2751. PushPlotClipRect();
  2752. ImU32 col_bg = GetStyleColorU32(ImPlotCol_LegendBg);
  2753. ImU32 col_bd = GetStyleColorU32(ImPlotCol_LegendBorder);
  2754. DrawList.AddRectFilled(legend.Rect.Min, legend.Rect.Max, col_bg);
  2755. DrawList.AddRect(legend.Rect.Min, legend.Rect.Max, col_bd);
  2756. bool legend_contextable = ShowLegendEntries(plot.Items, legend.Rect, legend.Hovered, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !legend_horz, DrawList)
  2757. && !ImHasFlag(legend.Flags, ImPlotLegendFlags_NoMenus);
  2758. // main ctx menu
  2759. if (gp.OpenContextThisFrame && legend_contextable && !ImHasFlag(plot.Flags, ImPlotFlags_NoMenus))
  2760. ImGui::OpenPopup("##LegendContext");
  2761. ImGui::PopClipRect();
  2762. if (ImGui::BeginPopup("##LegendContext")) {
  2763. ImGui::Text("Legend"); ImGui::Separator();
  2764. if (ShowLegendContextMenu(legend, !ImHasFlag(plot.Flags, ImPlotFlags_NoLegend)))
  2765. ImFlipFlag(plot.Flags, ImPlotFlags_NoLegend);
  2766. ImGui::EndPopup();
  2767. }
  2768. }
  2769. else {
  2770. plot.Items.Legend.Rect = ImRect();
  2771. }
  2772. // render border
  2773. if (render_border)
  2774. DrawList.AddRect(plot.PlotRect.Min, plot.PlotRect.Max, GetStyleColorU32(ImPlotCol_PlotBorder), 0, ImDrawFlags_RoundCornersAll, gp.Style.PlotBorderSize);
  2775. // render tags
  2776. for (int i = 0; i < gp.Tags.Size; ++i) {
  2777. ImPlotTag& tag = gp.Tags.Tags[i];
  2778. ImPlotAxis& axis = plot.Axes[tag.Axis];
  2779. if (!axis.Enabled || !axis.Range.Contains(tag.Value))
  2780. continue;
  2781. const char* txt = gp.Tags.GetText(i);
  2782. ImVec2 text_size = ImGui::CalcTextSize(txt);
  2783. ImVec2 size = text_size + gp.Style.AnnotationPadding * 2;
  2784. ImVec2 pos;
  2785. axis.Ticker.OverrideSizeLate(size);
  2786. float pix = IM_ROUND(axis.PlotToPixels(tag.Value));
  2787. if (axis.Vertical) {
  2788. if (axis.IsOpposite()) {
  2789. pos = ImVec2(axis.Datum1 + gp.Style.LabelPadding.x, pix - size.y * 0.5f);
  2790. DrawList.AddTriangleFilled(ImVec2(axis.Datum1,pix), pos, pos + ImVec2(0,size.y), tag.ColorBg);
  2791. }
  2792. else {
  2793. pos = ImVec2(axis.Datum1 - size.x - gp.Style.LabelPadding.x, pix - size.y * 0.5f);
  2794. DrawList.AddTriangleFilled(pos + ImVec2(size.x,0), ImVec2(axis.Datum1,pix), pos+size, tag.ColorBg);
  2795. }
  2796. }
  2797. else {
  2798. if (axis.IsOpposite()) {
  2799. pos = ImVec2(pix - size.x * 0.5f, axis.Datum1 - size.y - gp.Style.LabelPadding.y );
  2800. DrawList.AddTriangleFilled(pos + ImVec2(0,size.y), pos + size, ImVec2(pix,axis.Datum1), tag.ColorBg);
  2801. }
  2802. else {
  2803. pos = ImVec2(pix - size.x * 0.5f, axis.Datum1 + gp.Style.LabelPadding.y);
  2804. DrawList.AddTriangleFilled(pos, ImVec2(pix,axis.Datum1), pos + ImVec2(size.x, 0), tag.ColorBg);
  2805. }
  2806. }
  2807. DrawList.AddRectFilled(pos,pos+size,tag.ColorBg);
  2808. DrawList.AddText(pos+gp.Style.AnnotationPadding,tag.ColorFg,txt);
  2809. }
  2810. // FIT DATA --------------------------------------------------------------
  2811. const bool axis_equal = ImHasFlag(plot.Flags, ImPlotFlags_Equal);
  2812. if (plot.FitThisFrame) {
  2813. for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {
  2814. ImPlotAxis& x_axis = plot.XAxis(i);
  2815. if (x_axis.FitThisFrame) {
  2816. x_axis.ApplyFit(gp.Style.FitPadding.x);
  2817. if (axis_equal && x_axis.OrthoAxis != nullptr) {
  2818. double aspect = x_axis.GetAspect();
  2819. ImPlotAxis& y_axis = *x_axis.OrthoAxis;
  2820. if (y_axis.FitThisFrame) {
  2821. y_axis.ApplyFit(gp.Style.FitPadding.y);
  2822. y_axis.FitThisFrame = false;
  2823. aspect = ImMax(aspect, y_axis.GetAspect());
  2824. }
  2825. x_axis.SetAspect(aspect);
  2826. y_axis.SetAspect(aspect);
  2827. }
  2828. }
  2829. }
  2830. for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {
  2831. ImPlotAxis& y_axis = plot.YAxis(i);
  2832. if (y_axis.FitThisFrame) {
  2833. y_axis.ApplyFit(gp.Style.FitPadding.y);
  2834. if (axis_equal && y_axis.OrthoAxis != nullptr) {
  2835. double aspect = y_axis.GetAspect();
  2836. ImPlotAxis& x_axis = *y_axis.OrthoAxis;
  2837. if (x_axis.FitThisFrame) {
  2838. x_axis.ApplyFit(gp.Style.FitPadding.x);
  2839. x_axis.FitThisFrame = false;
  2840. aspect = ImMax(x_axis.GetAspect(), aspect);
  2841. }
  2842. x_axis.SetAspect(aspect);
  2843. y_axis.SetAspect(aspect);
  2844. }
  2845. }
  2846. }
  2847. plot.FitThisFrame = false;
  2848. }
  2849. // CONTEXT MENUS -----------------------------------------------------------
  2850. ImGui::PushOverrideID(plot.ID);
  2851. const bool can_ctx = gp.OpenContextThisFrame &&
  2852. !ImHasFlag(plot.Flags, ImPlotFlags_NoMenus) &&
  2853. !plot.Items.Legend.Hovered;
  2854. // main ctx menu
  2855. if (can_ctx && plot.Hovered)
  2856. ImGui::OpenPopup("##PlotContext");
  2857. if (ImGui::BeginPopup("##PlotContext")) {
  2858. ShowPlotContextMenu(plot);
  2859. ImGui::EndPopup();
  2860. }
  2861. // axes ctx menus
  2862. for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i) {
  2863. ImGui::PushID(i);
  2864. ImPlotAxis& x_axis = plot.XAxis(i);
  2865. if (can_ctx && x_axis.Hovered && x_axis.HasMenus())
  2866. ImGui::OpenPopup("##XContext");
  2867. if (ImGui::BeginPopup("##XContext")) {
  2868. ImGui::Text(x_axis.HasLabel() ? plot.GetAxisLabel(x_axis) : i == 0 ? "X-Axis" : "X-Axis %d", i + 1);
  2869. ImGui::Separator();
  2870. ShowAxisContextMenu(x_axis, axis_equal ? x_axis.OrthoAxis : nullptr, true);
  2871. ImGui::EndPopup();
  2872. }
  2873. ImGui::PopID();
  2874. }
  2875. for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i) {
  2876. ImGui::PushID(i);
  2877. ImPlotAxis& y_axis = plot.YAxis(i);
  2878. if (can_ctx && y_axis.Hovered && y_axis.HasMenus())
  2879. ImGui::OpenPopup("##YContext");
  2880. if (ImGui::BeginPopup("##YContext")) {
  2881. ImGui::Text(y_axis.HasLabel() ? plot.GetAxisLabel(y_axis) : i == 0 ? "Y-Axis" : "Y-Axis %d", i + 1);
  2882. ImGui::Separator();
  2883. ShowAxisContextMenu(y_axis, axis_equal ? y_axis.OrthoAxis : nullptr, false);
  2884. ImGui::EndPopup();
  2885. }
  2886. ImGui::PopID();
  2887. }
  2888. ImGui::PopID();
  2889. // LINKED AXES ------------------------------------------------------------
  2890. for (int i = 0; i < ImAxis_COUNT; ++i)
  2891. plot.Axes[i].PushLinks();
  2892. // CLEANUP ----------------------------------------------------------------
  2893. // remove items
  2894. if (gp.CurrentItems == &plot.Items)
  2895. gp.CurrentItems = nullptr;
  2896. // reset the plot items for the next frame
  2897. for (int i = 0; i < plot.Items.GetItemCount(); ++i) {
  2898. plot.Items.GetItemByIndex(i)->SeenThisFrame = false;
  2899. }
  2900. // mark the plot as initialized, i.e. having made it through one frame completely
  2901. plot.Initialized = true;
  2902. // Pop ImGui::PushID at the end of BeginPlot
  2903. ImGui::PopID();
  2904. // Reset context for next plot
  2905. ResetCtxForNextPlot(GImPlot);
  2906. // setup next subplot
  2907. if (gp.CurrentSubplot != nullptr) {
  2908. ImGui::PopID();
  2909. SubplotNextCell();
  2910. }
  2911. }
  2912. //-----------------------------------------------------------------------------
  2913. // BEGIN/END SUBPLOT
  2914. //-----------------------------------------------------------------------------
  2915. static const float SUBPLOT_BORDER_SIZE = 1.0f;
  2916. static const float SUBPLOT_SPLITTER_HALF_THICKNESS = 4.0f;
  2917. static const float SUBPLOT_SPLITTER_FEEDBACK_TIMER = 0.06f;
  2918. void SubplotSetCell(int row, int col) {
  2919. ImPlotContext& gp = *GImPlot;
  2920. ImPlotSubplot& subplot = *gp.CurrentSubplot;
  2921. if (row >= subplot.Rows || col >= subplot.Cols)
  2922. return;
  2923. float xoff = 0;
  2924. float yoff = 0;
  2925. for (int c = 0; c < col; ++c)
  2926. xoff += subplot.ColRatios[c];
  2927. for (int r = 0; r < row; ++r)
  2928. yoff += subplot.RowRatios[r];
  2929. const ImVec2 grid_size = subplot.GridRect.GetSize();
  2930. ImVec2 cpos = subplot.GridRect.Min + ImVec2(xoff*grid_size.x,yoff*grid_size.y);
  2931. cpos.x = IM_ROUND(cpos.x);
  2932. cpos.y = IM_ROUND(cpos.y);
  2933. ImGui::GetCurrentWindow()->DC.CursorPos = cpos;
  2934. // set cell size
  2935. subplot.CellSize.x = IM_ROUND(subplot.GridRect.GetWidth() * subplot.ColRatios[col]);
  2936. subplot.CellSize.y = IM_ROUND(subplot.GridRect.GetHeight() * subplot.RowRatios[row]);
  2937. // setup links
  2938. const bool lx = ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkAllX);
  2939. const bool ly = ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkAllY);
  2940. const bool lr = ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkRows);
  2941. const bool lc = ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkCols);
  2942. SetNextAxisLinks(ImAxis_X1, lx ? &subplot.ColLinkData[0].Min : lc ? &subplot.ColLinkData[col].Min : nullptr,
  2943. lx ? &subplot.ColLinkData[0].Max : lc ? &subplot.ColLinkData[col].Max : nullptr);
  2944. SetNextAxisLinks(ImAxis_Y1, ly ? &subplot.RowLinkData[0].Min : lr ? &subplot.RowLinkData[row].Min : nullptr,
  2945. ly ? &subplot.RowLinkData[0].Max : lr ? &subplot.RowLinkData[row].Max : nullptr);
  2946. // setup alignment
  2947. if (!ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoAlign)) {
  2948. gp.CurrentAlignmentH = &subplot.RowAlignmentData[row];
  2949. gp.CurrentAlignmentV = &subplot.ColAlignmentData[col];
  2950. }
  2951. // set idx
  2952. if (ImHasFlag(subplot.Flags, ImPlotSubplotFlags_ColMajor))
  2953. subplot.CurrentIdx = col * subplot.Rows + row;
  2954. else
  2955. subplot.CurrentIdx = row * subplot.Cols + col;
  2956. }
  2957. void SubplotSetCell(int idx) {
  2958. ImPlotContext& gp = *GImPlot;
  2959. ImPlotSubplot& subplot = *gp.CurrentSubplot;
  2960. if (idx >= subplot.Rows * subplot.Cols)
  2961. return;
  2962. int row = 0, col = 0;
  2963. if (ImHasFlag(subplot.Flags, ImPlotSubplotFlags_ColMajor)) {
  2964. row = idx % subplot.Rows;
  2965. col = idx / subplot.Rows;
  2966. }
  2967. else {
  2968. row = idx / subplot.Cols;
  2969. col = idx % subplot.Cols;
  2970. }
  2971. return SubplotSetCell(row, col);
  2972. }
  2973. void SubplotNextCell() {
  2974. ImPlotContext& gp = *GImPlot;
  2975. ImPlotSubplot& subplot = *gp.CurrentSubplot;
  2976. SubplotSetCell(++subplot.CurrentIdx);
  2977. }
  2978. bool BeginSubplots(const char* title, int rows, int cols, const ImVec2& size, ImPlotSubplotFlags flags, float* row_sizes, float* col_sizes) {
  2979. IM_ASSERT_USER_ERROR(rows > 0 && cols > 0, "Invalid sizing arguments!");
  2980. IM_ASSERT_USER_ERROR(GImPlot != nullptr, "No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?");
  2981. ImPlotContext& gp = *GImPlot;
  2982. IM_ASSERT_USER_ERROR(gp.CurrentSubplot == nullptr, "Mismatched BeginSubplots()/EndSubplots()!");
  2983. ImGuiContext &G = *GImGui;
  2984. ImGuiWindow * Window = G.CurrentWindow;
  2985. if (Window->SkipItems)
  2986. return false;
  2987. const ImGuiID ID = Window->GetID(title);
  2988. bool just_created = gp.Subplots.GetByKey(ID) == nullptr;
  2989. gp.CurrentSubplot = gp.Subplots.GetOrAddByKey(ID);
  2990. ImPlotSubplot& subplot = *gp.CurrentSubplot;
  2991. subplot.ID = ID;
  2992. subplot.Items.ID = ID - 1;
  2993. subplot.HasTitle = ImGui::FindRenderedTextEnd(title, nullptr) != title;
  2994. // push ID
  2995. ImGui::PushID(ID);
  2996. if (just_created)
  2997. subplot.Flags = flags;
  2998. else if (flags != subplot.PreviousFlags)
  2999. subplot.Flags = flags;
  3000. subplot.PreviousFlags = flags;
  3001. // check for change in rows and cols
  3002. if (subplot.Rows != rows || subplot.Cols != cols) {
  3003. subplot.RowAlignmentData.resize(rows);
  3004. subplot.RowLinkData.resize(rows);
  3005. subplot.RowRatios.resize(rows);
  3006. for (int r = 0; r < rows; ++r) {
  3007. subplot.RowAlignmentData[r].Reset();
  3008. subplot.RowLinkData[r] = ImPlotRange(0,1);
  3009. subplot.RowRatios[r] = 1.0f / rows;
  3010. }
  3011. subplot.ColAlignmentData.resize(cols);
  3012. subplot.ColLinkData.resize(cols);
  3013. subplot.ColRatios.resize(cols);
  3014. for (int c = 0; c < cols; ++c) {
  3015. subplot.ColAlignmentData[c].Reset();
  3016. subplot.ColLinkData[c] = ImPlotRange(0,1);
  3017. subplot.ColRatios[c] = 1.0f / cols;
  3018. }
  3019. }
  3020. // check incoming size requests
  3021. float row_sum = 0, col_sum = 0;
  3022. if (row_sizes != nullptr) {
  3023. row_sum = ImSum(row_sizes, rows);
  3024. for (int r = 0; r < rows; ++r)
  3025. subplot.RowRatios[r] = row_sizes[r] / row_sum;
  3026. }
  3027. if (col_sizes != nullptr) {
  3028. col_sum = ImSum(col_sizes, cols);
  3029. for (int c = 0; c < cols; ++c)
  3030. subplot.ColRatios[c] = col_sizes[c] / col_sum;
  3031. }
  3032. subplot.Rows = rows;
  3033. subplot.Cols = cols;
  3034. // calc plot frame sizes
  3035. ImVec2 title_size(0.0f, 0.0f);
  3036. if (!ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoTitle))
  3037. title_size = ImGui::CalcTextSize(title, nullptr, true);
  3038. const float pad_top = title_size.x > 0.0f ? title_size.y + gp.Style.LabelPadding.y : 0;
  3039. const ImVec2 half_pad = gp.Style.PlotPadding/2;
  3040. const ImVec2 frame_size = ImGui::CalcItemSize(size, gp.Style.PlotDefaultSize.x, gp.Style.PlotDefaultSize.y);
  3041. subplot.FrameRect = ImRect(Window->DC.CursorPos, Window->DC.CursorPos + frame_size);
  3042. subplot.GridRect.Min = subplot.FrameRect.Min + half_pad + ImVec2(0,pad_top);
  3043. subplot.GridRect.Max = subplot.FrameRect.Max - half_pad;
  3044. subplot.FrameHovered = subplot.FrameRect.Contains(ImGui::GetMousePos()) && ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows|ImGuiHoveredFlags_AllowWhenBlockedByActiveItem);
  3045. // outside legend adjustments (TODO: make function)
  3046. const bool share_items = ImHasFlag(subplot.Flags, ImPlotSubplotFlags_ShareItems);
  3047. if (share_items)
  3048. gp.CurrentItems = &subplot.Items;
  3049. if (share_items && !ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoLegend) && subplot.Items.GetLegendCount() > 0) {
  3050. ImPlotLegend& legend = subplot.Items.Legend;
  3051. const bool horz = ImHasFlag(legend.Flags, ImPlotLegendFlags_Horizontal);
  3052. const ImVec2 legend_size = CalcLegendSize(subplot.Items, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !horz);
  3053. const bool west = ImHasFlag(legend.Location, ImPlotLocation_West) && !ImHasFlag(legend.Location, ImPlotLocation_East);
  3054. const bool east = ImHasFlag(legend.Location, ImPlotLocation_East) && !ImHasFlag(legend.Location, ImPlotLocation_West);
  3055. const bool north = ImHasFlag(legend.Location, ImPlotLocation_North) && !ImHasFlag(legend.Location, ImPlotLocation_South);
  3056. const bool south = ImHasFlag(legend.Location, ImPlotLocation_South) && !ImHasFlag(legend.Location, ImPlotLocation_North);
  3057. if ((west && !horz) || (west && horz && !north && !south))
  3058. subplot.GridRect.Min.x += (legend_size.x + gp.Style.LegendPadding.x);
  3059. if ((east && !horz) || (east && horz && !north && !south))
  3060. subplot.GridRect.Max.x -= (legend_size.x + gp.Style.LegendPadding.x);
  3061. if ((north && horz) || (north && !horz && !west && !east))
  3062. subplot.GridRect.Min.y += (legend_size.y + gp.Style.LegendPadding.y);
  3063. if ((south && horz) || (south && !horz && !west && !east))
  3064. subplot.GridRect.Max.y -= (legend_size.y + gp.Style.LegendPadding.y);
  3065. }
  3066. // render single background frame
  3067. ImGui::RenderFrame(subplot.FrameRect.Min, subplot.FrameRect.Max, GetStyleColorU32(ImPlotCol_FrameBg), true, ImGui::GetStyle().FrameRounding);
  3068. // render title
  3069. if (title_size.x > 0.0f && !ImHasFlag(subplot.Flags, ImPlotFlags_NoTitle)) {
  3070. const ImU32 col = GetStyleColorU32(ImPlotCol_TitleText);
  3071. AddTextCentered(ImGui::GetWindowDrawList(),ImVec2(subplot.GridRect.GetCenter().x, subplot.GridRect.Min.y - pad_top + half_pad.y),col,title);
  3072. }
  3073. // render splitters
  3074. if (!ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoResize)) {
  3075. ImDrawList& DrawList = *ImGui::GetWindowDrawList();
  3076. const ImU32 hov_col = ImGui::ColorConvertFloat4ToU32(GImGui->Style.Colors[ImGuiCol_SeparatorHovered]);
  3077. const ImU32 act_col = ImGui::ColorConvertFloat4ToU32(GImGui->Style.Colors[ImGuiCol_SeparatorActive]);
  3078. float xpos = subplot.GridRect.Min.x;
  3079. float ypos = subplot.GridRect.Min.y;
  3080. int separator = 1;
  3081. // bool pass = false;
  3082. for (int r = 0; r < subplot.Rows-1; ++r) {
  3083. ypos += subplot.RowRatios[r] * subplot.GridRect.GetHeight();
  3084. const ImGuiID sep_id = subplot.ID + separator;
  3085. ImGui::KeepAliveID(sep_id);
  3086. const ImRect sep_bb = ImRect(subplot.GridRect.Min.x, ypos-SUBPLOT_SPLITTER_HALF_THICKNESS, subplot.GridRect.Max.x, ypos+SUBPLOT_SPLITTER_HALF_THICKNESS);
  3087. bool sep_hov = false, sep_hld = false;
  3088. const bool sep_clk = ImGui::ButtonBehavior(sep_bb, sep_id, &sep_hov, &sep_hld, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick);
  3089. if ((sep_hov && G.HoveredIdTimer > SUBPLOT_SPLITTER_FEEDBACK_TIMER) || sep_hld) {
  3090. if (sep_clk && ImGui::IsMouseDoubleClicked(0)) {
  3091. float p = (subplot.RowRatios[r] + subplot.RowRatios[r+1])/2;
  3092. subplot.RowRatios[r] = subplot.RowRatios[r+1] = p;
  3093. }
  3094. if (sep_clk) {
  3095. subplot.TempSizes[0] = subplot.RowRatios[r];
  3096. subplot.TempSizes[1] = subplot.RowRatios[r+1];
  3097. }
  3098. if (sep_hld) {
  3099. float dp = ImGui::GetMouseDragDelta(0).y / subplot.GridRect.GetHeight();
  3100. if (subplot.TempSizes[0] + dp > 0.1f && subplot.TempSizes[1] - dp > 0.1f) {
  3101. subplot.RowRatios[r] = subplot.TempSizes[0] + dp;
  3102. subplot.RowRatios[r+1] = subplot.TempSizes[1] - dp;
  3103. }
  3104. }
  3105. DrawList.AddLine(ImVec2(IM_ROUND(subplot.GridRect.Min.x),IM_ROUND(ypos)),
  3106. ImVec2(IM_ROUND(subplot.GridRect.Max.x),IM_ROUND(ypos)),
  3107. sep_hld ? act_col : hov_col, SUBPLOT_BORDER_SIZE);
  3108. ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS);
  3109. }
  3110. separator++;
  3111. }
  3112. for (int c = 0; c < subplot.Cols-1; ++c) {
  3113. xpos += subplot.ColRatios[c] * subplot.GridRect.GetWidth();
  3114. const ImGuiID sep_id = subplot.ID + separator;
  3115. ImGui::KeepAliveID(sep_id);
  3116. const ImRect sep_bb = ImRect(xpos-SUBPLOT_SPLITTER_HALF_THICKNESS, subplot.GridRect.Min.y, xpos+SUBPLOT_SPLITTER_HALF_THICKNESS, subplot.GridRect.Max.y);
  3117. bool sep_hov = false, sep_hld = false;
  3118. const bool sep_clk = ImGui::ButtonBehavior(sep_bb, sep_id, &sep_hov, &sep_hld, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick);
  3119. if ((sep_hov && G.HoveredIdTimer > SUBPLOT_SPLITTER_FEEDBACK_TIMER) || sep_hld) {
  3120. if (sep_clk && ImGui::IsMouseDoubleClicked(0)) {
  3121. float p = (subplot.ColRatios[c] + subplot.ColRatios[c+1])/2;
  3122. subplot.ColRatios[c] = subplot.ColRatios[c+1] = p;
  3123. }
  3124. if (sep_clk) {
  3125. subplot.TempSizes[0] = subplot.ColRatios[c];
  3126. subplot.TempSizes[1] = subplot.ColRatios[c+1];
  3127. }
  3128. if (sep_hld) {
  3129. float dp = ImGui::GetMouseDragDelta(0).x / subplot.GridRect.GetWidth();
  3130. if (subplot.TempSizes[0] + dp > 0.1f && subplot.TempSizes[1] - dp > 0.1f) {
  3131. subplot.ColRatios[c] = subplot.TempSizes[0] + dp;
  3132. subplot.ColRatios[c+1] = subplot.TempSizes[1] - dp;
  3133. }
  3134. }
  3135. DrawList.AddLine(ImVec2(IM_ROUND(xpos),IM_ROUND(subplot.GridRect.Min.y)),
  3136. ImVec2(IM_ROUND(xpos),IM_ROUND(subplot.GridRect.Max.y)),
  3137. sep_hld ? act_col : hov_col, SUBPLOT_BORDER_SIZE);
  3138. ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW);
  3139. }
  3140. separator++;
  3141. }
  3142. }
  3143. // set outgoing sizes
  3144. if (row_sizes != nullptr) {
  3145. for (int r = 0; r < rows; ++r)
  3146. row_sizes[r] = subplot.RowRatios[r] * row_sum;
  3147. }
  3148. if (col_sizes != nullptr) {
  3149. for (int c = 0; c < cols; ++c)
  3150. col_sizes[c] = subplot.ColRatios[c] * col_sum;
  3151. }
  3152. // push styling
  3153. PushStyleColor(ImPlotCol_FrameBg, IM_COL32_BLACK_TRANS);
  3154. PushStyleVar(ImPlotStyleVar_PlotPadding, half_pad);
  3155. PushStyleVar(ImPlotStyleVar_PlotMinSize, ImVec2(0,0));
  3156. ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize,0);
  3157. // set initial cursor pos
  3158. Window->DC.CursorPos = subplot.GridRect.Min;
  3159. // begin alignments
  3160. for (int r = 0; r < subplot.Rows; ++r)
  3161. subplot.RowAlignmentData[r].Begin();
  3162. for (int c = 0; c < subplot.Cols; ++c)
  3163. subplot.ColAlignmentData[c].Begin();
  3164. // clear legend data
  3165. subplot.Items.Legend.Reset();
  3166. // Setup first subplot
  3167. SubplotSetCell(0,0);
  3168. return true;
  3169. }
  3170. void EndSubplots() {
  3171. IM_ASSERT_USER_ERROR(GImPlot != nullptr, "No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?");
  3172. ImPlotContext& gp = *GImPlot;
  3173. IM_ASSERT_USER_ERROR(gp.CurrentSubplot != nullptr, "Mismatched BeginSubplots()/EndSubplots()!");
  3174. ImPlotSubplot& subplot = *gp.CurrentSubplot;
  3175. // set alignments
  3176. for (int r = 0; r < subplot.Rows; ++r)
  3177. subplot.RowAlignmentData[r].End();
  3178. for (int c = 0; c < subplot.Cols; ++c)
  3179. subplot.ColAlignmentData[c].End();
  3180. // pop styling
  3181. PopStyleColor();
  3182. PopStyleVar();
  3183. PopStyleVar();
  3184. ImGui::PopStyleVar();
  3185. // legend
  3186. subplot.Items.Legend.Hovered = false;
  3187. for (int i = 0; i < subplot.Items.GetItemCount(); ++i)
  3188. subplot.Items.GetItemByIndex(i)->LegendHovered = false;
  3189. // render legend
  3190. const bool share_items = ImHasFlag(subplot.Flags, ImPlotSubplotFlags_ShareItems);
  3191. ImDrawList& DrawList = *ImGui::GetWindowDrawList();
  3192. if (share_items && !ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoLegend) && subplot.Items.GetLegendCount() > 0) {
  3193. const bool legend_horz = ImHasFlag(subplot.Items.Legend.Flags, ImPlotLegendFlags_Horizontal);
  3194. const ImVec2 legend_size = CalcLegendSize(subplot.Items, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !legend_horz);
  3195. const ImVec2 legend_pos = GetLocationPos(subplot.FrameRect, legend_size, subplot.Items.Legend.Location, gp.Style.PlotPadding);
  3196. subplot.Items.Legend.Rect = ImRect(legend_pos, legend_pos + legend_size);
  3197. subplot.Items.Legend.Hovered = subplot.FrameHovered && subplot.Items.Legend.Rect.Contains(ImGui::GetIO().MousePos);
  3198. ImGui::PushClipRect(subplot.FrameRect.Min, subplot.FrameRect.Max, true);
  3199. ImU32 col_bg = GetStyleColorU32(ImPlotCol_LegendBg);
  3200. ImU32 col_bd = GetStyleColorU32(ImPlotCol_LegendBorder);
  3201. DrawList.AddRectFilled(subplot.Items.Legend.Rect.Min, subplot.Items.Legend.Rect.Max, col_bg);
  3202. DrawList.AddRect(subplot.Items.Legend.Rect.Min, subplot.Items.Legend.Rect.Max, col_bd);
  3203. bool legend_contextable = ShowLegendEntries(subplot.Items, subplot.Items.Legend.Rect, subplot.Items.Legend.Hovered, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !legend_horz, DrawList)
  3204. && !ImHasFlag(subplot.Items.Legend.Flags, ImPlotLegendFlags_NoMenus);
  3205. if (legend_contextable && !ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoMenus) && ImGui::GetIO().MouseReleased[gp.InputMap.Menu])
  3206. ImGui::OpenPopup("##LegendContext");
  3207. ImGui::PopClipRect();
  3208. if (ImGui::BeginPopup("##LegendContext")) {
  3209. ImGui::Text("Legend"); ImGui::Separator();
  3210. if (ShowLegendContextMenu(subplot.Items.Legend, !ImHasFlag(subplot.Flags, ImPlotFlags_NoLegend)))
  3211. ImFlipFlag(subplot.Flags, ImPlotFlags_NoLegend);
  3212. ImGui::EndPopup();
  3213. }
  3214. }
  3215. else {
  3216. subplot.Items.Legend.Rect = ImRect();
  3217. }
  3218. // remove items
  3219. if (gp.CurrentItems == &subplot.Items)
  3220. gp.CurrentItems = nullptr;
  3221. // reset the plot items for the next frame (TODO: put this elswhere)
  3222. for (int i = 0; i < subplot.Items.GetItemCount(); ++i) {
  3223. subplot.Items.GetItemByIndex(i)->SeenThisFrame = false;
  3224. }
  3225. // pop id
  3226. ImGui::PopID();
  3227. // set DC back correctly
  3228. GImGui->CurrentWindow->DC.CursorPos = subplot.FrameRect.Min;
  3229. ImGui::Dummy(subplot.FrameRect.GetSize());
  3230. ResetCtxForNextSubplot(GImPlot);
  3231. }
  3232. //-----------------------------------------------------------------------------
  3233. // [SECTION] Plot Utils
  3234. //-----------------------------------------------------------------------------
  3235. void SetAxis(ImAxis axis) {
  3236. ImPlotContext& gp = *GImPlot;
  3237. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "SetAxis() needs to be called between BeginPlot() and EndPlot()!");
  3238. IM_ASSERT_USER_ERROR(axis >= ImAxis_X1 && axis < ImAxis_COUNT, "Axis index out of bounds!");
  3239. IM_ASSERT_USER_ERROR(gp.CurrentPlot->Axes[axis].Enabled, "Axis is not enabled! Did you forget to call SetupAxis()?");
  3240. SetupLock();
  3241. if (axis < ImAxis_Y1)
  3242. gp.CurrentPlot->CurrentX = axis;
  3243. else
  3244. gp.CurrentPlot->CurrentY = axis;
  3245. }
  3246. void SetAxes(ImAxis x_idx, ImAxis y_idx) {
  3247. ImPlotContext& gp = *GImPlot;
  3248. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "SetAxes() needs to be called between BeginPlot() and EndPlot()!");
  3249. IM_ASSERT_USER_ERROR(x_idx >= ImAxis_X1 && x_idx < ImAxis_Y1, "X-Axis index out of bounds!");
  3250. IM_ASSERT_USER_ERROR(y_idx >= ImAxis_Y1 && y_idx < ImAxis_COUNT, "Y-Axis index out of bounds!");
  3251. IM_ASSERT_USER_ERROR(gp.CurrentPlot->Axes[x_idx].Enabled, "Axis is not enabled! Did you forget to call SetupAxis()?");
  3252. IM_ASSERT_USER_ERROR(gp.CurrentPlot->Axes[y_idx].Enabled, "Axis is not enabled! Did you forget to call SetupAxis()?");
  3253. SetupLock();
  3254. gp.CurrentPlot->CurrentX = x_idx;
  3255. gp.CurrentPlot->CurrentY = y_idx;
  3256. }
  3257. ImPlotPoint PixelsToPlot(float x, float y, ImAxis x_idx, ImAxis y_idx) {
  3258. ImPlotContext& gp = *GImPlot;
  3259. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PixelsToPlot() needs to be called between BeginPlot() and EndPlot()!");
  3260. IM_ASSERT_USER_ERROR(x_idx == IMPLOT_AUTO || (x_idx >= ImAxis_X1 && x_idx < ImAxis_Y1), "X-Axis index out of bounds!");
  3261. IM_ASSERT_USER_ERROR(y_idx == IMPLOT_AUTO || (y_idx >= ImAxis_Y1 && y_idx < ImAxis_COUNT), "Y-Axis index out of bounds!");
  3262. SetupLock();
  3263. ImPlotPlot& plot = *gp.CurrentPlot;
  3264. ImPlotAxis& x_axis = x_idx == IMPLOT_AUTO ? plot.Axes[plot.CurrentX] : plot.Axes[x_idx];
  3265. ImPlotAxis& y_axis = y_idx == IMPLOT_AUTO ? plot.Axes[plot.CurrentY] : plot.Axes[y_idx];
  3266. return ImPlotPoint( x_axis.PixelsToPlot(x), y_axis.PixelsToPlot(y) );
  3267. }
  3268. ImPlotPoint PixelsToPlot(const ImVec2& pix, ImAxis x_idx, ImAxis y_idx) {
  3269. return PixelsToPlot(pix.x, pix.y, x_idx, y_idx);
  3270. }
  3271. ImVec2 PlotToPixels(double x, double y, ImAxis x_idx, ImAxis y_idx) {
  3272. ImPlotContext& gp = *GImPlot;
  3273. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PlotToPixels() needs to be called between BeginPlot() and EndPlot()!");
  3274. IM_ASSERT_USER_ERROR(x_idx == IMPLOT_AUTO || (x_idx >= ImAxis_X1 && x_idx < ImAxis_Y1), "X-Axis index out of bounds!");
  3275. IM_ASSERT_USER_ERROR(y_idx == IMPLOT_AUTO || (y_idx >= ImAxis_Y1 && y_idx < ImAxis_COUNT), "Y-Axis index out of bounds!");
  3276. SetupLock();
  3277. ImPlotPlot& plot = *gp.CurrentPlot;
  3278. ImPlotAxis& x_axis = x_idx == IMPLOT_AUTO ? plot.Axes[plot.CurrentX] : plot.Axes[x_idx];
  3279. ImPlotAxis& y_axis = y_idx == IMPLOT_AUTO ? plot.Axes[plot.CurrentY] : plot.Axes[y_idx];
  3280. return ImVec2( x_axis.PlotToPixels(x), y_axis.PlotToPixels(y) );
  3281. }
  3282. ImVec2 PlotToPixels(const ImPlotPoint& plt, ImAxis x_idx, ImAxis y_idx) {
  3283. return PlotToPixels(plt.x, plt.y, x_idx, y_idx);
  3284. }
  3285. ImVec2 GetPlotPos() {
  3286. ImPlotContext& gp = *GImPlot;
  3287. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetPlotPos() needs to be called between BeginPlot() and EndPlot()!");
  3288. SetupLock();
  3289. return gp.CurrentPlot->PlotRect.Min;
  3290. }
  3291. ImVec2 GetPlotSize() {
  3292. ImPlotContext& gp = *GImPlot;
  3293. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetPlotSize() needs to be called between BeginPlot() and EndPlot()!");
  3294. SetupLock();
  3295. return gp.CurrentPlot->PlotRect.GetSize();
  3296. }
  3297. ImPlotPoint GetPlotMousePos(ImAxis x_idx, ImAxis y_idx) {
  3298. IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != nullptr, "GetPlotMousePos() needs to be called between BeginPlot() and EndPlot()!");
  3299. SetupLock();
  3300. return PixelsToPlot(ImGui::GetMousePos(), x_idx, y_idx);
  3301. }
  3302. ImPlotRect GetPlotLimits(ImAxis x_idx, ImAxis y_idx) {
  3303. ImPlotContext& gp = *GImPlot;
  3304. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetPlotLimits() needs to be called between BeginPlot() and EndPlot()!");
  3305. IM_ASSERT_USER_ERROR(x_idx == IMPLOT_AUTO || (x_idx >= ImAxis_X1 && x_idx < ImAxis_Y1), "X-Axis index out of bounds!");
  3306. IM_ASSERT_USER_ERROR(y_idx == IMPLOT_AUTO || (y_idx >= ImAxis_Y1 && y_idx < ImAxis_COUNT), "Y-Axis index out of bounds!");
  3307. SetupLock();
  3308. ImPlotPlot& plot = *gp.CurrentPlot;
  3309. ImPlotAxis& x_axis = x_idx == IMPLOT_AUTO ? plot.Axes[plot.CurrentX] : plot.Axes[x_idx];
  3310. ImPlotAxis& y_axis = y_idx == IMPLOT_AUTO ? plot.Axes[plot.CurrentY] : plot.Axes[y_idx];
  3311. ImPlotRect limits;
  3312. limits.X = x_axis.Range;
  3313. limits.Y = y_axis.Range;
  3314. return limits;
  3315. }
  3316. bool IsPlotHovered() {
  3317. ImPlotContext& gp = *GImPlot;
  3318. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "IsPlotHovered() needs to be called between BeginPlot() and EndPlot()!");
  3319. SetupLock();
  3320. return gp.CurrentPlot->Hovered;
  3321. }
  3322. bool IsAxisHovered(ImAxis axis) {
  3323. ImPlotContext& gp = *GImPlot;
  3324. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "IsPlotXAxisHovered() needs to be called between BeginPlot() and EndPlot()!");
  3325. SetupLock();
  3326. return gp.CurrentPlot->Axes[axis].Hovered;
  3327. }
  3328. bool IsSubplotsHovered() {
  3329. ImPlotContext& gp = *GImPlot;
  3330. IM_ASSERT_USER_ERROR(gp.CurrentSubplot != nullptr, "IsSubplotsHovered() needs to be called between BeginSubplots() and EndSubplots()!");
  3331. return gp.CurrentSubplot->FrameHovered;
  3332. }
  3333. bool IsPlotSelected() {
  3334. ImPlotContext& gp = *GImPlot;
  3335. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "IsPlotSelected() needs to be called between BeginPlot() and EndPlot()!");
  3336. SetupLock();
  3337. return gp.CurrentPlot->Selected;
  3338. }
  3339. ImPlotRect GetPlotSelection(ImAxis x_idx, ImAxis y_idx) {
  3340. ImPlotContext& gp = *GImPlot;
  3341. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "GetPlotSelection() needs to be called between BeginPlot() and EndPlot()!");
  3342. SetupLock();
  3343. ImPlotPlot& plot = *gp.CurrentPlot;
  3344. if (!plot.Selected)
  3345. return ImPlotRect(0,0,0,0);
  3346. ImPlotPoint p1 = PixelsToPlot(plot.SelectRect.Min + plot.PlotRect.Min, x_idx, y_idx);
  3347. ImPlotPoint p2 = PixelsToPlot(plot.SelectRect.Max + plot.PlotRect.Min, x_idx, y_idx);
  3348. ImPlotRect result;
  3349. result.X.Min = ImMin(p1.x, p2.x);
  3350. result.X.Max = ImMax(p1.x, p2.x);
  3351. result.Y.Min = ImMin(p1.y, p2.y);
  3352. result.Y.Max = ImMax(p1.y, p2.y);
  3353. return result;
  3354. }
  3355. void CancelPlotSelection() {
  3356. ImPlotContext& gp = *GImPlot;
  3357. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "CancelPlotSelection() needs to be called between BeginPlot() and EndPlot()!");
  3358. SetupLock();
  3359. ImPlotPlot& plot = *gp.CurrentPlot;
  3360. if (plot.Selected)
  3361. plot.Selected = plot.Selecting = false;
  3362. }
  3363. void HideNextItem(bool hidden, ImPlotCond cond) {
  3364. ImPlotContext& gp = *GImPlot;
  3365. gp.NextItemData.HasHidden = true;
  3366. gp.NextItemData.Hidden = hidden;
  3367. gp.NextItemData.HiddenCond = cond;
  3368. }
  3369. //-----------------------------------------------------------------------------
  3370. // [SECTION] Plot Tools
  3371. //-----------------------------------------------------------------------------
  3372. void Annotation(double x, double y, const ImVec4& col, const ImVec2& offset, bool clamp, bool round) {
  3373. ImPlotContext& gp = *GImPlot;
  3374. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "Annotation() needs to be called between BeginPlot() and EndPlot()!");
  3375. SetupLock();
  3376. char x_buff[IMPLOT_LABEL_MAX_SIZE];
  3377. char y_buff[IMPLOT_LABEL_MAX_SIZE];
  3378. ImPlotAxis& x_axis = gp.CurrentPlot->Axes[gp.CurrentPlot->CurrentX];
  3379. ImPlotAxis& y_axis = gp.CurrentPlot->Axes[gp.CurrentPlot->CurrentY];
  3380. LabelAxisValue(x_axis, x, x_buff, sizeof(x_buff), round);
  3381. LabelAxisValue(y_axis, y, y_buff, sizeof(y_buff), round);
  3382. Annotation(x,y,col,offset,clamp,"%s, %s",x_buff,y_buff);
  3383. }
  3384. void AnnotationV(double x, double y, const ImVec4& col, const ImVec2& offset, bool clamp, const char* fmt, va_list args) {
  3385. ImPlotContext& gp = *GImPlot;
  3386. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "Annotation() needs to be called between BeginPlot() and EndPlot()!");
  3387. SetupLock();
  3388. ImVec2 pos = PlotToPixels(x,y,IMPLOT_AUTO,IMPLOT_AUTO);
  3389. ImU32 bg = ImGui::GetColorU32(col);
  3390. ImU32 fg = col.w == 0 ? GetStyleColorU32(ImPlotCol_InlayText) : CalcTextColor(col);
  3391. gp.Annotations.AppendV(pos, offset, bg, fg, clamp, fmt, args);
  3392. }
  3393. void Annotation(double x, double y, const ImVec4& col, const ImVec2& offset, bool clamp, const char* fmt, ...) {
  3394. va_list args;
  3395. va_start(args, fmt);
  3396. AnnotationV(x,y,col,offset,clamp,fmt,args);
  3397. va_end(args);
  3398. }
  3399. void TagV(ImAxis axis, double v, const ImVec4& col, const char* fmt, va_list args) {
  3400. ImPlotContext& gp = *GImPlot;
  3401. SetupLock();
  3402. ImU32 bg = ImGui::GetColorU32(col);
  3403. ImU32 fg = col.w == 0 ? GetStyleColorU32(ImPlotCol_AxisText) : CalcTextColor(col);
  3404. gp.Tags.AppendV(axis,v,bg,fg,fmt,args);
  3405. }
  3406. void Tag(ImAxis axis, double v, const ImVec4& col, const char* fmt, ...) {
  3407. va_list args;
  3408. va_start(args, fmt);
  3409. TagV(axis,v,col,fmt,args);
  3410. va_end(args);
  3411. }
  3412. void Tag(ImAxis axis, double v, const ImVec4& color, bool round) {
  3413. ImPlotContext& gp = *GImPlot;
  3414. SetupLock();
  3415. char buff[IMPLOT_LABEL_MAX_SIZE];
  3416. ImPlotAxis& ax = gp.CurrentPlot->Axes[axis];
  3417. LabelAxisValue(ax, v, buff, sizeof(buff), round);
  3418. Tag(axis,v,color,"%s",buff);
  3419. }
  3420. IMPLOT_API void TagX(double x, const ImVec4& color, bool round) {
  3421. ImPlotContext& gp = *GImPlot;
  3422. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "TagX() needs to be called between BeginPlot() and EndPlot()!");
  3423. Tag(gp.CurrentPlot->CurrentX, x, color, round);
  3424. }
  3425. IMPLOT_API void TagX(double x, const ImVec4& color, const char* fmt, ...) {
  3426. ImPlotContext& gp = *GImPlot;
  3427. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "TagX() needs to be called between BeginPlot() and EndPlot()!");
  3428. va_list args;
  3429. va_start(args, fmt);
  3430. TagV(gp.CurrentPlot->CurrentX,x,color,fmt,args);
  3431. va_end(args);
  3432. }
  3433. IMPLOT_API void TagXV(double x, const ImVec4& color, const char* fmt, va_list args) {
  3434. ImPlotContext& gp = *GImPlot;
  3435. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "TagX() needs to be called between BeginPlot() and EndPlot()!");
  3436. TagV(gp.CurrentPlot->CurrentX, x, color, fmt, args);
  3437. }
  3438. IMPLOT_API void TagY(double y, const ImVec4& color, bool round) {
  3439. ImPlotContext& gp = *GImPlot;
  3440. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "TagY() needs to be called between BeginPlot() and EndPlot()!");
  3441. Tag(gp.CurrentPlot->CurrentY, y, color, round);
  3442. }
  3443. IMPLOT_API void TagY(double y, const ImVec4& color, const char* fmt, ...) {
  3444. ImPlotContext& gp = *GImPlot;
  3445. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "TagY() needs to be called between BeginPlot() and EndPlot()!");
  3446. va_list args;
  3447. va_start(args, fmt);
  3448. TagV(gp.CurrentPlot->CurrentY,y,color,fmt,args);
  3449. va_end(args);
  3450. }
  3451. IMPLOT_API void TagYV(double y, const ImVec4& color, const char* fmt, va_list args) {
  3452. ImPlotContext& gp = *GImPlot;
  3453. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "TagY() needs to be called between BeginPlot() and EndPlot()!");
  3454. TagV(gp.CurrentPlot->CurrentY, y, color, fmt, args);
  3455. }
  3456. static const float DRAG_GRAB_HALF_SIZE = 4.0f;
  3457. bool DragPoint(int n_id, double* x, double* y, const ImVec4& col, float radius, ImPlotDragToolFlags flags) {
  3458. ImGui::PushID("#IMPLOT_DRAG_POINT");
  3459. IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != nullptr, "DragPoint() needs to be called between BeginPlot() and EndPlot()!");
  3460. SetupLock();
  3461. if (!ImHasFlag(flags,ImPlotDragToolFlags_NoFit) && FitThisFrame()) {
  3462. FitPoint(ImPlotPoint(*x,*y));
  3463. }
  3464. const bool input = !ImHasFlag(flags, ImPlotDragToolFlags_NoInputs);
  3465. const bool show_curs = !ImHasFlag(flags, ImPlotDragToolFlags_NoCursors);
  3466. const bool no_delay = !ImHasFlag(flags, ImPlotDragToolFlags_Delayed);
  3467. const float grab_half_size = ImMax(DRAG_GRAB_HALF_SIZE, radius);
  3468. const ImVec4 color = IsColorAuto(col) ? ImGui::GetStyleColorVec4(ImGuiCol_Text) : col;
  3469. const ImU32 col32 = ImGui::ColorConvertFloat4ToU32(color);
  3470. ImVec2 pos = PlotToPixels(*x,*y,IMPLOT_AUTO,IMPLOT_AUTO);
  3471. const ImGuiID id = ImGui::GetCurrentWindow()->GetID(n_id);
  3472. ImRect rect(pos.x-grab_half_size,pos.y-grab_half_size,pos.x+grab_half_size,pos.y+grab_half_size);
  3473. bool hovered = false, held = false;
  3474. ImGui::KeepAliveID(id);
  3475. if (input)
  3476. ImGui::ButtonBehavior(rect,id,&hovered,&held);
  3477. bool dragging = false;
  3478. if (held && ImGui::IsMouseDragging(0)) {
  3479. *x = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).x;
  3480. *y = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).y;
  3481. dragging = true;
  3482. }
  3483. PushPlotClipRect();
  3484. ImDrawList& DrawList = *GetPlotDrawList();
  3485. if ((hovered || held) && show_curs)
  3486. ImGui::SetMouseCursor(ImGuiMouseCursor_Hand);
  3487. if (dragging && no_delay)
  3488. pos = PlotToPixels(*x,*y,IMPLOT_AUTO,IMPLOT_AUTO);
  3489. DrawList.AddCircleFilled(pos, radius, col32);
  3490. PopPlotClipRect();
  3491. ImGui::PopID();
  3492. return dragging;
  3493. }
  3494. bool DragLineX(int n_id, double* value, const ImVec4& col, float thickness, ImPlotDragToolFlags flags) {
  3495. // ImGui::PushID("#IMPLOT_DRAG_LINE_X");
  3496. ImPlotContext& gp = *GImPlot;
  3497. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "DragLineX() needs to be called between BeginPlot() and EndPlot()!");
  3498. SetupLock();
  3499. if (!ImHasFlag(flags,ImPlotDragToolFlags_NoFit) && FitThisFrame()) {
  3500. FitPointX(*value);
  3501. }
  3502. const bool input = !ImHasFlag(flags, ImPlotDragToolFlags_NoInputs);
  3503. const bool show_curs = !ImHasFlag(flags, ImPlotDragToolFlags_NoCursors);
  3504. const bool no_delay = !ImHasFlag(flags, ImPlotDragToolFlags_Delayed);
  3505. const float grab_half_size = ImMax(DRAG_GRAB_HALF_SIZE, thickness/2);
  3506. float yt = gp.CurrentPlot->PlotRect.Min.y;
  3507. float yb = gp.CurrentPlot->PlotRect.Max.y;
  3508. float x = IM_ROUND(PlotToPixels(*value,0,IMPLOT_AUTO,IMPLOT_AUTO).x);
  3509. const ImGuiID id = ImGui::GetCurrentWindow()->GetID(n_id);
  3510. ImRect rect(x-grab_half_size,yt,x+grab_half_size,yb);
  3511. bool hovered = false, held = false;
  3512. ImGui::KeepAliveID(id);
  3513. if (input)
  3514. ImGui::ButtonBehavior(rect,id,&hovered,&held);
  3515. if ((hovered || held) && show_curs)
  3516. ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW);
  3517. float len = gp.Style.MajorTickLen.x;
  3518. ImVec4 color = IsColorAuto(col) ? ImGui::GetStyleColorVec4(ImGuiCol_Text) : col;
  3519. ImU32 col32 = ImGui::ColorConvertFloat4ToU32(color);
  3520. bool dragging = false;
  3521. if (held && ImGui::IsMouseDragging(0)) {
  3522. *value = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).x;
  3523. dragging = true;
  3524. }
  3525. PushPlotClipRect();
  3526. ImDrawList& DrawList = *GetPlotDrawList();
  3527. if (dragging && no_delay)
  3528. x = IM_ROUND(PlotToPixels(*value,0,IMPLOT_AUTO,IMPLOT_AUTO).x);
  3529. DrawList.AddLine(ImVec2(x,yt), ImVec2(x,yb), col32, thickness);
  3530. DrawList.AddLine(ImVec2(x,yt), ImVec2(x,yt+len), col32, 3*thickness);
  3531. DrawList.AddLine(ImVec2(x,yb), ImVec2(x,yb-len), col32, 3*thickness);
  3532. PopPlotClipRect();
  3533. // ImGui::PopID();
  3534. return dragging;
  3535. }
  3536. bool DragLineY(int n_id, double* value, const ImVec4& col, float thickness, ImPlotDragToolFlags flags) {
  3537. ImGui::PushID("#IMPLOT_DRAG_LINE_Y");
  3538. ImPlotContext& gp = *GImPlot;
  3539. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "DragLineY() needs to be called between BeginPlot() and EndPlot()!");
  3540. SetupLock();
  3541. if (!ImHasFlag(flags,ImPlotDragToolFlags_NoFit) && FitThisFrame()) {
  3542. FitPointY(*value);
  3543. }
  3544. const bool input = !ImHasFlag(flags, ImPlotDragToolFlags_NoInputs);
  3545. const bool show_curs = !ImHasFlag(flags, ImPlotDragToolFlags_NoCursors);
  3546. const bool no_delay = !ImHasFlag(flags, ImPlotDragToolFlags_Delayed);
  3547. const float grab_half_size = ImMax(DRAG_GRAB_HALF_SIZE, thickness/2);
  3548. float xl = gp.CurrentPlot->PlotRect.Min.x;
  3549. float xr = gp.CurrentPlot->PlotRect.Max.x;
  3550. float y = IM_ROUND(PlotToPixels(0, *value,IMPLOT_AUTO,IMPLOT_AUTO).y);
  3551. const ImGuiID id = ImGui::GetCurrentWindow()->GetID(n_id);
  3552. ImRect rect(xl,y-grab_half_size,xr,y+grab_half_size);
  3553. bool hovered = false, held = false;
  3554. ImGui::KeepAliveID(id);
  3555. if (input)
  3556. ImGui::ButtonBehavior(rect,id,&hovered,&held);
  3557. if ((hovered || held) && show_curs)
  3558. ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS);
  3559. float len = gp.Style.MajorTickLen.y;
  3560. ImVec4 color = IsColorAuto(col) ? ImGui::GetStyleColorVec4(ImGuiCol_Text) : col;
  3561. ImU32 col32 = ImGui::ColorConvertFloat4ToU32(color);
  3562. bool dragging = false;
  3563. if (held && ImGui::IsMouseDragging(0)) {
  3564. *value = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).y;
  3565. dragging = true;
  3566. }
  3567. PushPlotClipRect();
  3568. ImDrawList& DrawList = *GetPlotDrawList();
  3569. if (dragging && no_delay)
  3570. y = IM_ROUND(PlotToPixels(0, *value,IMPLOT_AUTO,IMPLOT_AUTO).y);
  3571. DrawList.AddLine(ImVec2(xl,y), ImVec2(xr,y), col32, thickness);
  3572. DrawList.AddLine(ImVec2(xl,y), ImVec2(xl+len,y), col32, 3*thickness);
  3573. DrawList.AddLine(ImVec2(xr,y), ImVec2(xr-len,y), col32, 3*thickness);
  3574. PopPlotClipRect();
  3575. ImGui::PopID();
  3576. return dragging;
  3577. }
  3578. bool DragRect(int n_id, double* x_min, double* y_min, double* x_max, double* y_max, const ImVec4& col, ImPlotDragToolFlags flags) {
  3579. ImGui::PushID("#IMPLOT_DRAG_RECT");
  3580. IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != nullptr, "DragRect() needs to be called between BeginPlot() and EndPlot()!");
  3581. SetupLock();
  3582. if (!ImHasFlag(flags,ImPlotDragToolFlags_NoFit) && FitThisFrame()) {
  3583. FitPoint(ImPlotPoint(*x_min,*y_min));
  3584. FitPoint(ImPlotPoint(*x_max,*y_max));
  3585. }
  3586. const bool input = !ImHasFlag(flags, ImPlotDragToolFlags_NoInputs);
  3587. const bool show_curs = !ImHasFlag(flags, ImPlotDragToolFlags_NoCursors);
  3588. const bool no_delay = !ImHasFlag(flags, ImPlotDragToolFlags_Delayed);
  3589. bool h[] = {true,false,true,false};
  3590. double* x[] = {x_min,x_max,x_max,x_min};
  3591. double* y[] = {y_min,y_min,y_max,y_max};
  3592. ImVec2 p[4];
  3593. for (int i = 0; i < 4; ++i)
  3594. p[i] = PlotToPixels(*x[i],*y[i],IMPLOT_AUTO,IMPLOT_AUTO);
  3595. ImVec2 pc = PlotToPixels((*x_min+*x_max)/2,(*y_min+*y_max)/2,IMPLOT_AUTO,IMPLOT_AUTO);
  3596. ImRect rect(ImMin(p[0],p[2]),ImMax(p[0],p[2]));
  3597. ImRect rect_grab = rect; rect_grab.Expand(DRAG_GRAB_HALF_SIZE);
  3598. ImGuiMouseCursor cur[4];
  3599. if (show_curs) {
  3600. cur[0] = (rect.Min.x == p[0].x && rect.Min.y == p[0].y) || (rect.Max.x == p[0].x && rect.Max.y == p[0].y) ? ImGuiMouseCursor_ResizeNWSE : ImGuiMouseCursor_ResizeNESW;
  3601. cur[1] = cur[0] == ImGuiMouseCursor_ResizeNWSE ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
  3602. cur[2] = cur[1] == ImGuiMouseCursor_ResizeNWSE ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
  3603. cur[3] = cur[2] == ImGuiMouseCursor_ResizeNWSE ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
  3604. }
  3605. ImVec4 color = IsColorAuto(col) ? ImGui::GetStyleColorVec4(ImGuiCol_Text) : col;
  3606. ImU32 col32 = ImGui::ColorConvertFloat4ToU32(color);
  3607. color.w *= 0.25f;
  3608. ImU32 col32_a = ImGui::ColorConvertFloat4ToU32(color);
  3609. const ImGuiID id = ImGui::GetCurrentWindow()->GetID(n_id);
  3610. bool dragging = false;
  3611. bool hovered = false, held = false;
  3612. ImRect b_rect(pc.x-DRAG_GRAB_HALF_SIZE,pc.y-DRAG_GRAB_HALF_SIZE,pc.x+DRAG_GRAB_HALF_SIZE,pc.y+DRAG_GRAB_HALF_SIZE);
  3613. ImGui::KeepAliveID(id);
  3614. if (input)
  3615. ImGui::ButtonBehavior(b_rect,id,&hovered,&held);
  3616. if ((hovered || held) && show_curs)
  3617. ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeAll);
  3618. if (held && ImGui::IsMouseDragging(0)) {
  3619. for (int i = 0; i < 4; ++i) {
  3620. ImPlotPoint pp = PixelsToPlot(p[i] + ImGui::GetIO().MouseDelta,IMPLOT_AUTO,IMPLOT_AUTO);
  3621. *y[i] = pp.y;
  3622. *x[i] = pp.x;
  3623. }
  3624. dragging = true;
  3625. }
  3626. for (int i = 0; i < 4; ++i) {
  3627. // points
  3628. b_rect = ImRect(p[i].x-DRAG_GRAB_HALF_SIZE,p[i].y-DRAG_GRAB_HALF_SIZE,p[i].x+DRAG_GRAB_HALF_SIZE,p[i].y+DRAG_GRAB_HALF_SIZE);
  3629. ImGuiID p_id = id + i + 1;
  3630. ImGui::KeepAliveID(p_id);
  3631. if (input)
  3632. ImGui::ButtonBehavior(b_rect,p_id,&hovered,&held);
  3633. if ((hovered || held) && show_curs)
  3634. ImGui::SetMouseCursor(cur[i]);
  3635. if (held && ImGui::IsMouseDragging(0)) {
  3636. *x[i] = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).x;
  3637. *y[i] = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).y;
  3638. dragging = true;
  3639. }
  3640. // edges
  3641. ImVec2 e_min = ImMin(p[i],p[(i+1)%4]);
  3642. ImVec2 e_max = ImMax(p[i],p[(i+1)%4]);
  3643. b_rect = h[i] ? ImRect(e_min.x + DRAG_GRAB_HALF_SIZE, e_min.y - DRAG_GRAB_HALF_SIZE, e_max.x - DRAG_GRAB_HALF_SIZE, e_max.y + DRAG_GRAB_HALF_SIZE)
  3644. : ImRect(e_min.x - DRAG_GRAB_HALF_SIZE, e_min.y + DRAG_GRAB_HALF_SIZE, e_max.x + DRAG_GRAB_HALF_SIZE, e_max.y - DRAG_GRAB_HALF_SIZE);
  3645. ImGuiID e_id = id + i + 5;
  3646. ImGui::KeepAliveID(e_id);
  3647. if (input)
  3648. ImGui::ButtonBehavior(b_rect,e_id,&hovered,&held);
  3649. if ((hovered || held) && show_curs)
  3650. h[i] ? ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS) : ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW);
  3651. if (held && ImGui::IsMouseDragging(0)) {
  3652. if (h[i])
  3653. *y[i] = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).y;
  3654. else
  3655. *x[i] = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).x;
  3656. dragging = true;
  3657. }
  3658. if (hovered && ImGui::IsMouseDoubleClicked(0))
  3659. {
  3660. ImPlotRect b = GetPlotLimits(IMPLOT_AUTO,IMPLOT_AUTO);
  3661. if (h[i])
  3662. *y[i] = ((y[i] == y_min && *y_min < *y_max) || (y[i] == y_max && *y_max < *y_min)) ? b.Y.Min : b.Y.Max;
  3663. else
  3664. *x[i] = ((x[i] == x_min && *x_min < *x_max) || (x[i] == x_max && *x_max < *x_min)) ? b.X.Min : b.X.Max;
  3665. dragging = true;
  3666. }
  3667. }
  3668. PushPlotClipRect();
  3669. ImDrawList& DrawList = *GetPlotDrawList();
  3670. if (dragging && no_delay) {
  3671. for (int i = 0; i < 4; ++i)
  3672. p[i] = PlotToPixels(*x[i],*y[i],IMPLOT_AUTO,IMPLOT_AUTO);
  3673. pc = PlotToPixels((*x_min+*x_max)/2,(*y_min+*y_max)/2,IMPLOT_AUTO,IMPLOT_AUTO);
  3674. rect = ImRect(ImMin(p[0],p[2]),ImMax(p[0],p[2]));
  3675. }
  3676. DrawList.AddRectFilled(rect.Min, rect.Max, col32_a);
  3677. DrawList.AddRect(rect.Min, rect.Max, col32);
  3678. if (input && (dragging || rect_grab.Contains(ImGui::GetMousePos()))) {
  3679. DrawList.AddCircleFilled(pc,DRAG_GRAB_HALF_SIZE,col32);
  3680. for (int i = 0; i < 4; ++i)
  3681. DrawList.AddCircleFilled(p[i],DRAG_GRAB_HALF_SIZE,col32);
  3682. }
  3683. PopPlotClipRect();
  3684. ImGui::PopID();
  3685. return dragging;
  3686. }
  3687. bool DragRect(int id, ImPlotRect* bounds, const ImVec4& col, ImPlotDragToolFlags flags) {
  3688. return DragRect(id, &bounds->X.Min, &bounds->Y.Min,&bounds->X.Max, &bounds->Y.Max, col, flags);
  3689. }
  3690. //-----------------------------------------------------------------------------
  3691. // [SECTION] Legend Utils and Tools
  3692. //-----------------------------------------------------------------------------
  3693. bool IsLegendEntryHovered(const char* label_id) {
  3694. ImPlotContext& gp = *GImPlot;
  3695. IM_ASSERT_USER_ERROR(gp.CurrentItems != nullptr, "IsPlotItemHighlight() needs to be called within an itemized context!");
  3696. SetupLock();
  3697. ImGuiID id = ImGui::GetIDWithSeed(label_id, nullptr, gp.CurrentItems->ID);
  3698. ImPlotItem* item = gp.CurrentItems->GetItem(id);
  3699. return item && item->LegendHovered;
  3700. }
  3701. bool BeginLegendPopup(const char* label_id, ImGuiMouseButton mouse_button) {
  3702. ImPlotContext& gp = *GImPlot;
  3703. IM_ASSERT_USER_ERROR(gp.CurrentItems != nullptr, "BeginLegendPopup() needs to be called within an itemized context!");
  3704. SetupLock();
  3705. ImGuiWindow* window = GImGui->CurrentWindow;
  3706. if (window->SkipItems)
  3707. return false;
  3708. ImGuiID id = ImGui::GetIDWithSeed(label_id, nullptr, gp.CurrentItems->ID);
  3709. if (ImGui::IsMouseReleased(mouse_button)) {
  3710. ImPlotItem* item = gp.CurrentItems->GetItem(id);
  3711. if (item && item->LegendHovered)
  3712. ImGui::OpenPopupEx(id);
  3713. }
  3714. return ImGui::BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
  3715. }
  3716. void EndLegendPopup() {
  3717. SetupLock();
  3718. ImGui::EndPopup();
  3719. }
  3720. void ShowAltLegend(const char* title_id, bool vertical, const ImVec2 size, bool interactable) {
  3721. ImPlotContext& gp = *GImPlot;
  3722. ImGuiContext &G = *GImGui;
  3723. ImGuiWindow * Window = G.CurrentWindow;
  3724. if (Window->SkipItems)
  3725. return;
  3726. ImDrawList &DrawList = *Window->DrawList;
  3727. ImPlotPlot* plot = GetPlot(title_id);
  3728. ImVec2 legend_size;
  3729. ImVec2 default_size = gp.Style.LegendPadding * 2;
  3730. if (plot != nullptr) {
  3731. legend_size = CalcLegendSize(plot->Items, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, vertical);
  3732. default_size = legend_size + gp.Style.LegendPadding * 2;
  3733. }
  3734. ImVec2 frame_size = ImGui::CalcItemSize(size, default_size.x, default_size.y);
  3735. ImRect bb_frame = ImRect(Window->DC.CursorPos, Window->DC.CursorPos + frame_size);
  3736. ImGui::ItemSize(bb_frame);
  3737. if (!ImGui::ItemAdd(bb_frame, 0, &bb_frame))
  3738. return;
  3739. ImGui::RenderFrame(bb_frame.Min, bb_frame.Max, GetStyleColorU32(ImPlotCol_FrameBg), true, G.Style.FrameRounding);
  3740. DrawList.PushClipRect(bb_frame.Min, bb_frame.Max, true);
  3741. if (plot != nullptr) {
  3742. const ImVec2 legend_pos = GetLocationPos(bb_frame, legend_size, 0, gp.Style.LegendPadding);
  3743. const ImRect legend_bb(legend_pos, legend_pos + legend_size);
  3744. interactable = interactable && bb_frame.Contains(ImGui::GetIO().MousePos);
  3745. // render legend box
  3746. ImU32 col_bg = GetStyleColorU32(ImPlotCol_LegendBg);
  3747. ImU32 col_bd = GetStyleColorU32(ImPlotCol_LegendBorder);
  3748. DrawList.AddRectFilled(legend_bb.Min, legend_bb.Max, col_bg);
  3749. DrawList.AddRect(legend_bb.Min, legend_bb.Max, col_bd);
  3750. // render entries
  3751. ShowLegendEntries(plot->Items, legend_bb, interactable, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, vertical, DrawList);
  3752. }
  3753. DrawList.PopClipRect();
  3754. }
  3755. //-----------------------------------------------------------------------------
  3756. // [SECTION] Drag and Drop Utils
  3757. //-----------------------------------------------------------------------------
  3758. bool BeginDragDropTargetPlot() {
  3759. SetupLock();
  3760. ImPlotContext& gp = *GImPlot;
  3761. ImRect rect = gp.CurrentPlot->PlotRect;
  3762. return ImGui::BeginDragDropTargetCustom(rect, gp.CurrentPlot->ID);
  3763. }
  3764. bool BeginDragDropTargetAxis(ImAxis axis) {
  3765. SetupLock();
  3766. ImPlotPlot& plot = *GImPlot->CurrentPlot;
  3767. ImPlotAxis& ax = plot.Axes[axis];
  3768. ImRect rect = ax.HoverRect;
  3769. rect.Expand(-3.5f);
  3770. return ImGui::BeginDragDropTargetCustom(rect, ax.ID);
  3771. }
  3772. bool BeginDragDropTargetLegend() {
  3773. SetupLock();
  3774. ImPlotItemGroup& items = *GImPlot->CurrentItems;
  3775. ImRect rect = items.Legend.Rect;
  3776. return ImGui::BeginDragDropTargetCustom(rect, items.ID);
  3777. }
  3778. void EndDragDropTarget() {
  3779. SetupLock();
  3780. ImGui::EndDragDropTarget();
  3781. }
  3782. bool BeginDragDropSourcePlot(ImGuiDragDropFlags flags) {
  3783. SetupLock();
  3784. ImPlotContext& gp = *GImPlot;
  3785. ImPlotPlot* plot = gp.CurrentPlot;
  3786. if (GImGui->IO.KeyMods == gp.InputMap.OverrideMod || GImGui->DragDropPayload.SourceId == plot->ID)
  3787. return ImGui::ItemAdd(plot->PlotRect, plot->ID) && ImGui::BeginDragDropSource(flags);
  3788. return false;
  3789. }
  3790. bool BeginDragDropSourceAxis(ImAxis idx, ImGuiDragDropFlags flags) {
  3791. SetupLock();
  3792. ImPlotContext& gp = *GImPlot;
  3793. ImPlotAxis& axis = gp.CurrentPlot->Axes[idx];
  3794. if (GImGui->IO.KeyMods == gp.InputMap.OverrideMod || GImGui->DragDropPayload.SourceId == axis.ID)
  3795. return ImGui::ItemAdd(axis.HoverRect, axis.ID) && ImGui::BeginDragDropSource(flags);
  3796. return false;
  3797. }
  3798. bool BeginDragDropSourceItem(const char* label_id, ImGuiDragDropFlags flags) {
  3799. SetupLock();
  3800. ImPlotContext& gp = *GImPlot;
  3801. IM_ASSERT_USER_ERROR(gp.CurrentItems != nullptr, "BeginDragDropSourceItem() needs to be called within an itemized context!");
  3802. ImGuiID item_id = ImGui::GetIDWithSeed(label_id, nullptr, gp.CurrentItems->ID);
  3803. ImPlotItem* item = gp.CurrentItems->GetItem(item_id);
  3804. if (item != nullptr) {
  3805. return ImGui::ItemAdd(item->LegendHoverRect, item->ID) && ImGui::BeginDragDropSource(flags);
  3806. }
  3807. return false;
  3808. }
  3809. void EndDragDropSource() {
  3810. SetupLock();
  3811. ImGui::EndDragDropSource();
  3812. }
  3813. //-----------------------------------------------------------------------------
  3814. // [SECTION] Aligned Plots
  3815. //-----------------------------------------------------------------------------
  3816. bool BeginAlignedPlots(const char* group_id, bool vertical) {
  3817. IM_ASSERT_USER_ERROR(GImPlot != nullptr, "No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?");
  3818. ImPlotContext& gp = *GImPlot;
  3819. IM_ASSERT_USER_ERROR(gp.CurrentAlignmentH == nullptr && gp.CurrentAlignmentV == nullptr, "Mismatched BeginAlignedPlots()/EndAlignedPlots()!");
  3820. ImGuiContext &G = *GImGui;
  3821. ImGuiWindow * Window = G.CurrentWindow;
  3822. if (Window->SkipItems)
  3823. return false;
  3824. const ImGuiID ID = Window->GetID(group_id);
  3825. ImPlotAlignmentData* alignment = gp.AlignmentData.GetOrAddByKey(ID);
  3826. if (vertical)
  3827. gp.CurrentAlignmentV = alignment;
  3828. else
  3829. gp.CurrentAlignmentH = alignment;
  3830. if (alignment->Vertical != vertical)
  3831. alignment->Reset();
  3832. alignment->Vertical = vertical;
  3833. alignment->Begin();
  3834. return true;
  3835. }
  3836. void EndAlignedPlots() {
  3837. IM_ASSERT_USER_ERROR(GImPlot != nullptr, "No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?");
  3838. ImPlotContext& gp = *GImPlot;
  3839. IM_ASSERT_USER_ERROR(gp.CurrentAlignmentH != nullptr || gp.CurrentAlignmentV != nullptr, "Mismatched BeginAlignedPlots()/EndAlignedPlots()!");
  3840. ImPlotAlignmentData* alignment = gp.CurrentAlignmentH != nullptr ? gp.CurrentAlignmentH : (gp.CurrentAlignmentV != nullptr ? gp.CurrentAlignmentV : nullptr);
  3841. if (alignment)
  3842. alignment->End();
  3843. ResetCtxForNextAlignedPlots(GImPlot);
  3844. }
  3845. //-----------------------------------------------------------------------------
  3846. // [SECTION] Plot and Item Styling
  3847. //-----------------------------------------------------------------------------
  3848. ImPlotStyle& GetStyle() {
  3849. IM_ASSERT_USER_ERROR(GImPlot != nullptr, "No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?");
  3850. ImPlotContext& gp = *GImPlot;
  3851. return gp.Style;
  3852. }
  3853. void PushStyleColor(ImPlotCol idx, ImU32 col) {
  3854. ImPlotContext& gp = *GImPlot;
  3855. ImGuiColorMod backup;
  3856. backup.Col = (ImGuiCol)idx;
  3857. backup.BackupValue = gp.Style.Colors[idx];
  3858. gp.ColorModifiers.push_back(backup);
  3859. gp.Style.Colors[idx] = ImGui::ColorConvertU32ToFloat4(col);
  3860. }
  3861. void PushStyleColor(ImPlotCol idx, const ImVec4& col) {
  3862. ImPlotContext& gp = *GImPlot;
  3863. ImGuiColorMod backup;
  3864. backup.Col = (ImGuiCol)idx;
  3865. backup.BackupValue = gp.Style.Colors[idx];
  3866. gp.ColorModifiers.push_back(backup);
  3867. gp.Style.Colors[idx] = col;
  3868. }
  3869. void PopStyleColor(int count) {
  3870. ImPlotContext& gp = *GImPlot;
  3871. IM_ASSERT_USER_ERROR(count <= gp.ColorModifiers.Size, "You can't pop more modifiers than have been pushed!");
  3872. while (count > 0)
  3873. {
  3874. ImGuiColorMod& backup = gp.ColorModifiers.back();
  3875. gp.Style.Colors[backup.Col] = backup.BackupValue;
  3876. gp.ColorModifiers.pop_back();
  3877. count--;
  3878. }
  3879. }
  3880. void PushStyleVar(ImPlotStyleVar idx, float val) {
  3881. ImPlotContext& gp = *GImPlot;
  3882. const ImPlotStyleVarInfo* var_info = GetPlotStyleVarInfo(idx);
  3883. if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) {
  3884. float* pvar = (float*)var_info->GetVarPtr(&gp.Style);
  3885. gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar));
  3886. *pvar = val;
  3887. return;
  3888. }
  3889. IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
  3890. }
  3891. void PushStyleVar(ImPlotStyleVar idx, int val) {
  3892. ImPlotContext& gp = *GImPlot;
  3893. const ImPlotStyleVarInfo* var_info = GetPlotStyleVarInfo(idx);
  3894. if (var_info->Type == ImGuiDataType_S32 && var_info->Count == 1) {
  3895. int* pvar = (int*)var_info->GetVarPtr(&gp.Style);
  3896. gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar));
  3897. *pvar = val;
  3898. return;
  3899. }
  3900. else if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) {
  3901. float* pvar = (float*)var_info->GetVarPtr(&gp.Style);
  3902. gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar));
  3903. *pvar = (float)val;
  3904. return;
  3905. }
  3906. IM_ASSERT(0 && "Called PushStyleVar() int variant but variable is not a int!");
  3907. }
  3908. void PushStyleVar(ImPlotStyleVar idx, const ImVec2& val)
  3909. {
  3910. ImPlotContext& gp = *GImPlot;
  3911. const ImPlotStyleVarInfo* var_info = GetPlotStyleVarInfo(idx);
  3912. if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
  3913. {
  3914. ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&gp.Style);
  3915. gp.StyleModifiers.push_back(ImGuiStyleMod((ImGuiStyleVar)idx, *pvar));
  3916. *pvar = val;
  3917. return;
  3918. }
  3919. IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
  3920. }
  3921. void PopStyleVar(int count) {
  3922. ImPlotContext& gp = *GImPlot;
  3923. IM_ASSERT_USER_ERROR(count <= gp.StyleModifiers.Size, "You can't pop more modifiers than have been pushed!");
  3924. while (count > 0) {
  3925. ImGuiStyleMod& backup = gp.StyleModifiers.back();
  3926. const ImPlotStyleVarInfo* info = GetPlotStyleVarInfo(backup.VarIdx);
  3927. void* data = info->GetVarPtr(&gp.Style);
  3928. if (info->Type == ImGuiDataType_Float && info->Count == 1) {
  3929. ((float*)data)[0] = backup.BackupFloat[0];
  3930. }
  3931. else if (info->Type == ImGuiDataType_Float && info->Count == 2) {
  3932. ((float*)data)[0] = backup.BackupFloat[0];
  3933. ((float*)data)[1] = backup.BackupFloat[1];
  3934. }
  3935. else if (info->Type == ImGuiDataType_S32 && info->Count == 1) {
  3936. ((int*)data)[0] = backup.BackupInt[0];
  3937. }
  3938. gp.StyleModifiers.pop_back();
  3939. count--;
  3940. }
  3941. }
  3942. //------------------------------------------------------------------------------
  3943. // [Section] Colormaps
  3944. //------------------------------------------------------------------------------
  3945. ImPlotColormap AddColormap(const char* name, const ImVec4* colormap, int size, bool qual) {
  3946. ImPlotContext& gp = *GImPlot;
  3947. IM_ASSERT_USER_ERROR(size > 1, "The colormap size must be greater than 1!");
  3948. IM_ASSERT_USER_ERROR(gp.ColormapData.GetIndex(name) == -1, "The colormap name has already been used!");
  3949. ImVector<ImU32> buffer;
  3950. buffer.resize(size);
  3951. for (int i = 0; i < size; ++i)
  3952. buffer[i] = ImGui::ColorConvertFloat4ToU32(colormap[i]);
  3953. return gp.ColormapData.Append(name, buffer.Data, size, qual);
  3954. }
  3955. ImPlotColormap AddColormap(const char* name, const ImU32* colormap, int size, bool qual) {
  3956. ImPlotContext& gp = *GImPlot;
  3957. IM_ASSERT_USER_ERROR(size > 1, "The colormap size must be greater than 1!");
  3958. IM_ASSERT_USER_ERROR(gp.ColormapData.GetIndex(name) == -1, "The colormap name has already be used!");
  3959. return gp.ColormapData.Append(name, colormap, size, qual);
  3960. }
  3961. int GetColormapCount() {
  3962. ImPlotContext& gp = *GImPlot;
  3963. return gp.ColormapData.Count;
  3964. }
  3965. const char* GetColormapName(ImPlotColormap colormap) {
  3966. ImPlotContext& gp = *GImPlot;
  3967. return gp.ColormapData.GetName(colormap);
  3968. }
  3969. ImPlotColormap GetColormapIndex(const char* name) {
  3970. ImPlotContext& gp = *GImPlot;
  3971. return gp.ColormapData.GetIndex(name);
  3972. }
  3973. void PushColormap(ImPlotColormap colormap) {
  3974. ImPlotContext& gp = *GImPlot;
  3975. IM_ASSERT_USER_ERROR(colormap >= 0 && colormap < gp.ColormapData.Count, "The colormap index is invalid!");
  3976. gp.ColormapModifiers.push_back(gp.Style.Colormap);
  3977. gp.Style.Colormap = colormap;
  3978. }
  3979. void PushColormap(const char* name) {
  3980. ImPlotContext& gp = *GImPlot;
  3981. ImPlotColormap idx = gp.ColormapData.GetIndex(name);
  3982. IM_ASSERT_USER_ERROR(idx != -1, "The colormap name is invalid!");
  3983. PushColormap(idx);
  3984. }
  3985. void PopColormap(int count) {
  3986. ImPlotContext& gp = *GImPlot;
  3987. IM_ASSERT_USER_ERROR(count <= gp.ColormapModifiers.Size, "You can't pop more modifiers than have been pushed!");
  3988. while (count > 0) {
  3989. const ImPlotColormap& backup = gp.ColormapModifiers.back();
  3990. gp.Style.Colormap = backup;
  3991. gp.ColormapModifiers.pop_back();
  3992. count--;
  3993. }
  3994. }
  3995. ImU32 NextColormapColorU32() {
  3996. ImPlotContext& gp = *GImPlot;
  3997. IM_ASSERT_USER_ERROR(gp.CurrentItems != nullptr, "NextColormapColor() needs to be called between BeginPlot() and EndPlot()!");
  3998. int idx = gp.CurrentItems->ColormapIdx % gp.ColormapData.GetKeyCount(gp.Style.Colormap);
  3999. ImU32 col = gp.ColormapData.GetKeyColor(gp.Style.Colormap, idx);
  4000. gp.CurrentItems->ColormapIdx++;
  4001. return col;
  4002. }
  4003. ImVec4 NextColormapColor() {
  4004. return ImGui::ColorConvertU32ToFloat4(NextColormapColorU32());
  4005. }
  4006. int GetColormapSize(ImPlotColormap cmap) {
  4007. ImPlotContext& gp = *GImPlot;
  4008. cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap;
  4009. IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!");
  4010. return gp.ColormapData.GetKeyCount(cmap);
  4011. }
  4012. ImU32 GetColormapColorU32(int idx, ImPlotColormap cmap) {
  4013. ImPlotContext& gp = *GImPlot;
  4014. cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap;
  4015. IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!");
  4016. idx = idx % gp.ColormapData.GetKeyCount(cmap);
  4017. return gp.ColormapData.GetKeyColor(cmap, idx);
  4018. }
  4019. ImVec4 GetColormapColor(int idx, ImPlotColormap cmap) {
  4020. return ImGui::ColorConvertU32ToFloat4(GetColormapColorU32(idx,cmap));
  4021. }
  4022. ImU32 SampleColormapU32(float t, ImPlotColormap cmap) {
  4023. ImPlotContext& gp = *GImPlot;
  4024. cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap;
  4025. IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!");
  4026. return gp.ColormapData.LerpTable(cmap, t);
  4027. }
  4028. ImVec4 SampleColormap(float t, ImPlotColormap cmap) {
  4029. return ImGui::ColorConvertU32ToFloat4(SampleColormapU32(t,cmap));
  4030. }
  4031. void RenderColorBar(const ImU32* colors, int size, ImDrawList& DrawList, const ImRect& bounds, bool vert, bool reversed, bool continuous) {
  4032. const int n = continuous ? size - 1 : size;
  4033. ImU32 col1, col2;
  4034. if (vert) {
  4035. const float step = bounds.GetHeight() / n;
  4036. ImRect rect(bounds.Min.x, bounds.Min.y, bounds.Max.x, bounds.Min.y + step);
  4037. for (int i = 0; i < n; ++i) {
  4038. if (reversed) {
  4039. col1 = colors[size-i-1];
  4040. col2 = continuous ? colors[size-i-2] : col1;
  4041. }
  4042. else {
  4043. col1 = colors[i];
  4044. col2 = continuous ? colors[i+1] : col1;
  4045. }
  4046. DrawList.AddRectFilledMultiColor(rect.Min, rect.Max, col1, col1, col2, col2);
  4047. rect.TranslateY(step);
  4048. }
  4049. }
  4050. else {
  4051. const float step = bounds.GetWidth() / n;
  4052. ImRect rect(bounds.Min.x, bounds.Min.y, bounds.Min.x + step, bounds.Max.y);
  4053. for (int i = 0; i < n; ++i) {
  4054. if (reversed) {
  4055. col1 = colors[size-i-1];
  4056. col2 = continuous ? colors[size-i-2] : col1;
  4057. }
  4058. else {
  4059. col1 = colors[i];
  4060. col2 = continuous ? colors[i+1] : col1;
  4061. }
  4062. DrawList.AddRectFilledMultiColor(rect.Min, rect.Max, col1, col2, col2, col1);
  4063. rect.TranslateX(step);
  4064. }
  4065. }
  4066. }
  4067. void ColormapScale(const char* label, double scale_min, double scale_max, const ImVec2& size, const char* format, ImPlotColormapScaleFlags flags, ImPlotColormap cmap) {
  4068. ImGuiContext &G = *GImGui;
  4069. ImGuiWindow * Window = G.CurrentWindow;
  4070. if (Window->SkipItems)
  4071. return;
  4072. const ImGuiID ID = Window->GetID(label);
  4073. ImVec2 label_size(0,0);
  4074. if (!ImHasFlag(flags, ImPlotColormapScaleFlags_NoLabel)) {
  4075. label_size = ImGui::CalcTextSize(label,nullptr,true);
  4076. }
  4077. ImPlotContext& gp = *GImPlot;
  4078. cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap;
  4079. IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!");
  4080. ImVec2 frame_size = ImGui::CalcItemSize(size, 0, gp.Style.PlotDefaultSize.y);
  4081. if (frame_size.y < gp.Style.PlotMinSize.y && size.y < 0.0f)
  4082. frame_size.y = gp.Style.PlotMinSize.y;
  4083. ImPlotRange range(ImMin(scale_min,scale_max), ImMax(scale_min,scale_max));
  4084. gp.CTicker.Reset();
  4085. Locator_Default(gp.CTicker, range, frame_size.y, true, Formatter_Default, (void*)format);
  4086. const bool rend_label = label_size.x > 0;
  4087. const float txt_off = gp.Style.LabelPadding.x;
  4088. const float pad = txt_off + gp.CTicker.MaxSize.x + (rend_label ? txt_off + label_size.y : 0);
  4089. float bar_w = 20;
  4090. if (frame_size.x == 0)
  4091. frame_size.x = bar_w + pad + 2 * gp.Style.PlotPadding.x;
  4092. else {
  4093. bar_w = frame_size.x - (pad + 2 * gp.Style.PlotPadding.x);
  4094. if (bar_w < gp.Style.MajorTickLen.y)
  4095. bar_w = gp.Style.MajorTickLen.y;
  4096. }
  4097. ImDrawList &DrawList = *Window->DrawList;
  4098. ImRect bb_frame = ImRect(Window->DC.CursorPos, Window->DC.CursorPos + frame_size);
  4099. ImGui::ItemSize(bb_frame);
  4100. if (!ImGui::ItemAdd(bb_frame, ID, &bb_frame))
  4101. return;
  4102. ImGui::RenderFrame(bb_frame.Min, bb_frame.Max, GetStyleColorU32(ImPlotCol_FrameBg), true, G.Style.FrameRounding);
  4103. const bool opposite = ImHasFlag(flags, ImPlotColormapScaleFlags_Opposite);
  4104. const bool inverted = ImHasFlag(flags, ImPlotColormapScaleFlags_Invert);
  4105. const bool reversed = scale_min > scale_max;
  4106. float bb_grad_shift = opposite ? pad : 0;
  4107. ImRect bb_grad(bb_frame.Min + gp.Style.PlotPadding + ImVec2(bb_grad_shift, 0),
  4108. bb_frame.Min + ImVec2(bar_w + gp.Style.PlotPadding.x + bb_grad_shift,
  4109. frame_size.y - gp.Style.PlotPadding.y));
  4110. ImGui::PushClipRect(bb_frame.Min, bb_frame.Max, true);
  4111. const ImU32 col_text = ImGui::GetColorU32(ImGuiCol_Text);
  4112. const bool invert_scale = inverted ? (reversed ? false : true) : (reversed ? true : false);
  4113. const float y_min = invert_scale ? bb_grad.Max.y : bb_grad.Min.y;
  4114. const float y_max = invert_scale ? bb_grad.Min.y : bb_grad.Max.y;
  4115. RenderColorBar(gp.ColormapData.GetKeys(cmap), gp.ColormapData.GetKeyCount(cmap), DrawList, bb_grad, true, !inverted, !gp.ColormapData.IsQual(cmap));
  4116. for (int i = 0; i < gp.CTicker.TickCount(); ++i) {
  4117. const double y_pos_plt = gp.CTicker.Ticks[i].PlotPos;
  4118. const float y_pos = ImRemap((float)y_pos_plt, (float)range.Max, (float)range.Min, y_min, y_max);
  4119. const float tick_width = gp.CTicker.Ticks[i].Major ? gp.Style.MajorTickLen.y : gp.Style.MinorTickLen.y;
  4120. const float tick_thick = gp.CTicker.Ticks[i].Major ? gp.Style.MajorTickSize.y : gp.Style.MinorTickSize.y;
  4121. const float tick_t = (float)((y_pos_plt - scale_min) / (scale_max - scale_min));
  4122. const ImU32 tick_col = CalcTextColor(gp.ColormapData.LerpTable(cmap,tick_t));
  4123. if (y_pos < bb_grad.Max.y - 2 && y_pos > bb_grad.Min.y + 2) {
  4124. DrawList.AddLine(opposite ? ImVec2(bb_grad.Min.x+1, y_pos) : ImVec2(bb_grad.Max.x-1, y_pos),
  4125. opposite ? ImVec2(bb_grad.Min.x + tick_width, y_pos) : ImVec2(bb_grad.Max.x - tick_width, y_pos),
  4126. tick_col,
  4127. tick_thick);
  4128. }
  4129. const float txt_x = opposite ? bb_grad.Min.x - txt_off - gp.CTicker.Ticks[i].LabelSize.x : bb_grad.Max.x + txt_off;
  4130. const float txt_y = y_pos - gp.CTicker.Ticks[i].LabelSize.y * 0.5f;
  4131. DrawList.AddText(ImVec2(txt_x, txt_y), col_text, gp.CTicker.GetText(i));
  4132. }
  4133. if (rend_label) {
  4134. const float pos_x = opposite ? bb_frame.Min.x + gp.Style.PlotPadding.x : bb_grad.Max.x + 2 * txt_off + gp.CTicker.MaxSize.x;
  4135. const float pos_y = bb_grad.GetCenter().y + label_size.x * 0.5f;
  4136. const char* label_end = ImGui::FindRenderedTextEnd(label);
  4137. AddTextVertical(&DrawList,ImVec2(pos_x,pos_y),col_text,label,label_end);
  4138. }
  4139. DrawList.AddRect(bb_grad.Min, bb_grad.Max, GetStyleColorU32(ImPlotCol_PlotBorder));
  4140. ImGui::PopClipRect();
  4141. }
  4142. bool ColormapSlider(const char* label, float* t, ImVec4* out, const char* format, ImPlotColormap cmap) {
  4143. *t = ImClamp(*t,0.0f,1.0f);
  4144. ImGuiContext &G = *GImGui;
  4145. ImGuiWindow * Window = G.CurrentWindow;
  4146. if (Window->SkipItems)
  4147. return false;
  4148. ImPlotContext& gp = *GImPlot;
  4149. cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap;
  4150. IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!");
  4151. const ImU32* keys = gp.ColormapData.GetKeys(cmap);
  4152. const int count = gp.ColormapData.GetKeyCount(cmap);
  4153. const bool qual = gp.ColormapData.IsQual(cmap);
  4154. const ImVec2 pos = ImGui::GetCurrentWindow()->DC.CursorPos;
  4155. const float w = ImGui::CalcItemWidth();
  4156. const float h = ImGui::GetFrameHeight();
  4157. const ImRect rect = ImRect(pos.x,pos.y,pos.x+w,pos.y+h);
  4158. RenderColorBar(keys,count,*ImGui::GetWindowDrawList(),rect,false,false,!qual);
  4159. const ImU32 grab = CalcTextColor(gp.ColormapData.LerpTable(cmap,*t));
  4160. // const ImU32 text = CalcTextColor(gp.ColormapData.LerpTable(cmap,0.5f));
  4161. ImGui::PushStyleColor(ImGuiCol_FrameBg,IM_COL32_BLACK_TRANS);
  4162. ImGui::PushStyleColor(ImGuiCol_FrameBgActive,IM_COL32_BLACK_TRANS);
  4163. ImGui::PushStyleColor(ImGuiCol_FrameBgHovered,ImVec4(1,1,1,0.1f));
  4164. ImGui::PushStyleColor(ImGuiCol_SliderGrab,grab);
  4165. ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, grab);
  4166. ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize,2);
  4167. ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding,0);
  4168. const bool changed = ImGui::SliderFloat(label,t,0,1,format);
  4169. ImGui::PopStyleColor(5);
  4170. ImGui::PopStyleVar(2);
  4171. if (out != nullptr)
  4172. *out = ImGui::ColorConvertU32ToFloat4(gp.ColormapData.LerpTable(cmap,*t));
  4173. return changed;
  4174. }
  4175. bool ColormapButton(const char* label, const ImVec2& size_arg, ImPlotColormap cmap) {
  4176. ImGuiContext &G = *GImGui;
  4177. const ImGuiStyle& style = G.Style;
  4178. ImGuiWindow * Window = G.CurrentWindow;
  4179. if (Window->SkipItems)
  4180. return false;
  4181. ImPlotContext& gp = *GImPlot;
  4182. cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap;
  4183. IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!");
  4184. const ImU32* keys = gp.ColormapData.GetKeys(cmap);
  4185. const int count = gp.ColormapData.GetKeyCount(cmap);
  4186. const bool qual = gp.ColormapData.IsQual(cmap);
  4187. const ImVec2 pos = ImGui::GetCurrentWindow()->DC.CursorPos;
  4188. const ImVec2 label_size = ImGui::CalcTextSize(label, nullptr, true);
  4189. ImVec2 size = ImGui::CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);
  4190. const ImRect rect = ImRect(pos.x,pos.y,pos.x+size.x,pos.y+size.y);
  4191. RenderColorBar(keys,count,*ImGui::GetWindowDrawList(),rect,false,false,!qual);
  4192. const ImU32 text = CalcTextColor(gp.ColormapData.LerpTable(cmap,G.Style.ButtonTextAlign.x));
  4193. ImGui::PushStyleColor(ImGuiCol_Button,IM_COL32_BLACK_TRANS);
  4194. ImGui::PushStyleColor(ImGuiCol_ButtonHovered,ImVec4(1,1,1,0.1f));
  4195. ImGui::PushStyleColor(ImGuiCol_ButtonActive,ImVec4(1,1,1,0.2f));
  4196. ImGui::PushStyleColor(ImGuiCol_Text,text);
  4197. ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding,0);
  4198. const bool pressed = ImGui::Button(label,size);
  4199. ImGui::PopStyleColor(4);
  4200. ImGui::PopStyleVar(1);
  4201. return pressed;
  4202. }
  4203. //-----------------------------------------------------------------------------
  4204. // [Section] Miscellaneous
  4205. //-----------------------------------------------------------------------------
  4206. ImPlotInputMap& GetInputMap() {
  4207. IM_ASSERT_USER_ERROR(GImPlot != nullptr, "No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?");
  4208. ImPlotContext& gp = *GImPlot;
  4209. return gp.InputMap;
  4210. }
  4211. void MapInputDefault(ImPlotInputMap* dst) {
  4212. ImPlotInputMap& map = dst ? *dst : GetInputMap();
  4213. map.Pan = ImGuiMouseButton_Left;
  4214. map.PanMod = ImGuiMod_None;
  4215. map.Fit = ImGuiMouseButton_Left;
  4216. map.Menu = ImGuiMouseButton_Right;
  4217. map.Select = ImGuiMouseButton_Right;
  4218. map.SelectMod = ImGuiMod_None;
  4219. map.SelectCancel = ImGuiMouseButton_Left;
  4220. map.SelectHorzMod = ImGuiMod_Alt;
  4221. map.SelectVertMod = ImGuiMod_Shift;
  4222. map.OverrideMod = ImGuiMod_Ctrl;
  4223. map.ZoomMod = ImGuiMod_None;
  4224. map.ZoomRate = 0.1f;
  4225. }
  4226. void MapInputReverse(ImPlotInputMap* dst) {
  4227. ImPlotInputMap& map = dst ? *dst : GetInputMap();
  4228. map.Pan = ImGuiMouseButton_Right;
  4229. map.PanMod = ImGuiMod_None;
  4230. map.Fit = ImGuiMouseButton_Left;
  4231. map.Menu = ImGuiMouseButton_Right;
  4232. map.Select = ImGuiMouseButton_Left;
  4233. map.SelectMod = ImGuiMod_None;
  4234. map.SelectCancel = ImGuiMouseButton_Right;
  4235. map.SelectHorzMod = ImGuiMod_Alt;
  4236. map.SelectVertMod = ImGuiMod_Shift;
  4237. map.OverrideMod = ImGuiMod_Ctrl;
  4238. map.ZoomMod = ImGuiMod_None;
  4239. map.ZoomRate = 0.1f;
  4240. }
  4241. //-----------------------------------------------------------------------------
  4242. // [Section] Miscellaneous
  4243. //-----------------------------------------------------------------------------
  4244. void ItemIcon(const ImVec4& col) {
  4245. ItemIcon(ImGui::ColorConvertFloat4ToU32(col));
  4246. }
  4247. void ItemIcon(ImU32 col) {
  4248. const float txt_size = ImGui::GetTextLineHeight();
  4249. ImVec2 size(txt_size-4,txt_size);
  4250. ImGuiWindow* window = ImGui::GetCurrentWindow();
  4251. ImVec2 pos = window->DC.CursorPos;
  4252. ImGui::GetWindowDrawList()->AddRectFilled(pos + ImVec2(0,2), pos + size - ImVec2(0,2), col);
  4253. ImGui::Dummy(size);
  4254. }
  4255. void ColormapIcon(ImPlotColormap cmap) {
  4256. ImPlotContext& gp = *GImPlot;
  4257. const float txt_size = ImGui::GetTextLineHeight();
  4258. ImVec2 size(txt_size-4,txt_size);
  4259. ImGuiWindow* window = ImGui::GetCurrentWindow();
  4260. ImVec2 pos = window->DC.CursorPos;
  4261. ImRect rect(pos+ImVec2(0,2),pos+size-ImVec2(0,2));
  4262. ImDrawList& DrawList = *ImGui::GetWindowDrawList();
  4263. RenderColorBar(gp.ColormapData.GetKeys(cmap),gp.ColormapData.GetKeyCount(cmap),DrawList,rect,false,false,!gp.ColormapData.IsQual(cmap));
  4264. ImGui::Dummy(size);
  4265. }
  4266. ImDrawList* GetPlotDrawList() {
  4267. return ImGui::GetWindowDrawList();
  4268. }
  4269. void PushPlotClipRect(float expand) {
  4270. ImPlotContext& gp = *GImPlot;
  4271. IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr, "PushPlotClipRect() needs to be called between BeginPlot() and EndPlot()!");
  4272. SetupLock();
  4273. ImRect rect = gp.CurrentPlot->PlotRect;
  4274. rect.Expand(expand);
  4275. ImGui::PushClipRect(rect.Min, rect.Max, true);
  4276. }
  4277. void PopPlotClipRect() {
  4278. SetupLock();
  4279. ImGui::PopClipRect();
  4280. }
  4281. static void HelpMarker(const char* desc) {
  4282. ImGui::TextDisabled("(?)");
  4283. if (ImGui::IsItemHovered()) {
  4284. ImGui::BeginTooltip();
  4285. ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
  4286. ImGui::TextUnformatted(desc);
  4287. ImGui::PopTextWrapPos();
  4288. ImGui::EndTooltip();
  4289. }
  4290. }
  4291. bool ShowStyleSelector(const char* label)
  4292. {
  4293. static int style_idx = -1;
  4294. if (ImGui::Combo(label, &style_idx, "Auto\0Classic\0Dark\0Light\0"))
  4295. {
  4296. switch (style_idx)
  4297. {
  4298. case 0: StyleColorsAuto(); break;
  4299. case 1: StyleColorsClassic(); break;
  4300. case 2: StyleColorsDark(); break;
  4301. case 3: StyleColorsLight(); break;
  4302. }
  4303. return true;
  4304. }
  4305. return false;
  4306. }
  4307. bool ShowColormapSelector(const char* label) {
  4308. ImPlotContext& gp = *GImPlot;
  4309. bool set = false;
  4310. if (ImGui::BeginCombo(label, gp.ColormapData.GetName(gp.Style.Colormap))) {
  4311. for (int i = 0; i < gp.ColormapData.Count; ++i) {
  4312. const char* name = gp.ColormapData.GetName(i);
  4313. if (ImGui::Selectable(name, gp.Style.Colormap == i)) {
  4314. gp.Style.Colormap = i;
  4315. ImPlot::BustItemCache();
  4316. set = true;
  4317. }
  4318. }
  4319. ImGui::EndCombo();
  4320. }
  4321. return set;
  4322. }
  4323. bool ShowInputMapSelector(const char* label) {
  4324. static int map_idx = -1;
  4325. if (ImGui::Combo(label, &map_idx, "Default\0Reversed\0"))
  4326. {
  4327. switch (map_idx)
  4328. {
  4329. case 0: MapInputDefault(); break;
  4330. case 1: MapInputReverse(); break;
  4331. }
  4332. return true;
  4333. }
  4334. return false;
  4335. }
  4336. void ShowStyleEditor(ImPlotStyle* ref) {
  4337. ImPlotContext& gp = *GImPlot;
  4338. ImPlotStyle& style = GetStyle();
  4339. static ImPlotStyle ref_saved_style;
  4340. // Default to using internal storage as reference
  4341. static bool init = true;
  4342. if (init && ref == nullptr)
  4343. ref_saved_style = style;
  4344. init = false;
  4345. if (ref == nullptr)
  4346. ref = &ref_saved_style;
  4347. if (ImPlot::ShowStyleSelector("Colors##Selector"))
  4348. ref_saved_style = style;
  4349. // Save/Revert button
  4350. if (ImGui::Button("Save Ref"))
  4351. *ref = ref_saved_style = style;
  4352. ImGui::SameLine();
  4353. if (ImGui::Button("Revert Ref"))
  4354. style = *ref;
  4355. ImGui::SameLine();
  4356. HelpMarker("Save/Revert in local non-persistent storage. Default Colors definition are not affected. "
  4357. "Use \"Export\" below to save them somewhere.");
  4358. if (ImGui::BeginTabBar("##StyleEditor")) {
  4359. if (ImGui::BeginTabItem("Variables")) {
  4360. ImGui::Text("Item Styling");
  4361. ImGui::SliderFloat("LineWeight", &style.LineWeight, 0.0f, 5.0f, "%.1f");
  4362. ImGui::SliderFloat("MarkerSize", &style.MarkerSize, 2.0f, 10.0f, "%.1f");
  4363. ImGui::SliderFloat("MarkerWeight", &style.MarkerWeight, 0.0f, 5.0f, "%.1f");
  4364. ImGui::SliderFloat("FillAlpha", &style.FillAlpha, 0.0f, 1.0f, "%.2f");
  4365. ImGui::SliderFloat("ErrorBarSize", &style.ErrorBarSize, 0.0f, 10.0f, "%.1f");
  4366. ImGui::SliderFloat("ErrorBarWeight", &style.ErrorBarWeight, 0.0f, 5.0f, "%.1f");
  4367. ImGui::SliderFloat("DigitalBitHeight", &style.DigitalBitHeight, 0.0f, 20.0f, "%.1f");
  4368. ImGui::SliderFloat("DigitalBitGap", &style.DigitalBitGap, 0.0f, 20.0f, "%.1f");
  4369. ImGui::Text("Plot Styling");
  4370. ImGui::SliderFloat("PlotBorderSize", &style.PlotBorderSize, 0.0f, 2.0f, "%.0f");
  4371. ImGui::SliderFloat("MinorAlpha", &style.MinorAlpha, 0.0f, 1.0f, "%.2f");
  4372. ImGui::SliderFloat2("MajorTickLen", (float*)&style.MajorTickLen, 0.0f, 20.0f, "%.0f");
  4373. ImGui::SliderFloat2("MinorTickLen", (float*)&style.MinorTickLen, 0.0f, 20.0f, "%.0f");
  4374. ImGui::SliderFloat2("MajorTickSize", (float*)&style.MajorTickSize, 0.0f, 2.0f, "%.1f");
  4375. ImGui::SliderFloat2("MinorTickSize", (float*)&style.MinorTickSize, 0.0f, 2.0f, "%.1f");
  4376. ImGui::SliderFloat2("MajorGridSize", (float*)&style.MajorGridSize, 0.0f, 2.0f, "%.1f");
  4377. ImGui::SliderFloat2("MinorGridSize", (float*)&style.MinorGridSize, 0.0f, 2.0f, "%.1f");
  4378. ImGui::SliderFloat2("PlotDefaultSize", (float*)&style.PlotDefaultSize, 0.0f, 1000, "%.0f");
  4379. ImGui::SliderFloat2("PlotMinSize", (float*)&style.PlotMinSize, 0.0f, 300, "%.0f");
  4380. ImGui::Text("Plot Padding");
  4381. ImGui::SliderFloat2("PlotPadding", (float*)&style.PlotPadding, 0.0f, 20.0f, "%.0f");
  4382. ImGui::SliderFloat2("LabelPadding", (float*)&style.LabelPadding, 0.0f, 20.0f, "%.0f");
  4383. ImGui::SliderFloat2("LegendPadding", (float*)&style.LegendPadding, 0.0f, 20.0f, "%.0f");
  4384. ImGui::SliderFloat2("LegendInnerPadding", (float*)&style.LegendInnerPadding, 0.0f, 10.0f, "%.0f");
  4385. ImGui::SliderFloat2("LegendSpacing", (float*)&style.LegendSpacing, 0.0f, 5.0f, "%.0f");
  4386. ImGui::SliderFloat2("MousePosPadding", (float*)&style.MousePosPadding, 0.0f, 20.0f, "%.0f");
  4387. ImGui::SliderFloat2("AnnotationPadding", (float*)&style.AnnotationPadding, 0.0f, 5.0f, "%.0f");
  4388. ImGui::SliderFloat2("FitPadding", (float*)&style.FitPadding, 0, 0.2f, "%.2f");
  4389. ImGui::EndTabItem();
  4390. }
  4391. if (ImGui::BeginTabItem("Colors")) {
  4392. static int output_dest = 0;
  4393. static bool output_only_modified = false;
  4394. if (ImGui::Button("Export", ImVec2(75,0))) {
  4395. if (output_dest == 0)
  4396. ImGui::LogToClipboard();
  4397. else
  4398. ImGui::LogToTTY();
  4399. ImGui::LogText("ImVec4* colors = ImPlot::GetStyle().Colors;\n");
  4400. for (int i = 0; i < ImPlotCol_COUNT; i++) {
  4401. const ImVec4& col = style.Colors[i];
  4402. const char* name = ImPlot::GetStyleColorName(i);
  4403. if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0) {
  4404. if (IsColorAuto(i))
  4405. ImGui::LogText("colors[ImPlotCol_%s]%*s= IMPLOT_AUTO_COL;\n",name,14 - (int)strlen(name), "");
  4406. else
  4407. ImGui::LogText("colors[ImPlotCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);\n",
  4408. name, 14 - (int)strlen(name), "", col.x, col.y, col.z, col.w);
  4409. }
  4410. }
  4411. ImGui::LogFinish();
  4412. }
  4413. ImGui::SameLine(); ImGui::SetNextItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0");
  4414. ImGui::SameLine(); ImGui::Checkbox("Only Modified Colors", &output_only_modified);
  4415. static ImGuiTextFilter filter;
  4416. filter.Draw("Filter colors", ImGui::GetFontSize() * 16);
  4417. static ImGuiColorEditFlags alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf;
  4418. if (ImGui::RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } ImGui::SameLine();
  4419. if (ImGui::RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_AlphaPreview)) { alpha_flags = ImGuiColorEditFlags_AlphaPreview; } ImGui::SameLine();
  4420. if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } ImGui::SameLine();
  4421. HelpMarker(
  4422. "In the color list:\n"
  4423. "Left-click on colored square to open color picker,\n"
  4424. "Right-click to open edit options menu.");
  4425. ImGui::Separator();
  4426. ImGui::PushItemWidth(-160);
  4427. for (int i = 0; i < ImPlotCol_COUNT; i++) {
  4428. const char* name = ImPlot::GetStyleColorName(i);
  4429. if (!filter.PassFilter(name))
  4430. continue;
  4431. ImGui::PushID(i);
  4432. ImVec4 temp = GetStyleColorVec4(i);
  4433. const bool is_auto = IsColorAuto(i);
  4434. if (!is_auto)
  4435. ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.25f);
  4436. if (ImGui::Button("Auto")) {
  4437. if (is_auto)
  4438. style.Colors[i] = temp;
  4439. else
  4440. style.Colors[i] = IMPLOT_AUTO_COL;
  4441. BustItemCache();
  4442. }
  4443. if (!is_auto)
  4444. ImGui::PopStyleVar();
  4445. ImGui::SameLine();
  4446. if (ImGui::ColorEdit4(name, &temp.x, ImGuiColorEditFlags_NoInputs | alpha_flags)) {
  4447. style.Colors[i] = temp;
  4448. BustItemCache();
  4449. }
  4450. if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0) {
  4451. ImGui::SameLine(175); if (ImGui::Button("Save")) { ref->Colors[i] = style.Colors[i]; }
  4452. ImGui::SameLine(); if (ImGui::Button("Revert")) {
  4453. style.Colors[i] = ref->Colors[i];
  4454. BustItemCache();
  4455. }
  4456. }
  4457. ImGui::PopID();
  4458. }
  4459. ImGui::PopItemWidth();
  4460. ImGui::Separator();
  4461. ImGui::Text("Colors that are set to Auto (i.e. IMPLOT_AUTO_COL) will\n"
  4462. "be automatically deduced from your ImGui style or the\n"
  4463. "current ImPlot Colormap. If you want to style individual\n"
  4464. "plot items, use Push/PopStyleColor around its function.");
  4465. ImGui::EndTabItem();
  4466. }
  4467. if (ImGui::BeginTabItem("Colormaps")) {
  4468. static int output_dest = 0;
  4469. if (ImGui::Button("Export", ImVec2(75,0))) {
  4470. if (output_dest == 0)
  4471. ImGui::LogToClipboard();
  4472. else
  4473. ImGui::LogToTTY();
  4474. int size = GetColormapSize();
  4475. const char* name = GetColormapName(gp.Style.Colormap);
  4476. ImGui::LogText("static const ImU32 %s_Data[%d] = {\n", name, size);
  4477. for (int i = 0; i < size; ++i) {
  4478. ImU32 col = GetColormapColorU32(i,gp.Style.Colormap);
  4479. ImGui::LogText(" %u%s\n", col, i == size - 1 ? "" : ",");
  4480. }
  4481. ImGui::LogText("};\nImPlotColormap %s = ImPlot::AddColormap(\"%s\", %s_Data, %d);", name, name, name, size);
  4482. ImGui::LogFinish();
  4483. }
  4484. ImGui::SameLine(); ImGui::SetNextItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0");
  4485. ImGui::SameLine();
  4486. static bool edit = false;
  4487. ImGui::Checkbox("Edit Mode",&edit);
  4488. // built-in/added
  4489. ImGui::Separator();
  4490. for (int i = 0; i < gp.ColormapData.Count; ++i) {
  4491. ImGui::PushID(i);
  4492. int size = gp.ColormapData.GetKeyCount(i);
  4493. bool selected = i == gp.Style.Colormap;
  4494. const char* name = GetColormapName(i);
  4495. if (!selected)
  4496. ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.25f);
  4497. if (ImGui::Button(name, ImVec2(100,0))) {
  4498. gp.Style.Colormap = i;
  4499. BustItemCache();
  4500. }
  4501. if (!selected)
  4502. ImGui::PopStyleVar();
  4503. ImGui::SameLine();
  4504. ImGui::BeginGroup();
  4505. if (edit) {
  4506. for (int c = 0; c < size; ++c) {
  4507. ImGui::PushID(c);
  4508. ImVec4 col4 = ImGui::ColorConvertU32ToFloat4(gp.ColormapData.GetKeyColor(i,c));
  4509. if (ImGui::ColorEdit4("",&col4.x,ImGuiColorEditFlags_NoInputs)) {
  4510. ImU32 col32 = ImGui::ColorConvertFloat4ToU32(col4);
  4511. gp.ColormapData.SetKeyColor(i,c,col32);
  4512. BustItemCache();
  4513. }
  4514. if ((c + 1) % 12 != 0 && c != size -1)
  4515. ImGui::SameLine();
  4516. ImGui::PopID();
  4517. }
  4518. }
  4519. else {
  4520. if (ImPlot::ColormapButton("##",ImVec2(-1,0),i))
  4521. edit = true;
  4522. }
  4523. ImGui::EndGroup();
  4524. ImGui::PopID();
  4525. }
  4526. static ImVector<ImVec4> custom;
  4527. if (custom.Size == 0) {
  4528. custom.push_back(ImVec4(1,0,0,1));
  4529. custom.push_back(ImVec4(0,1,0,1));
  4530. custom.push_back(ImVec4(0,0,1,1));
  4531. }
  4532. ImGui::Separator();
  4533. ImGui::BeginGroup();
  4534. static char name[16] = "MyColormap";
  4535. if (ImGui::Button("+", ImVec2((100 - ImGui::GetStyle().ItemSpacing.x)/2,0)))
  4536. custom.push_back(ImVec4(0,0,0,1));
  4537. ImGui::SameLine();
  4538. if (ImGui::Button("-", ImVec2((100 - ImGui::GetStyle().ItemSpacing.x)/2,0)) && custom.Size > 2)
  4539. custom.pop_back();
  4540. ImGui::SetNextItemWidth(100);
  4541. ImGui::InputText("##Name",name,16,ImGuiInputTextFlags_CharsNoBlank);
  4542. static bool qual = true;
  4543. ImGui::Checkbox("Qualitative",&qual);
  4544. if (ImGui::Button("Add", ImVec2(100, 0)) && gp.ColormapData.GetIndex(name)==-1)
  4545. AddColormap(name,custom.Data,custom.Size,qual);
  4546. ImGui::EndGroup();
  4547. ImGui::SameLine();
  4548. ImGui::BeginGroup();
  4549. for (int c = 0; c < custom.Size; ++c) {
  4550. ImGui::PushID(c);
  4551. if (ImGui::ColorEdit4("##Col1", &custom[c].x, ImGuiColorEditFlags_NoInputs)) {
  4552. }
  4553. if ((c + 1) % 12 != 0)
  4554. ImGui::SameLine();
  4555. ImGui::PopID();
  4556. }
  4557. ImGui::EndGroup();
  4558. ImGui::EndTabItem();
  4559. }
  4560. ImGui::EndTabBar();
  4561. }
  4562. }
  4563. void ShowUserGuide() {
  4564. ImGui::BulletText("Left-click drag within the plot area to pan X and Y axes.");
  4565. ImGui::Indent();
  4566. ImGui::BulletText("Left-click drag on axis labels to pan an individual axis.");
  4567. ImGui::Unindent();
  4568. ImGui::BulletText("Scroll in the plot area to zoom both X any Y axes.");
  4569. ImGui::Indent();
  4570. ImGui::BulletText("Scroll on axis labels to zoom an individual axis.");
  4571. ImGui::Unindent();
  4572. ImGui::BulletText("Right-click drag to box select data.");
  4573. ImGui::Indent();
  4574. ImGui::BulletText("Hold Alt to expand box selection horizontally.");
  4575. ImGui::BulletText("Hold Shift to expand box selection vertically.");
  4576. ImGui::BulletText("Left-click while box selecting to cancel the selection.");
  4577. ImGui::Unindent();
  4578. ImGui::BulletText("Double left-click to fit all visible data.");
  4579. ImGui::Indent();
  4580. ImGui::BulletText("Double left-click axis labels to fit the individual axis.");
  4581. ImGui::Unindent();
  4582. ImGui::BulletText("Right-click open the full plot context menu.");
  4583. ImGui::Indent();
  4584. ImGui::BulletText("Right-click axis labels to open an individual axis context menu.");
  4585. ImGui::Unindent();
  4586. ImGui::BulletText("Click legend label icons to show/hide plot items.");
  4587. }
  4588. void ShowTicksMetrics(const ImPlotTicker& ticker) {
  4589. ImGui::BulletText("Size: %d", ticker.TickCount());
  4590. ImGui::BulletText("MaxSize: [%f,%f]", ticker.MaxSize.x, ticker.MaxSize.y);
  4591. }
  4592. void ShowAxisMetrics(const ImPlotPlot& plot, const ImPlotAxis& axis) {
  4593. ImGui::BulletText("Label: %s", axis.LabelOffset == -1 ? "[none]" : plot.GetAxisLabel(axis));
  4594. ImGui::BulletText("Flags: 0x%08X", axis.Flags);
  4595. ImGui::BulletText("Range: [%f,%f]",axis.Range.Min, axis.Range.Max);
  4596. ImGui::BulletText("Pixels: %f", axis.PixelSize());
  4597. ImGui::BulletText("Aspect: %f", axis.GetAspect());
  4598. ImGui::BulletText(axis.OrthoAxis == nullptr ? "OrtherAxis: NULL" : "OrthoAxis: 0x%08X", axis.OrthoAxis->ID);
  4599. ImGui::BulletText("LinkedMin: %p", (void*)axis.LinkedMin);
  4600. ImGui::BulletText("LinkedMax: %p", (void*)axis.LinkedMax);
  4601. ImGui::BulletText("HasRange: %s", axis.HasRange ? "true" : "false");
  4602. ImGui::BulletText("Hovered: %s", axis.Hovered ? "true" : "false");
  4603. ImGui::BulletText("Held: %s", axis.Held ? "true" : "false");
  4604. if (ImGui::TreeNode("Transform")) {
  4605. ImGui::BulletText("PixelMin: %f", axis.PixelMin);
  4606. ImGui::BulletText("PixelMax: %f", axis.PixelMax);
  4607. ImGui::BulletText("ScaleToPixel: %f", axis.ScaleToPixel);
  4608. ImGui::BulletText("ScaleMax: %f", axis.ScaleMax);
  4609. ImGui::TreePop();
  4610. }
  4611. if (ImGui::TreeNode("Ticks")) {
  4612. ShowTicksMetrics(axis.Ticker);
  4613. ImGui::TreePop();
  4614. }
  4615. }
  4616. void ShowMetricsWindow(bool* p_popen) {
  4617. static bool show_plot_rects = false;
  4618. static bool show_axes_rects = false;
  4619. static bool show_axis_rects = false;
  4620. static bool show_canvas_rects = false;
  4621. static bool show_frame_rects = false;
  4622. static bool show_subplot_frame_rects = false;
  4623. static bool show_subplot_grid_rects = false;
  4624. ImDrawList& fg = *ImGui::GetForegroundDrawList();
  4625. ImPlotContext& gp = *GImPlot;
  4626. // ImGuiContext& g = *GImGui;
  4627. ImGuiIO& io = ImGui::GetIO();
  4628. ImGui::Begin("ImPlot Metrics", p_popen);
  4629. ImGui::Text("ImPlot " IMPLOT_VERSION);
  4630. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  4631. ImGui::Text("Mouse Position: [%.0f,%.0f]", io.MousePos.x, io.MousePos.y);
  4632. ImGui::Separator();
  4633. if (ImGui::TreeNode("Tools")) {
  4634. if (ImGui::Button("Bust Plot Cache"))
  4635. BustPlotCache();
  4636. ImGui::SameLine();
  4637. if (ImGui::Button("Bust Item Cache"))
  4638. BustItemCache();
  4639. ImGui::Checkbox("Show Frame Rects", &show_frame_rects);
  4640. ImGui::Checkbox("Show Canvas Rects",&show_canvas_rects);
  4641. ImGui::Checkbox("Show Plot Rects", &show_plot_rects);
  4642. ImGui::Checkbox("Show Axes Rects", &show_axes_rects);
  4643. ImGui::Checkbox("Show Axis Rects", &show_axis_rects);
  4644. ImGui::Checkbox("Show Subplot Frame Rects", &show_subplot_frame_rects);
  4645. ImGui::Checkbox("Show Subplot Grid Rects", &show_subplot_grid_rects);
  4646. ImGui::TreePop();
  4647. }
  4648. const int n_plots = gp.Plots.GetBufSize();
  4649. const int n_subplots = gp.Subplots.GetBufSize();
  4650. // render rects
  4651. for (int p = 0; p < n_plots; ++p) {
  4652. ImPlotPlot* plot = gp.Plots.GetByIndex(p);
  4653. if (show_frame_rects)
  4654. fg.AddRect(plot->FrameRect.Min, plot->FrameRect.Max, IM_COL32(255,0,255,255));
  4655. if (show_canvas_rects)
  4656. fg.AddRect(plot->CanvasRect.Min, plot->CanvasRect.Max, IM_COL32(0,255,255,255));
  4657. if (show_plot_rects)
  4658. fg.AddRect(plot->PlotRect.Min, plot->PlotRect.Max, IM_COL32(255,255,0,255));
  4659. if (show_axes_rects)
  4660. fg.AddRect(plot->AxesRect.Min, plot->AxesRect.Max, IM_COL32(0,255,128,255));
  4661. if (show_axis_rects) {
  4662. for (int i = 0; i < ImAxis_COUNT; ++i) {
  4663. if (plot->Axes[i].Enabled)
  4664. fg.AddRect(plot->Axes[i].HoverRect.Min, plot->Axes[i].HoverRect.Max, IM_COL32(0,255,0,255));
  4665. }
  4666. }
  4667. }
  4668. for (int p = 0; p < n_subplots; ++p) {
  4669. ImPlotSubplot* subplot = gp.Subplots.GetByIndex(p);
  4670. if (show_subplot_frame_rects)
  4671. fg.AddRect(subplot->FrameRect.Min, subplot->FrameRect.Max, IM_COL32(255,0,0,255));
  4672. if (show_subplot_grid_rects)
  4673. fg.AddRect(subplot->GridRect.Min, subplot->GridRect.Max, IM_COL32(0,0,255,255));
  4674. }
  4675. if (ImGui::TreeNode("Plots","Plots (%d)", n_plots)) {
  4676. for (int p = 0; p < n_plots; ++p) {
  4677. // plot
  4678. ImPlotPlot& plot = *gp.Plots.GetByIndex(p);
  4679. ImGui::PushID(p);
  4680. if (ImGui::TreeNode("Plot", "Plot [0x%08X]", plot.ID)) {
  4681. int n_items = plot.Items.GetItemCount();
  4682. if (ImGui::TreeNode("Items", "Items (%d)", n_items)) {
  4683. for (int i = 0; i < n_items; ++i) {
  4684. ImPlotItem* item = plot.Items.GetItemByIndex(i);
  4685. ImGui::PushID(i);
  4686. if (ImGui::TreeNode("Item", "Item [0x%08X]", item->ID)) {
  4687. ImGui::Bullet(); ImGui::Checkbox("Show", &item->Show);
  4688. ImGui::Bullet();
  4689. ImVec4 temp = ImGui::ColorConvertU32ToFloat4(item->Color);
  4690. if (ImGui::ColorEdit4("Color",&temp.x, ImGuiColorEditFlags_NoInputs))
  4691. item->Color = ImGui::ColorConvertFloat4ToU32(temp);
  4692. ImGui::BulletText("NameOffset: %d",item->NameOffset);
  4693. ImGui::BulletText("Name: %s", item->NameOffset != -1 ? plot.Items.Legend.Labels.Buf.Data + item->NameOffset : "N/A");
  4694. ImGui::BulletText("Hovered: %s",item->LegendHovered ? "true" : "false");
  4695. ImGui::TreePop();
  4696. }
  4697. ImGui::PopID();
  4698. }
  4699. ImGui::TreePop();
  4700. }
  4701. char buff[16];
  4702. for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i) {
  4703. ImFormatString(buff,16,"X-Axis %d", i+1);
  4704. if (plot.XAxis(i).Enabled && ImGui::TreeNode(buff, "X-Axis %d [0x%08X]", i+1, plot.XAxis(i).ID)) {
  4705. ShowAxisMetrics(plot, plot.XAxis(i));
  4706. ImGui::TreePop();
  4707. }
  4708. }
  4709. for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i) {
  4710. ImFormatString(buff,16,"Y-Axis %d", i+1);
  4711. if (plot.YAxis(i).Enabled && ImGui::TreeNode(buff, "Y-Axis %d [0x%08X]", i+1, plot.YAxis(i).ID)) {
  4712. ShowAxisMetrics(plot, plot.YAxis(i));
  4713. ImGui::TreePop();
  4714. }
  4715. }
  4716. ImGui::BulletText("Title: %s", plot.HasTitle() ? plot.GetTitle() : "none");
  4717. ImGui::BulletText("Flags: 0x%08X", plot.Flags);
  4718. ImGui::BulletText("Initialized: %s", plot.Initialized ? "true" : "false");
  4719. ImGui::BulletText("Selecting: %s", plot.Selecting ? "true" : "false");
  4720. ImGui::BulletText("Selected: %s", plot.Selected ? "true" : "false");
  4721. ImGui::BulletText("Hovered: %s", plot.Hovered ? "true" : "false");
  4722. ImGui::BulletText("Held: %s", plot.Held ? "true" : "false");
  4723. ImGui::BulletText("LegendHovered: %s", plot.Items.Legend.Hovered ? "true" : "false");
  4724. ImGui::BulletText("ContextLocked: %s", plot.ContextLocked ? "true" : "false");
  4725. ImGui::TreePop();
  4726. }
  4727. ImGui::PopID();
  4728. }
  4729. ImGui::TreePop();
  4730. }
  4731. if (ImGui::TreeNode("Subplots","Subplots (%d)", n_subplots)) {
  4732. for (int p = 0; p < n_subplots; ++p) {
  4733. // plot
  4734. ImPlotSubplot& plot = *gp.Subplots.GetByIndex(p);
  4735. ImGui::PushID(p);
  4736. if (ImGui::TreeNode("Subplot", "Subplot [0x%08X]", plot.ID)) {
  4737. int n_items = plot.Items.GetItemCount();
  4738. if (ImGui::TreeNode("Items", "Items (%d)", n_items)) {
  4739. for (int i = 0; i < n_items; ++i) {
  4740. ImPlotItem* item = plot.Items.GetItemByIndex(i);
  4741. ImGui::PushID(i);
  4742. if (ImGui::TreeNode("Item", "Item [0x%08X]", item->ID)) {
  4743. ImGui::Bullet(); ImGui::Checkbox("Show", &item->Show);
  4744. ImGui::Bullet();
  4745. ImVec4 temp = ImGui::ColorConvertU32ToFloat4(item->Color);
  4746. if (ImGui::ColorEdit4("Color",&temp.x, ImGuiColorEditFlags_NoInputs))
  4747. item->Color = ImGui::ColorConvertFloat4ToU32(temp);
  4748. ImGui::BulletText("NameOffset: %d",item->NameOffset);
  4749. ImGui::BulletText("Name: %s", item->NameOffset != -1 ? plot.Items.Legend.Labels.Buf.Data + item->NameOffset : "N/A");
  4750. ImGui::BulletText("Hovered: %s",item->LegendHovered ? "true" : "false");
  4751. ImGui::TreePop();
  4752. }
  4753. ImGui::PopID();
  4754. }
  4755. ImGui::TreePop();
  4756. }
  4757. ImGui::BulletText("Flags: 0x%08X", plot.Flags);
  4758. ImGui::BulletText("FrameHovered: %s", plot.FrameHovered ? "true" : "false");
  4759. ImGui::BulletText("LegendHovered: %s", plot.Items.Legend.Hovered ? "true" : "false");
  4760. ImGui::TreePop();
  4761. }
  4762. ImGui::PopID();
  4763. }
  4764. ImGui::TreePop();
  4765. }
  4766. if (ImGui::TreeNode("Colormaps")) {
  4767. ImGui::BulletText("Colormaps: %d", gp.ColormapData.Count);
  4768. ImGui::BulletText("Memory: %d bytes", gp.ColormapData.Tables.Size * 4);
  4769. if (ImGui::TreeNode("Data")) {
  4770. for (int m = 0; m < gp.ColormapData.Count; ++m) {
  4771. if (ImGui::TreeNode(gp.ColormapData.GetName(m))) {
  4772. int count = gp.ColormapData.GetKeyCount(m);
  4773. int size = gp.ColormapData.GetTableSize(m);
  4774. bool qual = gp.ColormapData.IsQual(m);
  4775. ImGui::BulletText("Qualitative: %s", qual ? "true" : "false");
  4776. ImGui::BulletText("Key Count: %d", count);
  4777. ImGui::BulletText("Table Size: %d", size);
  4778. ImGui::Indent();
  4779. static float t = 0.5;
  4780. ImVec4 samp;
  4781. float wid = 32 * 10 - ImGui::GetFrameHeight() - ImGui::GetStyle().ItemSpacing.x;
  4782. ImGui::SetNextItemWidth(wid);
  4783. ImPlot::ColormapSlider("##Sample",&t,&samp,"%.3f",m);
  4784. ImGui::SameLine();
  4785. ImGui::ColorButton("Sampler",samp);
  4786. ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0,0,0,0));
  4787. ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0));
  4788. for (int c = 0; c < size; ++c) {
  4789. ImVec4 col = ImGui::ColorConvertU32ToFloat4(gp.ColormapData.GetTableColor(m,c));
  4790. ImGui::PushID(m*1000+c);
  4791. ImGui::ColorButton("",col,0,ImVec2(10,10));
  4792. ImGui::PopID();
  4793. if ((c + 1) % 32 != 0 && c != size - 1)
  4794. ImGui::SameLine();
  4795. }
  4796. ImGui::PopStyleVar();
  4797. ImGui::PopStyleColor();
  4798. ImGui::Unindent();
  4799. ImGui::TreePop();
  4800. }
  4801. }
  4802. ImGui::TreePop();
  4803. }
  4804. ImGui::TreePop();
  4805. }
  4806. ImGui::End();
  4807. }
  4808. bool ShowDatePicker(const char* id, int* level, ImPlotTime* t, const ImPlotTime* t1, const ImPlotTime* t2) {
  4809. ImGui::PushID(id);
  4810. ImGui::BeginGroup();
  4811. ImGuiStyle& style = ImGui::GetStyle();
  4812. ImVec4 col_txt = style.Colors[ImGuiCol_Text];
  4813. ImVec4 col_dis = style.Colors[ImGuiCol_TextDisabled];
  4814. ImVec4 col_btn = style.Colors[ImGuiCol_Button];
  4815. ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0,0,0,0));
  4816. ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0));
  4817. const float ht = ImGui::GetFrameHeight();
  4818. ImVec2 cell_size(ht*1.25f,ht);
  4819. char buff[32];
  4820. bool clk = false;
  4821. tm& Tm = GImPlot->Tm;
  4822. const int min_yr = 1970;
  4823. const int max_yr = 2999;
  4824. // t1 parts
  4825. int t1_mo = 0; int t1_md = 0; int t1_yr = 0;
  4826. if (t1 != nullptr) {
  4827. GetTime(*t1,&Tm);
  4828. t1_mo = Tm.tm_mon;
  4829. t1_md = Tm.tm_mday;
  4830. t1_yr = Tm.tm_year + 1900;
  4831. }
  4832. // t2 parts
  4833. int t2_mo = 0; int t2_md = 0; int t2_yr = 0;
  4834. if (t2 != nullptr) {
  4835. GetTime(*t2,&Tm);
  4836. t2_mo = Tm.tm_mon;
  4837. t2_md = Tm.tm_mday;
  4838. t2_yr = Tm.tm_year + 1900;
  4839. }
  4840. // day widget
  4841. if (*level == 0) {
  4842. *t = FloorTime(*t, ImPlotTimeUnit_Day);
  4843. GetTime(*t, &Tm);
  4844. const int this_year = Tm.tm_year + 1900;
  4845. const int last_year = this_year - 1;
  4846. const int next_year = this_year + 1;
  4847. const int this_mon = Tm.tm_mon;
  4848. const int last_mon = this_mon == 0 ? 11 : this_mon - 1;
  4849. const int next_mon = this_mon == 11 ? 0 : this_mon + 1;
  4850. const int days_this_mo = GetDaysInMonth(this_year, this_mon);
  4851. const int days_last_mo = GetDaysInMonth(this_mon == 0 ? last_year : this_year, last_mon);
  4852. ImPlotTime t_first_mo = FloorTime(*t,ImPlotTimeUnit_Mo);
  4853. GetTime(t_first_mo,&Tm);
  4854. const int first_wd = Tm.tm_wday;
  4855. // month year
  4856. ImFormatString(buff, 32, "%s %d", MONTH_NAMES[this_mon], this_year);
  4857. if (ImGui::Button(buff))
  4858. *level = 1;
  4859. ImGui::SameLine(5*cell_size.x);
  4860. BeginDisabledControls(this_year <= min_yr && this_mon == 0);
  4861. if (ImGui::ArrowButtonEx("##Up",ImGuiDir_Up,cell_size))
  4862. *t = AddTime(*t, ImPlotTimeUnit_Mo, -1);
  4863. EndDisabledControls(this_year <= min_yr && this_mon == 0);
  4864. ImGui::SameLine();
  4865. BeginDisabledControls(this_year >= max_yr && this_mon == 11);
  4866. if (ImGui::ArrowButtonEx("##Down",ImGuiDir_Down,cell_size))
  4867. *t = AddTime(*t, ImPlotTimeUnit_Mo, 1);
  4868. EndDisabledControls(this_year >= max_yr && this_mon == 11);
  4869. // render weekday abbreviations
  4870. ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);
  4871. for (int i = 0; i < 7; ++i) {
  4872. ImGui::Button(WD_ABRVS[i],cell_size);
  4873. if (i != 6) { ImGui::SameLine(); }
  4874. }
  4875. ImGui::PopItemFlag();
  4876. // 0 = last mo, 1 = this mo, 2 = next mo
  4877. int mo = first_wd > 0 ? 0 : 1;
  4878. int day = mo == 1 ? 1 : days_last_mo - first_wd + 1;
  4879. for (int i = 0; i < 6; ++i) {
  4880. for (int j = 0; j < 7; ++j) {
  4881. if (mo == 0 && day > days_last_mo) {
  4882. mo = 1;
  4883. day = 1;
  4884. }
  4885. else if (mo == 1 && day > days_this_mo) {
  4886. mo = 2;
  4887. day = 1;
  4888. }
  4889. const int now_yr = (mo == 0 && this_mon == 0) ? last_year : ((mo == 2 && this_mon == 11) ? next_year : this_year);
  4890. const int now_mo = mo == 0 ? last_mon : (mo == 1 ? this_mon : next_mon);
  4891. const int now_md = day;
  4892. const bool off_mo = mo == 0 || mo == 2;
  4893. const bool t1_or_t2 = (t1 != nullptr && t1_mo == now_mo && t1_yr == now_yr && t1_md == now_md) ||
  4894. (t2 != nullptr && t2_mo == now_mo && t2_yr == now_yr && t2_md == now_md);
  4895. if (off_mo)
  4896. ImGui::PushStyleColor(ImGuiCol_Text, col_dis);
  4897. if (t1_or_t2) {
  4898. ImGui::PushStyleColor(ImGuiCol_Button, col_btn);
  4899. ImGui::PushStyleColor(ImGuiCol_Text, col_txt);
  4900. }
  4901. ImGui::PushID(i*7+j);
  4902. ImFormatString(buff,32,"%d",day);
  4903. if (now_yr == min_yr-1 || now_yr == max_yr+1) {
  4904. ImGui::Dummy(cell_size);
  4905. }
  4906. else if (ImGui::Button(buff,cell_size) && !clk) {
  4907. *t = MakeTime(now_yr, now_mo, now_md);
  4908. clk = true;
  4909. }
  4910. ImGui::PopID();
  4911. if (t1_or_t2)
  4912. ImGui::PopStyleColor(2);
  4913. if (off_mo)
  4914. ImGui::PopStyleColor();
  4915. if (j != 6)
  4916. ImGui::SameLine();
  4917. day++;
  4918. }
  4919. }
  4920. }
  4921. // month widget
  4922. else if (*level == 1) {
  4923. *t = FloorTime(*t, ImPlotTimeUnit_Mo);
  4924. GetTime(*t, &Tm);
  4925. int this_yr = Tm.tm_year + 1900;
  4926. ImFormatString(buff, 32, "%d", this_yr);
  4927. if (ImGui::Button(buff))
  4928. *level = 2;
  4929. BeginDisabledControls(this_yr <= min_yr);
  4930. ImGui::SameLine(5*cell_size.x);
  4931. if (ImGui::ArrowButtonEx("##Up",ImGuiDir_Up,cell_size))
  4932. *t = AddTime(*t, ImPlotTimeUnit_Yr, -1);
  4933. EndDisabledControls(this_yr <= min_yr);
  4934. ImGui::SameLine();
  4935. BeginDisabledControls(this_yr >= max_yr);
  4936. if (ImGui::ArrowButtonEx("##Down",ImGuiDir_Down,cell_size))
  4937. *t = AddTime(*t, ImPlotTimeUnit_Yr, 1);
  4938. EndDisabledControls(this_yr >= max_yr);
  4939. // ImGui::Dummy(cell_size);
  4940. cell_size.x *= 7.0f/4.0f;
  4941. cell_size.y *= 7.0f/3.0f;
  4942. int mo = 0;
  4943. for (int i = 0; i < 3; ++i) {
  4944. for (int j = 0; j < 4; ++j) {
  4945. const bool t1_or_t2 = (t1 != nullptr && t1_yr == this_yr && t1_mo == mo) ||
  4946. (t2 != nullptr && t2_yr == this_yr && t2_mo == mo);
  4947. if (t1_or_t2)
  4948. ImGui::PushStyleColor(ImGuiCol_Button, col_btn);
  4949. if (ImGui::Button(MONTH_ABRVS[mo],cell_size) && !clk) {
  4950. *t = MakeTime(this_yr, mo);
  4951. *level = 0;
  4952. }
  4953. if (t1_or_t2)
  4954. ImGui::PopStyleColor();
  4955. if (j != 3)
  4956. ImGui::SameLine();
  4957. mo++;
  4958. }
  4959. }
  4960. }
  4961. else if (*level == 2) {
  4962. *t = FloorTime(*t, ImPlotTimeUnit_Yr);
  4963. int this_yr = GetYear(*t);
  4964. int yr = this_yr - this_yr % 20;
  4965. ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);
  4966. ImFormatString(buff,32,"%d-%d",yr,yr+19);
  4967. ImGui::Button(buff);
  4968. ImGui::PopItemFlag();
  4969. ImGui::SameLine(5*cell_size.x);
  4970. BeginDisabledControls(yr <= min_yr);
  4971. if (ImGui::ArrowButtonEx("##Up",ImGuiDir_Up,cell_size))
  4972. *t = MakeTime(yr-20);
  4973. EndDisabledControls(yr <= min_yr);
  4974. ImGui::SameLine();
  4975. BeginDisabledControls(yr + 20 >= max_yr);
  4976. if (ImGui::ArrowButtonEx("##Down",ImGuiDir_Down,cell_size))
  4977. *t = MakeTime(yr+20);
  4978. EndDisabledControls(yr+ 20 >= max_yr);
  4979. // ImGui::Dummy(cell_size);
  4980. cell_size.x *= 7.0f/4.0f;
  4981. cell_size.y *= 7.0f/5.0f;
  4982. for (int i = 0; i < 5; ++i) {
  4983. for (int j = 0; j < 4; ++j) {
  4984. const bool t1_or_t2 = (t1 != nullptr && t1_yr == yr) || (t2 != nullptr && t2_yr == yr);
  4985. if (t1_or_t2)
  4986. ImGui::PushStyleColor(ImGuiCol_Button, col_btn);
  4987. ImFormatString(buff,32,"%d",yr);
  4988. if (yr<1970||yr>3000) {
  4989. ImGui::Dummy(cell_size);
  4990. }
  4991. else if (ImGui::Button(buff,cell_size)) {
  4992. *t = MakeTime(yr);
  4993. *level = 1;
  4994. }
  4995. if (t1_or_t2)
  4996. ImGui::PopStyleColor();
  4997. if (j != 3)
  4998. ImGui::SameLine();
  4999. yr++;
  5000. }
  5001. }
  5002. }
  5003. ImGui::PopStyleVar();
  5004. ImGui::PopStyleColor();
  5005. ImGui::EndGroup();
  5006. ImGui::PopID();
  5007. return clk;
  5008. }
  5009. bool ShowTimePicker(const char* id, ImPlotTime* t) {
  5010. ImPlotContext& gp = *GImPlot;
  5011. ImGui::PushID(id);
  5012. tm& Tm = gp.Tm;
  5013. GetTime(*t,&Tm);
  5014. static const char* nums[] = { "00","01","02","03","04","05","06","07","08","09",
  5015. "10","11","12","13","14","15","16","17","18","19",
  5016. "20","21","22","23","24","25","26","27","28","29",
  5017. "30","31","32","33","34","35","36","37","38","39",
  5018. "40","41","42","43","44","45","46","47","48","49",
  5019. "50","51","52","53","54","55","56","57","58","59"};
  5020. static const char* am_pm[] = {"am","pm"};
  5021. bool hour24 = gp.Style.Use24HourClock;
  5022. int hr = hour24 ? Tm.tm_hour : ((Tm.tm_hour == 0 || Tm.tm_hour == 12) ? 12 : Tm.tm_hour % 12);
  5023. int min = Tm.tm_min;
  5024. int sec = Tm.tm_sec;
  5025. int ap = Tm.tm_hour < 12 ? 0 : 1;
  5026. bool changed = false;
  5027. ImVec2 spacing = ImGui::GetStyle().ItemSpacing;
  5028. spacing.x = 0;
  5029. float width = ImGui::CalcTextSize("888").x;
  5030. float height = ImGui::GetFrameHeight();
  5031. ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, spacing);
  5032. ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize,2.0f);
  5033. ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0,0,0,0));
  5034. ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0,0,0,0));
  5035. ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImGui::GetStyleColorVec4(ImGuiCol_ButtonHovered));
  5036. ImGui::SetNextItemWidth(width);
  5037. if (ImGui::BeginCombo("##hr",nums[hr],ImGuiComboFlags_NoArrowButton)) {
  5038. const int ia = hour24 ? 0 : 1;
  5039. const int ib = hour24 ? 24 : 13;
  5040. for (int i = ia; i < ib; ++i) {
  5041. if (ImGui::Selectable(nums[i],i==hr)) {
  5042. hr = i;
  5043. changed = true;
  5044. }
  5045. }
  5046. ImGui::EndCombo();
  5047. }
  5048. ImGui::SameLine();
  5049. ImGui::Text(":");
  5050. ImGui::SameLine();
  5051. ImGui::SetNextItemWidth(width);
  5052. if (ImGui::BeginCombo("##min",nums[min],ImGuiComboFlags_NoArrowButton)) {
  5053. for (int i = 0; i < 60; ++i) {
  5054. if (ImGui::Selectable(nums[i],i==min)) {
  5055. min = i;
  5056. changed = true;
  5057. }
  5058. }
  5059. ImGui::EndCombo();
  5060. }
  5061. ImGui::SameLine();
  5062. ImGui::Text(":");
  5063. ImGui::SameLine();
  5064. ImGui::SetNextItemWidth(width);
  5065. if (ImGui::BeginCombo("##sec",nums[sec],ImGuiComboFlags_NoArrowButton)) {
  5066. for (int i = 0; i < 60; ++i) {
  5067. if (ImGui::Selectable(nums[i],i==sec)) {
  5068. sec = i;
  5069. changed = true;
  5070. }
  5071. }
  5072. ImGui::EndCombo();
  5073. }
  5074. if (!hour24) {
  5075. ImGui::SameLine();
  5076. if (ImGui::Button(am_pm[ap],ImVec2(0,height))) {
  5077. ap = 1 - ap;
  5078. changed = true;
  5079. }
  5080. }
  5081. ImGui::PopStyleColor(3);
  5082. ImGui::PopStyleVar(2);
  5083. ImGui::PopID();
  5084. if (changed) {
  5085. if (!hour24)
  5086. hr = hr % 12 + ap * 12;
  5087. Tm.tm_hour = hr;
  5088. Tm.tm_min = min;
  5089. Tm.tm_sec = sec;
  5090. *t = MkTime(&Tm);
  5091. }
  5092. return changed;
  5093. }
  5094. void StyleColorsAuto(ImPlotStyle* dst) {
  5095. ImPlotStyle* style = dst ? dst : &ImPlot::GetStyle();
  5096. ImVec4* colors = style->Colors;
  5097. style->MinorAlpha = 0.25f;
  5098. colors[ImPlotCol_Line] = IMPLOT_AUTO_COL;
  5099. colors[ImPlotCol_Fill] = IMPLOT_AUTO_COL;
  5100. colors[ImPlotCol_MarkerOutline] = IMPLOT_AUTO_COL;
  5101. colors[ImPlotCol_MarkerFill] = IMPLOT_AUTO_COL;
  5102. colors[ImPlotCol_ErrorBar] = IMPLOT_AUTO_COL;
  5103. colors[ImPlotCol_FrameBg] = IMPLOT_AUTO_COL;
  5104. colors[ImPlotCol_PlotBg] = IMPLOT_AUTO_COL;
  5105. colors[ImPlotCol_PlotBorder] = IMPLOT_AUTO_COL;
  5106. colors[ImPlotCol_LegendBg] = IMPLOT_AUTO_COL;
  5107. colors[ImPlotCol_LegendBorder] = IMPLOT_AUTO_COL;
  5108. colors[ImPlotCol_LegendText] = IMPLOT_AUTO_COL;
  5109. colors[ImPlotCol_TitleText] = IMPLOT_AUTO_COL;
  5110. colors[ImPlotCol_InlayText] = IMPLOT_AUTO_COL;
  5111. colors[ImPlotCol_PlotBorder] = IMPLOT_AUTO_COL;
  5112. colors[ImPlotCol_AxisText] = IMPLOT_AUTO_COL;
  5113. colors[ImPlotCol_AxisGrid] = IMPLOT_AUTO_COL;
  5114. colors[ImPlotCol_AxisTick] = IMPLOT_AUTO_COL;
  5115. colors[ImPlotCol_AxisBg] = IMPLOT_AUTO_COL;
  5116. colors[ImPlotCol_AxisBgHovered] = IMPLOT_AUTO_COL;
  5117. colors[ImPlotCol_AxisBgActive] = IMPLOT_AUTO_COL;
  5118. colors[ImPlotCol_Selection] = IMPLOT_AUTO_COL;
  5119. colors[ImPlotCol_Crosshairs] = IMPLOT_AUTO_COL;
  5120. }
  5121. void StyleColorsClassic(ImPlotStyle* dst) {
  5122. ImPlotStyle* style = dst ? dst : &ImPlot::GetStyle();
  5123. ImVec4* colors = style->Colors;
  5124. style->MinorAlpha = 0.5f;
  5125. colors[ImPlotCol_Line] = IMPLOT_AUTO_COL;
  5126. colors[ImPlotCol_Fill] = IMPLOT_AUTO_COL;
  5127. colors[ImPlotCol_MarkerOutline] = IMPLOT_AUTO_COL;
  5128. colors[ImPlotCol_MarkerFill] = IMPLOT_AUTO_COL;
  5129. colors[ImPlotCol_ErrorBar] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
  5130. colors[ImPlotCol_FrameBg] = ImVec4(0.43f, 0.43f, 0.43f, 0.39f);
  5131. colors[ImPlotCol_PlotBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.35f);
  5132. colors[ImPlotCol_PlotBorder] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f);
  5133. colors[ImPlotCol_LegendBg] = ImVec4(0.11f, 0.11f, 0.14f, 0.92f);
  5134. colors[ImPlotCol_LegendBorder] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f);
  5135. colors[ImPlotCol_LegendText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
  5136. colors[ImPlotCol_TitleText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
  5137. colors[ImPlotCol_InlayText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
  5138. colors[ImPlotCol_AxisText] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
  5139. colors[ImPlotCol_AxisGrid] = ImVec4(0.90f, 0.90f, 0.90f, 0.25f);
  5140. colors[ImPlotCol_AxisTick] = IMPLOT_AUTO_COL; // TODO
  5141. colors[ImPlotCol_AxisBg] = IMPLOT_AUTO_COL; // TODO
  5142. colors[ImPlotCol_AxisBgHovered] = IMPLOT_AUTO_COL; // TODO
  5143. colors[ImPlotCol_AxisBgActive] = IMPLOT_AUTO_COL; // TODO
  5144. colors[ImPlotCol_Selection] = ImVec4(0.97f, 0.97f, 0.39f, 1.00f);
  5145. colors[ImPlotCol_Crosshairs] = ImVec4(0.50f, 0.50f, 0.50f, 0.75f);
  5146. }
  5147. void StyleColorsDark(ImPlotStyle* dst) {
  5148. ImPlotStyle* style = dst ? dst : &ImPlot::GetStyle();
  5149. ImVec4* colors = style->Colors;
  5150. style->MinorAlpha = 0.25f;
  5151. colors[ImPlotCol_Line] = IMPLOT_AUTO_COL;
  5152. colors[ImPlotCol_Fill] = IMPLOT_AUTO_COL;
  5153. colors[ImPlotCol_MarkerOutline] = IMPLOT_AUTO_COL;
  5154. colors[ImPlotCol_MarkerFill] = IMPLOT_AUTO_COL;
  5155. colors[ImPlotCol_ErrorBar] = IMPLOT_AUTO_COL;
  5156. colors[ImPlotCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f);
  5157. colors[ImPlotCol_PlotBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.50f);
  5158. colors[ImPlotCol_PlotBorder] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f);
  5159. colors[ImPlotCol_LegendBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f);
  5160. colors[ImPlotCol_LegendBorder] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f);
  5161. colors[ImPlotCol_LegendText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
  5162. colors[ImPlotCol_TitleText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
  5163. colors[ImPlotCol_InlayText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
  5164. colors[ImPlotCol_AxisText] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
  5165. colors[ImPlotCol_AxisGrid] = ImVec4(1.00f, 1.00f, 1.00f, 0.25f);
  5166. colors[ImPlotCol_AxisTick] = IMPLOT_AUTO_COL; // TODO
  5167. colors[ImPlotCol_AxisBg] = IMPLOT_AUTO_COL; // TODO
  5168. colors[ImPlotCol_AxisBgHovered] = IMPLOT_AUTO_COL; // TODO
  5169. colors[ImPlotCol_AxisBgActive] = IMPLOT_AUTO_COL; // TODO
  5170. colors[ImPlotCol_Selection] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
  5171. colors[ImPlotCol_Crosshairs] = ImVec4(1.00f, 1.00f, 1.00f, 0.50f);
  5172. }
  5173. void StyleColorsLight(ImPlotStyle* dst) {
  5174. ImPlotStyle* style = dst ? dst : &ImPlot::GetStyle();
  5175. ImVec4* colors = style->Colors;
  5176. style->MinorAlpha = 1.0f;
  5177. colors[ImPlotCol_Line] = IMPLOT_AUTO_COL;
  5178. colors[ImPlotCol_Fill] = IMPLOT_AUTO_COL;
  5179. colors[ImPlotCol_MarkerOutline] = IMPLOT_AUTO_COL;
  5180. colors[ImPlotCol_MarkerFill] = IMPLOT_AUTO_COL;
  5181. colors[ImPlotCol_ErrorBar] = IMPLOT_AUTO_COL;
  5182. colors[ImPlotCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
  5183. colors[ImPlotCol_PlotBg] = ImVec4(0.42f, 0.57f, 1.00f, 0.13f);
  5184. colors[ImPlotCol_PlotBorder] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
  5185. colors[ImPlotCol_LegendBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.98f);
  5186. colors[ImPlotCol_LegendBorder] = ImVec4(0.82f, 0.82f, 0.82f, 0.80f);
  5187. colors[ImPlotCol_LegendText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
  5188. colors[ImPlotCol_TitleText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
  5189. colors[ImPlotCol_InlayText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
  5190. colors[ImPlotCol_AxisText] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
  5191. colors[ImPlotCol_AxisGrid] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
  5192. colors[ImPlotCol_AxisTick] = ImVec4(0.00f, 0.00f, 0.00f, 0.25f);
  5193. colors[ImPlotCol_AxisBg] = IMPLOT_AUTO_COL; // TODO
  5194. colors[ImPlotCol_AxisBgHovered] = IMPLOT_AUTO_COL; // TODO
  5195. colors[ImPlotCol_AxisBgActive] = IMPLOT_AUTO_COL; // TODO
  5196. colors[ImPlotCol_Selection] = ImVec4(0.82f, 0.64f, 0.03f, 1.00f);
  5197. colors[ImPlotCol_Crosshairs] = ImVec4(0.00f, 0.00f, 0.00f, 0.50f);
  5198. }
  5199. //-----------------------------------------------------------------------------
  5200. // [SECTION] Obsolete Functions/Types
  5201. //-----------------------------------------------------------------------------
  5202. #ifndef IMPLOT_DISABLE_OBSOLETE_FUNCTIONS
  5203. bool BeginPlot(const char* title, const char* x_label, const char* y1_label, const ImVec2& size,
  5204. ImPlotFlags flags, ImPlotAxisFlags x_flags, ImPlotAxisFlags y1_flags, ImPlotAxisFlags y2_flags, ImPlotAxisFlags y3_flags,
  5205. const char* y2_label, const char* y3_label)
  5206. {
  5207. if (!BeginPlot(title, size, flags))
  5208. return false;
  5209. SetupAxis(ImAxis_X1, x_label, x_flags);
  5210. SetupAxis(ImAxis_Y1, y1_label, y1_flags);
  5211. if (ImHasFlag(flags, ImPlotFlags_YAxis2))
  5212. SetupAxis(ImAxis_Y2, y2_label, y2_flags);
  5213. if (ImHasFlag(flags, ImPlotFlags_YAxis3))
  5214. SetupAxis(ImAxis_Y3, y3_label, y3_flags);
  5215. return true;
  5216. }
  5217. #endif
  5218. } // namespace ImPlot