Compare commits

..

297 Commits
v1.14 ... v1.30

Author SHA1 Message Date
c343e95a0a Update README.md 2015-02-01 00:15:18 +00:00
bcb3753774 Web: Redone one screenshot so it fits in github website without resizing 2015-02-01 00:14:29 +00:00
b69f82ee34 New set of pictures! 2015-02-01 00:01:01 +00:00
49569a903c Shortened text 2015-01-31 23:55:47 +00:00
2f5c754ef1 InputText: process character input before Return because they may come together (IME batch) 2015-01-31 23:51:00 +00:00
35c0842bcf Examples: DirectX11: fixed handling of unicode character inputs. 2015-01-31 23:26:53 +00:00
bebd2da1f1 Wrapping g.ActiveId assignment into a function for easy breakpoint. 2015-01-31 22:57:59 +00:00
3f6091b26b Pedantic grammar fix 2015-01-31 21:27:26 +00:00
5834297928 Examples: DirectX11: increasing vertex buffer size (would really need a dynamic buffer size)
+ Delete unused code
2015-01-31 21:12:59 +00:00
381c7428c1 Examples: changed default background color. 2015-01-31 20:08:43 +00:00
a548c9b0d5 Version change 2015-01-31 19:10:04 +00:00
ca10c49e27 Embedded a mouse cursor that can be drawn for you by setting io.MouseDrawCursor 2015-01-31 18:55:05 +00:00
68bad703ee ImColor::HSV() helper + color buttons demo 2015-01-31 17:15:07 +00:00
8d1583d611 Added ImColor() inline helper. Image/ImageButton() now takes ImVec4 for consistency and honor window alpha. 2015-01-31 16:44:55 +00:00
cb3b69c879 Exposed ColorConvertHSVtoRGB, ColorConvertRGBtoHSV, ColorConvertFloat4ToU32 2015-01-31 16:36:12 +00:00
3cf47988b0 Added ImageButton() using regular framing + override framing size (#73) 2015-01-31 16:21:12 +00:00
2ecc285919 ImDrawList::AddCallback() allows for custom rendering (e.g. 3D scene inside a imgui widget)) 2015-01-31 15:24:55 +00:00
82666cdc57 ShowTestWindow() early out if window is collapsed. Drawing the 2 columns example differently. 2015-01-31 10:20:37 +00:00
4437293b79 Added ImDrawList::SplitDrawCmd() to force multiple draw calls for depending rendering/blending + Comments 2015-01-31 09:51:25 +00:00
64679a0b03 ImFontAtlas::Build() does a sanity memset on glyph rectangles. 2015-01-29 17:44:46 +01:00
4c4bbcb451 Examples: fixed custom rendering example canvas size. 2015-01-29 15:04:56 +01:00
229ba6ea18 Update README.md 2015-01-29 15:01:44 +01:00
27161d2a98 Added io.DisplayVisibleMin / io.DisplayVisibleMax to allow for virtual / scrolling display.
+ remove duplicated "Setup outer clipping rectangle" block in Begin))
2015-01-29 14:20:25 +01:00
962ef3924a Added extra asserts and tweaked code in Begin() 2015-01-29 14:07:20 +01:00
07f69966f8 ImDrawList::AddImage() color parameter defaults to white 2015-01-29 13:46:34 +01:00
79042a3a3c GetVoidPtr() functions like GetInt, GetFloat. Renamed GetIntPtr/GetFloatPtr to GetIntRef/GetFloatRef 2015-01-29 10:22:32 +01:00
5b180afc4e Merge pull request #116 from emoon/master
Added Set/GetVoidPtr in ImGuiStorage
2015-01-29 10:10:48 +01:00
c9c41c3874 Added Set/GetVoidPtr in ImGuiStorage 2015-01-28 21:31:22 +01:00
00842d18e4 Speculative GCC warning fix (again) 2015-01-24 11:30:40 +01:00
4535f5f899 Fixed some warnings with Clang/GCC 2015-01-24 11:18:31 +01:00
638babb0dd Examples: added simple drawing app example for using ImDrawList and custom drawing 2015-01-23 01:38:04 +01:00
32b8ad7381 Fixed mouse aiming within InputText() - broken during 01/18 merge 2015-01-23 00:02:44 +01:00
7530f3c985 Added IsItemActive() - replace IsItemFocused()
ClipAdvance() --> ItemAdd() - nb: return value is inverted
2015-01-22 23:54:05 +01:00
70188c5623 Added comments 2015-01-22 11:03:24 +01:00
f1ccd32cb1 stb_truetype: implementation is now static + submitted PR to origin. 2015-01-21 23:45:21 +01:00
26174cba85 Added InvisibleButton() 2015-01-21 23:03:25 +01:00
dbffbacaf6 Added IMGUI_DISABLE_STB_***_IMPLEMENTATION 2015-01-21 11:59:11 +01:00
26f93e6660 IMGUI_STB_NAMESPACE define Stb stuff in a namespace (trying stuff to reduce problems with multiple implementations) 2015-01-21 11:54:23 +01:00
9524d76fe8 Documentation 2015-01-20 22:37:18 +01:00
942e1ca811 Notes, todo items 2015-01-20 10:37:30 +01:00
b24d4d0538 Ignore lists 2015-01-20 01:04:34 +01:00
b0eac255ca Warning fixes for 64-bit architectures 2015-01-20 01:01:25 +01:00
53f4fd38e4 Merge branch 'master' of https://github.com/ocornut/imgui 2015-01-18 15:12:47 +00:00
56ac857cac Added stub for obsolete GetDefaultFontData() to help the user upgrading 2015-01-18 15:12:41 +00:00
7ea9253c31 Update README.md 2015-01-18 12:56:59 +00:00
a1c0c0e298 stb_truetype.h mod comment 2015-01-18 12:54:35 +00:00
b87f9a19c8 Merge pull request #113 from ocornut/2015-01-truetype
Merge - TTF font loading, mulitple fonts, Image support
2015-01-18 12:27:32 +00:00
7e2305eb36 Comments 2015-01-18 12:22:17 +00:00
46fbff50cf Documentation 2015-01-18 12:19:49 +00:00
bfe894406d ImFontAtlas: some more optimisations / cleanup. 2015-01-18 12:12:16 +00:00
e685e49781 ImFontAtlas: reduced number of temporary allocation when building lots of input ranges 2015-01-18 11:55:58 +00:00
edcf2d3bf6 Examples: more comments on loading fonts. 2015-01-18 11:38:14 +00:00
8386e4fb7e Fix handling of NULL GlyphRanges. Asserting on AddFontFromFileTTF() failure. 2015-01-18 11:36:23 +00:00
ed23598e49 Font documentation 2015-01-18 11:24:06 +00:00
ca81fd3a34 Removing the binary_to_c() comment, link to license for ProggyClean 2015-01-18 11:19:11 +00:00
1916a0c78c Renamed FontAtlas to Fonts. Further cleanup/comments. 2015-01-18 10:46:49 +00:00
1f8d209202 Fixed more clang warnings + AddFontFromMemoryTTF() not honoring font_no parameter 2015-01-17 23:21:06 +00:00
37dcf58e2f Fixed clang warnings 2015-01-17 23:13:54 +00:00
0dad59b032 Merge remote-tracking branch 'origin/master' into 2015-01-truetype 2015-01-17 22:57:35 +00:00
e666920784 ImFont: small optimization to our (incorrect) handling of TAB
TAB is still handled as 4-spaces width (which is incorrect)
But CalcTextSize is simplified.
2015-01-17 22:53:54 +00:00
5ad9a2f119 Comments on new API 2015-01-17 22:38:10 +00:00
2c31599bcc ImFontAtlas allows loading multiple fonts into same texture. Revamped new init API for 1.30 2015-01-17 22:15:29 +00:00
a3e368a477 Fixed alignment of ColorEdit4() label 2015-01-17 17:19:07 +00:00
cb9a3235be Removed PixelCenterOffset, uncesssary 2015-01-17 17:17:18 +00:00
ad92018bc0 Fixed lower-right rounded triangle rendering precision.
PixelCenterOffset is handled very inconsistently, needs to be fixed.
2015-01-17 17:03:22 +00:00
43c8b5e0d2 Examples: DirectX11: use linear sampler to be in sync with other examples. 2015-01-17 16:52:21 +00:00
014f88b1fc Font fixes for horizontal centering within frames 2015-01-17 15:44:25 +00:00
edee014ab8 ImDrawList merging commands with same texture 2015-01-17 14:13:08 +00:00
3e30ad3802 PushFont/PopFont changes texture at high-level in current draw list - faster 2015-01-17 14:00:43 +00:00
7ebd7ef9ac Added PushFont/PopFont API 2015-01-17 13:40:56 +00:00
79d1a9d941 Commenting asserts. 2015-01-17 12:27:27 +00:00
97fcee0d0d Fix usage of multiple Begin/End pair for the same window, handling of move in End() was stealing Active ID 2015-01-16 10:55:49 +00:00
ab8d2782c6 Merge remote-tracking branch 'upstream/master' into 2015-01-truetype
Conflicts:
	imgui.cpp
	imgui.h
2015-01-15 18:07:44 +00:00
f61e8e6e26 Tooltip always auto-resize. May look into max-over-xx-seconds policy later. 2015-01-15 18:00:10 +00:00
2082487366 Allow SetNextWindowPos() to affect tooltips. 2015-01-15 17:47:53 +00:00
584c7ffac8 Added SetCursorScreenPos() helper (WindowPos+CursorPos = SrceenPos) 2015-01-15 14:41:22 +00:00
2d7a2310fd Collapsing header also honor FrameRounding 2015-01-15 10:29:51 +00:00
62ecdd21a5 Examples: Added a color slider for the background color + tweak first example use of button.s 2015-01-15 09:59:18 +00:00
02f0dbca37 ColorEdit3: clicking on color square change edit-mode, removing color-edit mode button by default. 2015-01-15 09:49:12 +00:00
8ba93d947c Added FrameRounding setting (default to 0 for now). 2015-01-15 09:14:44 +00:00
3c8f010c29 Fixed TooltipBg color not being honored by tooltip + no minimum tooltip size. 2015-01-14 22:10:48 +00:00
4f6643cc0c Fix missing glyph handling in modified stb_truetype.h (ttf branch) 2015-01-14 22:05:13 +00:00
188165a063 Fix stupid crash on fallback glyph handling (ttf branch) 2015-01-14 21:59:39 +00:00
08b50cce12 TODO list update 2015-01-14 21:58:30 +00:00
04eca0c375 TODO list update 2015-01-14 13:43:41 +00:00
a372d67f47 Improve memory reserve policy for Clipboard/ImGuiBuffer 2015-01-14 13:04:33 +00:00
3a20671802 Fixed logging to clipboard on architectures where va_list are modified by vsnprintf (fixed #112) 2015-01-14 13:01:53 +00:00
5322224881 Warning fixes for llvm windows 64-bits 2015-01-13 23:19:11 +00:00
e2d8c03e1a Fixed ImGuiTextBuffer::empty() to ignore the enforced zero-terminator
+ removed unnecessary destructor
2015-01-13 23:06:55 +00:00
f0b493c217 Fixed style.WindowMinSize not honored properly. 2015-01-13 23:05:20 +00:00
6c6d1746d4 Fix missing glyph handling in modified stb_truetype.h 2015-01-13 08:56:02 +00:00
f061884dea Typos and comments 2015-01-11 22:22:46 +00:00
0f89e06152 Fixed temporary glyph rectangle allocation using size much too big. 2015-01-11 22:03:03 +00:00
e5d0d8334f Tweak default texture width for large amount of characters. 2015-01-11 21:55:21 +00:00
d27b295f4c Documentation on new font / texture get api 2015-01-11 21:24:12 +00:00
0f4d74d614 ImFont::GetTextureData API allow to retrieve 8/32 bits data + lazily load defaults font
Examples: OpenGL3 and DirectX11 back to using 32-bits texture solely for
ease of integration.
2015-01-11 21:06:57 +00:00
241e8086fa Mde it optional to new() io.Font - however it stills needs to be loaded. 2015-01-11 18:27:05 +00:00
51df5874a6 Examples' Says "OpenGL2" vs "OpenGL3" in title bar. 2015-01-11 18:03:40 +00:00
a09f426b89 TAB to spaces 2015-01-11 17:56:43 +00:00
5ca563b5a5 Speculative fix for warnings for GCC/Clang 2015-01-11 17:22:04 +00:00
20bb6270bc Examples: all supports TextureID in renderer, added LoadFontTexture() function. 2015-01-11 17:17:43 +00:00
40f7b67ef1 ImDrawList::AddText() allows changing font 2015-01-11 16:46:39 +00:00
cc79b85c28 Added first-pass of Image() based on #73 + demo 2015-01-11 16:30:39 +00:00
1a6e7f25e0 ImVector: less hoops in back() / front(), more friendly for debugger and unoptimized builds
+ fixed typos
2015-01-11 16:25:57 +00:00
c1fe6fe14d Fixed GetStyleColName() not matching the enum strings for 3 values (#111) 2015-01-09 17:19:24 +00:00
5dff478dc0 Build fix for GCC/Clang, cannot foward declare a static array? 2015-01-09 09:00:53 +00:00
2757e3573a Comments 2015-01-08 23:53:07 +00:00
f77490cb2d Cleanup extra_fonts/ folder 2015-01-08 23:49:17 +00:00
b3a208901a Loading TTF file with stb_truetype. Broke setup API slightly. Font baked, packed with space for custom data. Embeds compressed ProggyClean. 2015-01-08 23:35:01 +00:00
dd8a7655f5 Fixed DirectX11 example. 2015-01-08 18:56:47 +00:00
b0ea57e518 Version number 2015-01-07 19:07:43 +00:00
4260195159 Revert "Reexported proggy_clean_13 in a 256x64 texture (instead of 256x128) and documented exact export parameters"
Correct but cause problems because many people don't have 1 BPP PNG loaders

This reverts commit 98a38e24ab.
2015-01-07 18:59:44 +00:00
26fdf1655c Fixed leak on shutdown (fixes #110) + possible uninitialized member. 2015-01-07 14:55:35 +00:00
c1251d2994 Examples: Fixed warnings for Clang 2015-01-06 17:43:23 +00:00
1c657564ac Examples: Added STB_IMAGE_STATIC in examples to avoid conflicting implementation. Relate to #109 2015-01-06 17:35:36 +00:00
98a38e24ab Reexported proggy_clean_13 in a 256x64 texture (instead of 256x128) and documented exact export parameters 2015-01-05 11:13:02 +00:00
0505995193 Very minor code/comments tweaks. 2015-01-04 22:29:53 +00:00
4905ec46f1 Fixed hovering of child windows / combo boxes that extend beyond the root window limits. 2015-01-04 22:07:37 +00:00
3fe669f547 Failure in LogToFile() treated at an error (assert) in the absence of another type of error handling. 2015-01-04 21:37:49 +00:00
22c1d7eded Renamed some color enums 2015-01-04 19:37:24 +00:00
39373b563b Checkbox and Radio buttons activate on click-release to be consistent with other widgets and most UI 2015-01-04 19:23:36 +00:00
97d34271f8 Fix clipboard pasting into an InputText box not filtering the characters according to input box semantic (number, etc.) 2015-01-04 18:47:08 +00:00
a5f4108781 Activating widget bring parent window to front 2015-01-04 18:36:33 +00:00
3674d30e90 Fixed clicking on Combo box label. 2015-01-04 18:32:15 +00:00
2268b098e0 Avoid marking settings as dirty when window is marked unsaved + minor FocusWindow() optimisation 2015-01-04 18:23:30 +00:00
4bccc06933 Dragging outside area of a widget while it is active doesn't trigger hover on other widgets. 2015-01-04 18:12:30 +00:00
ee49c2288d Todo items. 2015-01-03 17:38:10 +00:00
34664dc28c InputText() consume input characters immediately (fixes #105) 2015-01-03 17:37:39 +00:00
e4f96147de Update README.md 2014-12-31 15:55:34 +00:00
12225abfe2 Version number (fix) 2014-12-31 10:38:36 +00:00
505bd1a66d Fixed text input filtering for character in the 128-255 range. 2014-12-31 09:49:53 +00:00
c9002620c6 Update README.md 2014-12-30 17:13:04 +00:00
f8c58fe328 Fix for Clang 2014-12-30 16:55:32 +00:00
74ab555558 Examples: Console:: added support for History callbacks + cleanup to be self contained. 2014-12-30 16:49:39 +00:00
da5227fa28 Added comment about defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h 2014-12-30 15:44:19 +00:00
3b028c7ebf Fixed InputInt() InputFloat() label not declaring their width, breaking SameLine (bug #100)
+ shallow cleanups
2014-12-30 15:38:28 +00:00
2d111ccb55 crc32 on strings is performed in one pass - removed the strlen() call. 2014-12-30 15:18:21 +00:00
691ca46978 Version number 2014-12-30 15:10:55 +00:00
209be54e49 Version number 2014-12-30 12:21:57 +00:00
aa750d538d Style editor: added an Output button to output colors to clipboard/tty 2014-12-30 12:08:33 +00:00
929f127d06 Added SliderInt2(), SliderInt3(), SliderInt4() for consistency 2014-12-30 11:54:04 +00:00
60b4389ac1 Empty label consistently remove the inner-padding normally preceeding the label. 2014-12-30 11:41:46 +00:00
a950df6655 Tightening default style (saving -2 pixels on each axis per widget) 2014-12-30 10:00:00 +00:00
409b1ac6b5 Log output \r\n under Windows so files are readable with Notepad 2014-12-29 20:41:27 +00:00
036a153cf4 Log depth padding relative to start depth. Tree node and headers looking better when logged to text. Added LogText(). 2014-12-29 20:18:52 +00:00
886d954e3d GetStyleColorName -> GetStyleColName for consistency with type name. Removed ImGuiStyleVar_ColumnsMinSpacing 2014-12-29 19:56:01 +00:00
39952d2362 Renamed GetTreeStateStorage() to GetStateStorage(). Columns storing floats instead of fixed point integers 2014-12-29 18:17:54 +00:00
1b25fa8169 Added LogFinish() to stop logging at an arbitrary point. 2014-12-29 18:13:41 +00:00
0796dc0dc1 Minor fix for cases of malformed .ini file (zero-terminating text file like it was before previous commit). 2014-12-29 18:05:22 +00:00
8994f2f1e4 Cleanup. Removed unnecessary calls to sqrtf(). Factoring bits into ImLoadFileToMemory(). Added index of static helpers. 2014-12-29 11:23:03 +00:00
e2fbbe0274 Factoring bits out of Begin() into a private CreateNewWindow() funciton
(Hopefully to ease a bit the merging work for ProDBG)
2014-12-28 17:54:02 +00:00
5b7ed5432e CalcTextSize() default third parameter to false because it almost never makes sense to use it from the outside (may obsolete it) 2014-12-28 16:17:08 +00:00
bf3212c681 Taking notes of issues/todo 2014-12-28 16:09:19 +00:00
34728394ec Fixed clipped ImGui::Combo not registering its size properly (was flickering when scrolling with combo on the edge of clipping region) 2014-12-26 12:38:13 +00:00
90351298d1 Renamed second parameter to Begin() to 'bool* p_opened' to be more self-explanatory. Added more comments on the use of Begin(). 2014-12-22 13:29:39 +00:00
69f3d67d18 Preserve windows position on zero-sized display (minimized). 2014-12-22 02:14:31 +00:00
d6c13128b9 Update README.md - tweaks 2014-12-22 02:07:02 +00:00
b3febabc30 OpenGL3 example: fix growing of VBO 2014-12-22 01:47:34 +00:00
ac29859f70 Support zero-sized display, now sets default as -1,-1 and assert if display size is negative. 2014-12-22 01:45:13 +00:00
a3af51fd4e Added ImGuiStyleVar_WindowRounding enum for PushStyleVar() API 2014-12-19 12:56:00 +00:00
b09c49180f Update README.md minor fixes 2014-12-14 10:44:43 +00:00
7e868e2842 Cleanup todo list, removed 3 done items + added 1 new 2014-12-11 10:12:52 +00:00
0056ccce26 Version number 2014-12-10 23:40:25 +00:00
486506e37f Update README.md 2014-12-10 23:39:48 +00:00
e9e0e36f98 New and better Set[Next]Window(Pos|Size|Collapsed) API.
Removed rarely useful SetNewWindowDefaultPos() in favor of new API.
2014-12-10 19:22:30 +00:00
3399890a84 Added ImGuiWindowFlags_NoSavedSettings flag + Fixed overlay example app. 2014-12-10 17:13:45 +00:00
2a3bff9a82 Comments 2014-12-10 16:56:11 +00:00
09bacfbe18 OpenGL example: allow resizing window. 2014-12-10 15:27:40 +00:00
cca5f473ca Clarified comment 2014-12-08 17:18:20 +00:00
6523fb263d OpenGL3 example: fixed mouse handling. 2014-12-08 17:15:08 +00:00
bdb2344db0 ImGuiStorage helper can store float + added functions to get pointer to data. Exposed ImGui::GetId() - may be misleading? 2014-12-08 17:14:54 +00:00
0a0769227d Added Travis CI build banner. 2014-12-07 10:17:39 +00:00
6252b26af2 Update README.md 2014-12-07 10:15:34 +00:00
987188d437 Fix Clang warning with offsetof() macro? Added -Wall in OpenGL 3 example. 2014-12-07 09:58:45 +00:00
71e20680db Setup Travis CI integration with Clang + -Wall in Makefiles 2014-12-07 09:48:01 +00:00
bb20065be0 Setup Travis CI integration
Getting there!
2014-12-06 23:30:38 +00:00
fec067d033 Setup Travis CI integration
More libs needed
2014-12-06 23:27:40 +00:00
2eb837ea86 Setup Travis CI integration
Different PPA source
2014-12-06 23:23:57 +00:00
857a4e364c Setup Travis CI integration
Yes please
2014-12-06 23:21:05 +00:00
2599849e9c Setup Travis CI integration
Trying again with a PPA for glfw3-dev
2014-12-06 23:17:30 +00:00
da1b8f7e46 Setup Travis CI integration
Argh.
2014-12-06 23:06:04 +00:00
0687af2ce5 Setup Travis CI integration
Failing to get glfw3 for ubuntu, trying osx/gcc
2014-12-06 23:01:41 +00:00
1d45478637 Setup Travis CI integration
Argh.
2014-12-06 21:06:00 +00:00
1bfb59174a Setup Travis CI integration
Apt-get update needed..
2014-12-06 21:04:25 +00:00
83575a464f Setup Travis CI integration
Forgot sudo. Removing apt-get update, probably works without.
2014-12-06 21:01:00 +00:00
3e83de58b5 Setup Travis CI integration 2014-12-06 20:59:14 +00:00
2b0d8447e3 Setup Travis CI integration
Testing
2014-12-06 20:56:34 +00:00
d553cd96b0 Setup Travis CI integration
Testing.
2014-12-06 20:50:27 +00:00
30ee2fed2b Merge branch 'master' of https://github.com/ocornut/imgui 2014-12-06 20:43:13 +00:00
036ed3ea93 OpenGL3 example: unregistered mouse callback for mouse click-release faster than frame interval. 2014-12-06 20:43:08 +00:00
123691023b Merge pull request #94 from emoon/master
Clang warning fixes
2014-12-06 12:59:22 +00:00
317dab5269 Clang warning fixes 2014-12-06 13:49:46 +01:00
e43cd6e97f Added IMGUI_INCLUDE_IMGUI_USER_H 2014-12-05 23:09:43 +00:00
a5cc2e4161 Fixed InputInt() writing to output when it doesn't need to, which break with large int due to int<>float conversions. Added todo note. 2014-12-05 12:34:14 +00:00
6b16424faf Comments. 2014-12-04 11:54:49 +00:00
d133831909 In-code FAQ: added comment about reading WantCaptureMouse / WantCaptureKeyboard 2014-12-04 11:42:13 +00:00
2e5b81627f Examples: DirectX11: moved shader to be close to its usage location, 2014-12-03 18:46:13 +00:00
52b5376d9b Examples: OpenGL3: cleaned up to match features of OpenGL2 example 2014-12-03 18:40:28 +00:00
b02eed3e49 Examples: adding title to the top of each examples. Cleaning up file headers. 2014-12-03 18:29:46 +00:00
90b4ff13fb Ignore list. 2014-12-03 18:19:48 +00:00
6c9edb6db0 Examples: removed LICENSE file from MSVC project. 2014-12-03 18:19:05 +00:00
860cf578f5 Added ImGuiWindowFlags_NoScrollWithMouse flag.
ButtonBehaviour test hovering of CurrentRootWindow (vs CurrentWindow, different for child-windows). This is intentionally meant to fix grabbing the lower-right resize grip when lower-right corner has a child-window, but may be the overall right-er test. Testing out.
2014-12-03 18:17:10 +00:00
e0dc8ac910 Merge pull request #93 from olivierchatry/master
Added OpenGL programmable-pipeline example.
2014-12-03 18:15:42 +00:00
2f176033c6 fixed indentation mix, removed some unused code, updated different callback using the example_opengl code. 2014-12-03 19:11:23 +01:00
a8d2bc69ed added opengl3 sample, mix from @ocornut and @thelinked 2014-12-03 18:37:07 +01:00
63ff0ad0ff Examples: OpenGL: fix accessing libraries via ProjectDir instead of SolutionDir 2014-12-03 12:00:03 +00:00
d31623061f ImVector: private -> protected 2014-12-03 11:56:40 +00:00
bd762b559c DirectX11 example: fixed projection matrix offset. 2014-12-01 09:34:17 +00:00
e6b9950645 Update README.md
Credits+link for stb_textedit.h
2014-11-30 18:06:52 +00:00
b4fd216bd2 DirectX9/DirectX11 example: fixed window initially showing an hourglass cursor. 2014-11-30 18:02:08 +00:00
0730ec7577 Example apps: accumulate mouse wheel to accodomate for slow framerate. 2014-11-30 17:41:08 +00:00
0e6f288a2f DirectX11 example: further tweaks/massaging (-15 lines). Syncing example. 2014-11-30 17:26:44 +00:00
7f804d3d64 Tab->Spaces :( visual studio can't even be trusted for that, oh thanks. 2014-11-30 16:56:35 +00:00
de44af5227 DirectX11 example: closing all handler/resources in Cleanup. 2014-11-30 16:53:33 +00:00
0f29cd7a14 Removed Microsoft IME handler in examples, too confusing. Moved to imgui.cpp instruction block. 2014-11-30 15:54:58 +00:00
a5a84a9b69 Tab->Spaces :( 2014-11-30 15:53:47 +00:00
197b2763fc Fixed DirectX11 example Release build include 2014-11-30 15:51:42 +00:00
df00fa8113 Fixed DirectX11 example to compile with whatever Visual Studio version user has 2014-11-30 15:33:57 +00:00
e835ef1d90 Fix from incorrect change left-over in a31e44b99a 2014-11-30 15:19:39 +00:00
ae75553ba1 Ignore list for new examples structure 2014-11-30 15:01:08 +00:00
2e576de9ca Fix comments 2014-11-30 15:00:07 +00:00
9e16317382 Added DirectX11 example application (code is too long!) 2014-11-30 14:59:21 +00:00
b5acb16378 Examples: created single .sln solution for all example projects. 2014-11-30 12:54:27 +00:00
38164a410d ImStrnicmp tweak 2014-11-30 12:31:43 +00:00
214c967df8 Example code: warning fix + comments. 2014-11-30 12:28:21 +00:00
31654958f9 Merge pull request #92 from memononen/master
Smoother mouse wheel scrolling
2014-11-30 12:25:21 +00:00
a31e44b99a Fixed Clang -Weverything warnings + TODO list entries 2014-11-30 12:21:50 +00:00
54ea495207 Updated example code. 2014-11-30 12:24:27 +02:00
eb789c0288 Smoother scrolling
- changed IO.MouseWheel to float, allows smoother scrolling
2014-11-30 12:20:25 +02:00
e9aead09cb Remove unneeded extra parameter from ImFont::FindGlyph() 2014-11-29 00:04:05 +00:00
e4a79e9fc8 Moved IO.Font*** options to inside the IO.Font-> structure.. Added IO.FontGlobalScale setting (vs Font->Scale) 2014-11-29 00:02:46 +00:00
e27eddfbd2 Grammar fix + ocd alignment 2014-11-28 23:10:43 +00:00
311a2f8328 New version of IMGUI_ONCE_UPON_A_FRAME helper macro 2014-11-28 23:08:45 +00:00
df2ad5e899 Renamed ImBitmapFont -> ImFont, removed abstraction-pretend typedef 2014-11-28 22:38:41 +00:00
07a6ba8aaf Merge branch 'master' of https://github.com/ocornut/imgui 2014-11-28 22:29:07 +00:00
16d6561aba Increased visibility of check box and radio button with smaller size. + comments 2014-11-28 21:53:31 +00:00
abe45e9976 Moved API Breaking Changes section of the documentation above the programmer's FAQ. 2014-11-26 22:27:48 +00:00
c0999495e7 Fixed move-by-word in InputText() - broken 2 days ago, sorry. stb_ expect a define. 2014-11-26 22:19:46 +00:00
b9118750ae Removed IMGUI_ONCE_UPON_A_FRAME in favor of ImGuiOnceUponAFrame which is supported by all compilers 2014-11-26 22:16:38 +00:00
7f6453ca70 Update README.md
Grammar fix
2014-11-25 15:19:05 +00:00
24a9d32531 Update README.md 2014-11-25 15:17:15 +00:00
ec4b510775 Minor tidying & comments 2014-11-24 10:02:39 +00:00
1484799b18 Console example: fixing losing text selection when using TAB completion with no match 2014-11-23 23:50:23 +00:00
895f93f694 Remove unused variables 2014-11-23 23:36:54 +00:00
49defcf083 InputText support for completion/history/custom callback + added fancy completion example in the console demo app
Unfortunately quite messy because of the UTF-8 <> wchar confusion going
around. Not well tested for UTF-8 compliance with non-Ascii characters.
2014-11-23 23:35:26 +00:00
e78c47961e Not word-wrapping on apostrophes 2014-11-21 16:35:35 +00:00
8c4fcf1359 Added ImGuiWindowFlags_AlwaysAutoResize + example app. Calling SetWindowSize(0,0) force an autofit without zero-sizing first. 2014-11-21 16:29:56 +00:00
2322318cac PopStyleVar() fix. OOPS 2014-11-21 14:19:26 +00:00
5f8175abaa Version number 2014-11-21 13:40:38 +00:00
ab4f5e6862 Update README.md 2014-11-21 13:38:09 +00:00
075fe0220e MouseWheel input is normalized 2014-11-21 13:24:57 +00:00
cf037b4769 PushStyleColor/PushStyleVar can be used outside the scope of a window. Added 'count' parameter to PopStyleColor/PopStyleVar 2014-11-21 13:23:22 +00:00
97192606a6 Fixed Tab > space 2014-11-20 15:19:55 +00:00
e90984f638 Update README.md about performance 2014-11-20 12:27:05 +00:00
366516c154 Added "performance" screenshot 2014-11-20 12:10:53 +00:00
a6e0d182b0 Added "performance" screenshot 2014-11-20 12:04:08 +00:00
3572b04c69 ShowTestWindow: fixed example app from not displaying when header is collaposed. 2014-11-20 11:54:13 +00:00
fd8752df8d Style editor: colors list inside a scrolling region 2014-11-20 11:33:40 +00:00
f1dcd72e9f General fixes of Columns() api. User has more flexibility in the way to fill cells. 2014-11-20 11:31:55 +00:00
2aee4419e3 Fixed compatibility with std::vector if user decide to #define ImVector 2014-11-20 08:15:21 +00:00
9f2545e6bb Fixed comment 2014-11-18 10:01:34 +00:00
f3bd033b6d More fixes for ultra pedantic Clang -Weverything 2014-11-18 09:55:31 +00:00
b15532345b Using sqrtf, cosf, sinf. Made STB_TEXTEDIT_ implemtations static. Tweaks. 2014-11-18 07:51:55 +00:00
15436b46e8 Merge pull request #83 from emoon/master
Fixed Clang warnings
2014-11-18 07:40:50 +00:00
b01adf16de Fixed more Clang warnings 2014-11-17 20:37:22 +01:00
428c4d4ece Fixed Clang warnings 2014-11-17 20:35:58 +01:00
172ff0a262 Commenting unnecessary strlen calls that could be removed for speedup 2014-11-17 02:27:26 +09:00
c6f3d0924e Default 'text_end' parameter for low-level AddText/CalcTextSizeA functions 2014-11-17 02:18:37 +09:00
ac40284536 Fixed punctuation. 2014-11-15 13:29:44 +00:00
191e17eaf8 Added IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT 2014-11-15 13:18:25 +00:00
616668dac3 OpenGL example: uses offsetof() macros for vertice definition instead of hardcoded offsets 2014-11-15 13:10:15 +00:00
36e52167da OpenGL example: made the render function save/restore OpenGL state properly-ish 2014-11-15 12:56:41 +00:00
3f85fe2fe7 Cleanup and TODO list items 2014-11-15 12:00:35 +00:00
447cc88e04 Fixed unaligned memory access - fix font loading when building on Emscripten 2014-11-15 11:41:03 +00:00
9c707b6d8f Added assert to catch font data loading failure in a location that's easier to understand 2014-11-14 11:22:35 +09:00
9b5493d1d9 Added assert to catch users using Begin/End without a first NewFrame 2014-11-14 11:17:59 +09:00
8a65d97bf0 Warning fixes (now testing with Clang) 2014-11-12 16:56:42 +09:00
be93b842c1 Merge pull request #77 from ybunyak/master
Fix namespaces for Value() and Color() functions.
2014-11-12 08:48:53 +09:00
7961c53145 Fix namespaces for Value() and Color() functions. 2014-11-12 01:36:34 +02:00
d3bc92a674 Added INDEX to top of imgui.cpp
Explicit namespace prefix on all ImGui:: functions.
Fixed some typos.
2014-11-10 10:29:01 +09:00
4205241e86 PushTextWrapPos() defaults to 0.0 2014-11-10 10:23:06 +09:00
c97636aef4 Fixed lines clockwiseness to be consistent with other primitives. 2014-11-10 09:36:01 +09:00
ee3355fe8e Version number 2014-11-07 17:43:00 +09:00
1e30400f80 Added PushStyleVar(),PopStyleVar() helpers.
BeginChild() allows to specify negative sizes to specify "use remaining minus xx".
Added a simple example console into the demo window.
2014-11-07 17:22:38 +09:00
3a64c77826 Renamed IsHovered() to IsItemHovered() 2014-11-07 15:49:14 +09:00
e19f0d370a Added dummy IMGUI_API definition in front of entry-points for silly DLL action 2014-11-07 15:40:58 +09:00
6c192f3221 Added GetContentRegionMax() supporting columns. Some bug fixes with using columns. 2014-11-07 15:17:04 +09:00
78645a7dba Added word-wrapping API TextWrapped(), PushTextWrapPos(), PopTextWrapPos()
Added word-wrapping sample in the test window.
Added IsItemFocused() to tell if last widget is being focused for keyboard input.
2014-11-07 14:45:56 +09:00
74363c5a43 Fixed column using a "funny scale factor" (non power of two) #67 2014-10-26 21:33:34 +00:00
0b10cf4bd7 Fixed some typos in comments 2014-10-26 21:31:34 +00:00
3d84858755 Made with the NoResize flag can still use auto-fitting. Added SetWindowSize(). 2014-10-26 20:07:15 +00:00
fad5e45d2c Minor tweaks 2014-10-26 19:56:57 +00:00
05a3a9b962 Merge pull request #66 from JarrettBillingsley/master
Added callback versions of PlotLines/PlotHistogram
2014-10-26 20:53:40 +01:00
85eee4a4c5 Added overloads of ImGui::PlotLines and ImGui::PlotHistogram which take a value getter function instead of raw value data, and changed the implementation of the original overloads to use this new implementation. 2014-10-26 12:25:00 -07:00
4c4798546e Merge pull request #1 from ocornut/master
GCC warning fix
2014-10-26 12:22:27 -07:00
f768579377 GCC warning fix 2014-10-26 18:57:19 +00:00
e6eafd6fa8 Fixed warnings for GCC -Wpedantic 2014-10-26 15:08:28 +00:00
58 changed files with 9224 additions and 6977 deletions

13
.gitignore vendored
View File

@ -1,14 +1 @@
## Visual Studio files
examples/directx9_example/Debug/*
examples/directx9_example/Release/*
examples/directx9_example/ipch/*
examples/opengl_example/Debug/*
examples/opengl_example/Release/*
examples/opengl_example/ipch/*
*.opensdf
*.sdf
*.suo
*.vcxproj.user
## Ini files
imgui.ini

17
.travis.yml Normal file
View File

@ -0,0 +1,17 @@
language: cpp
os:
- linux
compiler:
- gcc
- clang
before_install:
- if [ $TRAVIS_OS_NAME == linux ]; then sudo add-apt-repository -y ppa:pyglfw/pyglfw && sudo apt-get update -qq && sudo apt-get install -y --no-install-recommends libglfw3-dev libglew-dev libxrandr-dev libxi-dev libxxf86vm-dev; fi
- if [ $TRAVIS_OS_NAME == osx ]; then brew update && brew install glew && brew install glfw3; fi
script:
- make -C examples/opengl_example
- make -C examples/opengl3_example

View File

@ -1,13 +1,23 @@
ImGui
=====
[![Build Status](https://travis-ci.org/ocornut/imgui.svg?branch=master)](https://travis-ci.org/ocornut/imgui)
ImGui is a bloat-free graphical user interface library for C++. It outputs vertex buffers that you can render in your 3D-pipeline enabled application. It is portable, renderer agnostic and carries minimal amount of dependencies (only 3 files are needed). It is based on an "immediate" graphical user interface paradigm which allows you to build user interfaces with ease.
ImGui is a bloat-free graphical user interface library for C++. It outputs vertex buffers that you can render in your 3D-pipeline enabled application. It is portable, renderer agnostic and carries minimal amount of dependencies. It is based on an "immediate" graphical user interface paradigm which allows you to build user interfaces with ease.
ImGui is designed to enable fast iteration and allow programmers to create "content creation" or "debug" tools (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal, and thus lacks certain features normally found in more high-level libraries
ImGui is designed to enable fast iteration and allow programmers to create "content creation" or "debug" tools (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal, and thus lacks certain features normally found in more high-level libraries.
ImGui is particularly suited to integration in 3D applications, fullscreen applications, embedded applications, games, or any applications on consoles platforms where operating system features are non-standard.
After ImGui is setup in your engine, you can use it like in this example:
ImGui is self-contained within 6 files that you can easily copy and compile into your application/engine:
- imgui.cpp
- imgui.h
- imconfig.h (empty by default, user-editable)
- stb_rect_pack.h
- stb_textedit.h
- stb_truetype.h
Your code passes mouse/keyboard inputs and settings to ImGui (see example applications for more details). After ImGui is setup, you can use it like in this example:
![screenshot of sample code alongside its output with ImGui](/web/code_sample_01.png?raw=true)
@ -22,8 +32,9 @@ Gallery
![screenshot 2](/web/test_window_02.png?raw=true)
![screenshot 3](/web/test_window_03.png?raw=true)
![screenshot 4](/web/test_window_04.png?raw=true)
![screenshot 4](/web/examples_02.png?raw=true)
UTF-8 is supported for text display and input. Here using M+ font to display Japanese:
ImGui can load TTF fonts. UTF-8 is supported for text display and input. Here using M+ font to display Japanese:
![utf-8 screenshot](/web/utf8_sample_01.png?raw=true)
@ -38,39 +49,74 @@ The Immediate Mode GUI paradigm may at first appear unusual to some users. This
Frequently Asked Question
-------------------------
<b>How do you use ImGui on a platform that may not have a mouse and keyboard?</b>
I recommend using [Synergy](http://synergy-project.org). With the uSynergy.c micro client running you can seamlessly use your PC input devices from a video game console or a tablet. ImGui was also designed to function with touch inputs if you increase the padding of widgets to compensate for the lack of precision of touch devices, but it is recommended you use a mouse to allow optimising for screen real-estate.
<b>Where are samples?</b>
The bulk of example user code is contained within the ImGui::ShowTestWindow() function. It covers most features of ImGui so you can read the code and call the function itself to see its output. Ready-to-go example applications covering different versions of OpenGL/DirectX are provided in the examples/ folder.
<b>How do you use ImGui on a platform that may not have a mouse or keyboard?</b>
I recommend using [Synergy](http://synergy-project.org). With the uSynergy.c micro client running on your platform and connecting to your PC, you can seamlessly use your PC input devices from a video game console or a tablet. ImGui allows to increase the hit box of widgets (via the _TouchPadding_ setting) to accomodate a little for the lack of precision of touch inputs, but it is recommended you use a mouse to allow optimising for screen real-estate.
<b>I integrated ImGui in my engine and the text or lines are blurry..</b>
- Try adjusting ImGui::GetIO().PixelCenterOffset to 0.0f or 0.5f.
- In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
<b>Can you create elaborate/serious tools with ImGui?</b>
Yes. I have written data browsers, debuggers, profilers and all sort of non-trivial tools with the library. There's no reason you cannot, and in my experience the simplicity of the API is very empowering. However note that ImGui is programmer centric and the immediate-mode GUI paradigm might requires a bit of adaptation before you can realize its full potential.
<b>Is ImGui fast?</b>
Down the fundation of its visual design, ImGui is engineered to be fairly performant both in term of CPU and GPU usage. Running elaborate code and creating elaborate UI will of course have a cost but ImGui aims to minimize it.
Mileage may vary but the following screenshot should give you an idea of the cost of running and rendering UI code (In the case of a trivial demo application like this one, your driver/os setup may be a bottleneck and cause higher variation or throttled framerate. Testing performance as part of a real application is recommended).
![performance screenshot](/web/performance_01_close_up.png?raw=true)
This is showing framerate on my 2011 iMac running Windows 7, OpenGL, AMD Radeon HD 6700M. ([click here for the full-size picture](/web/performance_01.png)).
In contrast, librairies featuring higher-quality rendering and layouting techniques may have a higher resources footprint.
<b>Can you reskin the look of ImGui?</b>
Yes, you can alter the look of the interface to some degree: changing colors, sizes and padding, font. However, as ImGui is designed and optimised to create debug tools, the amount of skinning you can apply is limited. There is only so much you can stray away from the default look and feel of the interface. The example below uses modified settings to create a more compact UI with different colors:
Yes, you can alter the look of the interface to some degree: changing colors, sizes and padding, font. However, as ImGui is designed and optimised to create debug tools, the amount of skinning you can apply is limited. There is only so much you can stray away from the default look and feel of the interface. The example below uses modified settings to create a very compact UI with different colors:
![skinning screenshot 1](/web/skinning_sample_01.png?raw=true)
<b>Can you develop features xxxx for ImGui?</b>
<b>Why using C++ (as opposed to C)?</b>
Please use GitHub 'Issues' facilities to suggest and discuss improvements. If you are company and would like specific non-trivial features to be implemented, I am available for hire to work on or with ImGui. Donations are also welcome to support further work on the library.
ImGui takes advantage of a few C++ features for convenience but nothing in the realm of Boost-insanity/quagmire. In particular, function overloading and default parameters are used to make the API easier to use and code more terse. Doing so I believe the API is sitting on a sweet spot and giving up on those features would make the API more cumbersome. Other features such as namespace, constructors and templates (in the case of the ImVector<> class) are also relied on as a convenience but could be removed.
Shall someone wants to use ImGui from another language, it should be possible to wrap ImGui to be used from a raw C API in the future.
Donate
------
<b>Can I donate to support the development of ImGui?</b>
Yes please! I have setup an [**ImGui Patreon page**](http://www.patreon.com/imgui) if you want to donate and enable me to spend more time improving the library. If your company uses ImGui on a commercial project please consider making a small contribution. One-off donations are also greatly appreciated. I am also available for hire to work on or with ImGui. Thanks!
Credits
-------
Developed by [Omar Cornut](http://www.miracleworld.net). The library was developed with the support of [Media Molecule](http://www.mediamolecule.com) and first used internally on the game [Tearaway](http://tearaway.mediamolecule.com).
Developed by [Omar Cornut](http://www.miracleworld.net) and every direct or indirect contributors to the GitHub. The early version of this library was developed with the support of [Media Molecule](http://www.mediamolecule.com) and first used internally on the game [Tearaway](http://tearaway.mediamolecule.com).
Embeds [proggy_clean](http://upperbounds.net) font by Tristan Grimmer (MIT license).
Embeds [M+ fonts](http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html) font by Coji Morishita (free software license).
Embeds [ProggyClean.ttf](http://upperbounds.net) font by Tristan Grimmer (MIT license).
Inspiration, feedback, and testing: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. Thanks!
Embeds [stb_textedit.h, stb_truetype.h, stb_rectpack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain).
Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. And everybody posting feedback, questions and patches on the GitHub.
ImGui is financially supported on [**Patreon**](http://www.patreon.com/imgui).
Special supporters
- Wild Sheep Studio
- Jetha Chan
Supporters
- Michel Courtine
And other supporters; thanks!
License
-------

28
examples/.gitignore vendored Normal file
View File

@ -0,0 +1,28 @@
## Visual Studio files
Debug/*
Release/*
ipch/*
x64/*
directx9_example/Debug/*
directx9_example/Release/*
directx9_example/ipch/*
directx9_example/x64/*
directx11_example/Debug/*
directx11_example/Release/*
directx11_example/ipch/*
directx11_example/x64/*
opengl_example/Debug/*
opengl_example/Release/*
opengl_example/ipch/*
opengl_example/x64/*
opengl3_example/Debug/*
opengl3_example/Release/*
opengl3_example/ipch/*
opengl3_example/x64/*
*.opensdf
*.sdf
*.suo
*.vcxproj.user
## Ini files
imgui.ini

View File

@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{9F316E83-5AE5-4939-A723-305A94F48005}</ProjectGuid>
<RootNamespace>directx11_example</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>$(DXSDK_DIR)/Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>d3d11.lib;d3dcompiler.lib;dxgi.lib;imm32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<AdditionalIncludeDirectories>$(DXSDK_DIR)/Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>d3d11.lib;d3dcompiler.lib;dxgi.lib;imm32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="..\..\imconfig.h" />
<ClInclude Include="..\..\imgui.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\imgui.cpp" />
<ClCompile Include="main.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="imgui">
<UniqueIdentifier>{0587d7a3-f2ce-4d56-b84f-a0005d3bfce6}</UniqueIdentifier>
</Filter>
<Filter Include="sources">
<UniqueIdentifier>{08e36723-ce4f-4cff-9662-c40801cf1acf}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\imconfig.h">
<Filter>imgui</Filter>
</ClInclude>
<ClInclude Include="..\..\imgui.h">
<Filter>imgui</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\imgui.cpp">
<Filter>imgui</Filter>
</ClCompile>
<ClCompile Include="main.cpp">
<Filter>sources</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,609 @@
// ImGui - standalone example application for DirectX 11
#include <windows.h>
#include "../../imgui.h"
// DirectX 11
#include <d3d11.h>
#include <d3dcompiler.h>
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strdup
static HWND hWnd;
static ID3D11Device* g_pd3dDevice = NULL;
static ID3D11DeviceContext* g_pd3dDeviceImmediateContext = NULL;
static IDXGISwapChain* g_pSwapChain = NULL;
static ID3D11Buffer* g_pVB = NULL;
static ID3D11RenderTargetView* g_mainRenderTargetView;
static ID3D10Blob * g_pVertexShaderBlob = NULL;
static ID3D11VertexShader* g_pVertexShader = NULL;
static ID3D11InputLayout* g_pInputLayout = NULL;
static ID3D11Buffer* g_pVertexConstantBuffer = NULL;
static ID3D10Blob * g_pPixelShaderBlob = NULL;
static ID3D11PixelShader* g_pPixelShader = NULL;
static ID3D11SamplerState* g_pFontSampler = NULL;
static ID3D11BlendState* g_blendState = NULL;
struct CUSTOMVERTEX
{
float pos[2];
float uv[2];
unsigned int col;
};
struct VERTEX_CONSTANT_BUFFER
{
float mvp[4][4];
};
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
// If text or lines are blurry when integrating ImGui in your engine:
// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
{
// Copy and convert all vertices into a single contiguous buffer
D3D11_MAPPED_SUBRESOURCE mappedResource;
if (g_pd3dDeviceImmediateContext->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource) != S_OK)
return;
CUSTOMVERTEX* vtx_dst = (CUSTOMVERTEX*)mappedResource.pData;
for (int n = 0; n < cmd_lists_count; n++)
{
const ImDrawList* cmd_list = cmd_lists[n];
const ImDrawVert* vtx_src = &cmd_list->vtx_buffer[0];
for (size_t i = 0; i < cmd_list->vtx_buffer.size(); i++)
{
vtx_dst->pos[0] = vtx_src->pos.x;
vtx_dst->pos[1] = vtx_src->pos.y;
vtx_dst->uv[0] = vtx_src->uv.x;
vtx_dst->uv[1] = vtx_src->uv.y;
vtx_dst->col = vtx_src->col;
vtx_dst++;
vtx_src++;
}
}
g_pd3dDeviceImmediateContext->Unmap(g_pVB, 0);
// Setup orthographic projection matrix into our constant buffer
{
D3D11_MAPPED_SUBRESOURCE mappedResource;
if (g_pd3dDeviceImmediateContext->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource) != S_OK)
return;
VERTEX_CONSTANT_BUFFER* pConstantBuffer = (VERTEX_CONSTANT_BUFFER*)mappedResource.pData;
const float L = 0.0f;
const float R = ImGui::GetIO().DisplaySize.x;
const float B = ImGui::GetIO().DisplaySize.y;
const float T = 0.0f;
const float mvp[4][4] =
{
{ 2.0f/(R-L), 0.0f, 0.0f, 0.0f},
{ 0.0f, 2.0f/(T-B), 0.0f, 0.0f,},
{ 0.0f, 0.0f, 0.5f, 0.0f },
{ (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
};
memcpy(&pConstantBuffer->mvp, mvp, sizeof(mvp));
g_pd3dDeviceImmediateContext->Unmap(g_pVertexConstantBuffer, 0);
}
// Setup viewport
{
D3D11_VIEWPORT vp;
memset(&vp, 0, sizeof(D3D11_VIEWPORT));
vp.Width = ImGui::GetIO().DisplaySize.x;
vp.Height = ImGui::GetIO().DisplaySize.y;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
g_pd3dDeviceImmediateContext->RSSetViewports(1, &vp);
}
// Bind shader and vertex buffers
unsigned int stride = sizeof(CUSTOMVERTEX);
unsigned int offset = 0;
g_pd3dDeviceImmediateContext->IASetInputLayout(g_pInputLayout);
g_pd3dDeviceImmediateContext->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
g_pd3dDeviceImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
g_pd3dDeviceImmediateContext->VSSetShader(g_pVertexShader, NULL, 0);
g_pd3dDeviceImmediateContext->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
g_pd3dDeviceImmediateContext->PSSetShader(g_pPixelShader, NULL, 0);
g_pd3dDeviceImmediateContext->PSSetSamplers(0, 1, &g_pFontSampler);
// Setup render state
const float blendFactor[4] = { 0.f, 0.f, 0.f, 0.f };
g_pd3dDeviceImmediateContext->OMSetBlendState(g_blendState, blendFactor, 0xffffffff);
// Render command lists
int vtx_offset = 0;
for (int n = 0; n < cmd_lists_count; n++)
{
// Render command list
const ImDrawList* cmd_list = cmd_lists[n];
for (size_t cmd_i = 0; cmd_i < cmd_list->commands.size(); cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->commands[cmd_i];
const D3D11_RECT r = { (LONG)pcmd->clip_rect.x, (LONG)pcmd->clip_rect.y, (LONG)pcmd->clip_rect.z, (LONG)pcmd->clip_rect.w };
g_pd3dDeviceImmediateContext->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->texture_id);
g_pd3dDeviceImmediateContext->RSSetScissorRects(1, &r);
g_pd3dDeviceImmediateContext->Draw(pcmd->vtx_count, vtx_offset);
vtx_offset += pcmd->vtx_count;
}
}
// Restore modified state
g_pd3dDeviceImmediateContext->IASetInputLayout(NULL);
g_pd3dDeviceImmediateContext->PSSetShader(NULL, NULL, 0);
g_pd3dDeviceImmediateContext->VSSetShader(NULL, NULL, 0);
}
HRESULT InitDeviceD3D(HWND hWnd)
{
// Setup swap chain
DXGI_SWAP_CHAIN_DESC sd;
{
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 2;
sd.BufferDesc.Width = 0;
sd.BufferDesc.Height = 0;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
}
UINT createDeviceFlags = 0;
#ifdef _DEBUG
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_FEATURE_LEVEL featureLevel;
const D3D_FEATURE_LEVEL featureLevelArray[1] = { D3D_FEATURE_LEVEL_11_0, };
if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 1, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceImmediateContext) != S_OK)
return E_FAIL;
// Setup rasterizer
{
D3D11_RASTERIZER_DESC RSDesc;
memset(&RSDesc, 0, sizeof(D3D11_RASTERIZER_DESC));
RSDesc.FillMode = D3D11_FILL_SOLID;
RSDesc.CullMode = D3D11_CULL_NONE;
RSDesc.FrontCounterClockwise = FALSE;
RSDesc.DepthBias = 0;
RSDesc.SlopeScaledDepthBias = 0.0f;
RSDesc.DepthBiasClamp = 0;
RSDesc.DepthClipEnable = TRUE;
RSDesc.ScissorEnable = TRUE;
RSDesc.AntialiasedLineEnable = FALSE;
RSDesc.MultisampleEnable = (sd.SampleDesc.Count > 1) ? TRUE : FALSE;
ID3D11RasterizerState* pRState = NULL;
g_pd3dDevice->CreateRasterizerState(&RSDesc, &pRState);
g_pd3dDeviceImmediateContext->RSSetState(pRState);
pRState->Release();
}
// Create the render target
{
ID3D11Texture2D* pBackBuffer;
D3D11_RENDER_TARGET_VIEW_DESC render_target_view_desc;
ZeroMemory(&render_target_view_desc, sizeof(render_target_view_desc));
render_target_view_desc.Format = sd.BufferDesc.Format;
render_target_view_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
g_pd3dDevice->CreateRenderTargetView(pBackBuffer, &render_target_view_desc, &g_mainRenderTargetView);
g_pd3dDeviceImmediateContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
pBackBuffer->Release();
}
// Create the vertex shader
{
static const char* vertexShader =
"cbuffer vertexBuffer : register(c0) \
{\
float4x4 ProjectionMatrix; \
};\
struct VS_INPUT\
{\
float2 pos : POSITION;\
float4 col : COLOR0;\
float2 uv : TEXCOORD0;\
};\
\
struct PS_INPUT\
{\
float4 pos : SV_POSITION;\
float4 col : COLOR0;\
float2 uv : TEXCOORD0;\
};\
\
PS_INPUT main(VS_INPUT input)\
{\
PS_INPUT output;\
output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
output.col = input.col;\
output.uv = input.uv;\
return output;\
}";
D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &g_pVertexShaderBlob, NULL);
if (g_pVertexShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
return E_FAIL;
if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK)
return E_FAIL;
// Create the input layout
D3D11_INPUT_ELEMENT_DESC localLayout[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, (size_t)(&((CUSTOMVERTEX*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((CUSTOMVERTEX*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((CUSTOMVERTEX*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
if (g_pd3dDevice->CreateInputLayout(localLayout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
return E_FAIL;
// Create the constant buffer
{
D3D11_BUFFER_DESC cbDesc;
cbDesc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
cbDesc.Usage = D3D11_USAGE_DYNAMIC;
cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cbDesc.MiscFlags = 0;
g_pd3dDevice->CreateBuffer(&cbDesc, NULL, &g_pVertexConstantBuffer);
}
}
// Create the pixel shader
{
static const char* pixelShader =
"struct PS_INPUT\
{\
float4 pos : SV_POSITION;\
float4 col : COLOR0;\
float2 uv : TEXCOORD0;\
};\
sampler sampler0;\
Texture2D texture0;\
\
float4 main(PS_INPUT input) : SV_Target\
{\
float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
return out_col; \
}";
D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &g_pPixelShaderBlob, NULL);
if (g_pPixelShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
return E_FAIL;
if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK)
return E_FAIL;
}
// Create the blending setup
{
D3D11_BLEND_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.AlphaToCoverageEnable = false;
desc.RenderTarget[0].BlendEnable = true;
desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
g_pd3dDevice->CreateBlendState(&desc, &g_blendState);
}
return S_OK;
}
void CleanupDevice()
{
if (g_pd3dDeviceImmediateContext) g_pd3dDeviceImmediateContext->ClearState();
// InitImGui
if (g_pFontSampler) g_pFontSampler->Release();
if (ID3D11ShaderResourceView* font_texture_view = (ID3D11ShaderResourceView*)ImGui::GetIO().Fonts->TexID)
font_texture_view->Release();
if (g_pVB) g_pVB->Release();
// InitDeviceD3D
if (g_blendState) g_blendState->Release();
if (g_pPixelShader) g_pPixelShader->Release();
if (g_pPixelShaderBlob) g_pPixelShaderBlob->Release();
if (g_pVertexConstantBuffer) g_pVertexConstantBuffer->Release();
if (g_pInputLayout) g_pInputLayout->Release();
if (g_pVertexShader) g_pVertexShader->Release();
if (g_pVertexShaderBlob) g_pVertexShaderBlob->Release();
if (g_mainRenderTargetView) g_mainRenderTargetView->Release();
if (g_pSwapChain) g_pSwapChain->Release();
if (g_pd3dDeviceImmediateContext) g_pd3dDeviceImmediateContext->Release();
if (g_pd3dDevice) g_pd3dDevice->Release();
}
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
ImGuiIO& io = ImGui::GetIO();
switch (msg)
{
case WM_LBUTTONDOWN:
io.MouseDown[0] = true;
return true;
case WM_LBUTTONUP:
io.MouseDown[0] = false;
return true;
case WM_RBUTTONDOWN:
io.MouseDown[1] = true;
return true;
case WM_RBUTTONUP:
io.MouseDown[1] = false;
return true;
case WM_MOUSEWHEEL:
io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
return true;
case WM_MOUSEMOVE:
// Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
io.MousePos.x = (signed short)(lParam);
io.MousePos.y = (signed short)(lParam >> 16);
return true;
case WM_CHAR:
// You can also use ToAscii()+GetKeyboardState() to retrieve characters.
if (wParam > 0 && wParam < 0x10000)
io.AddInputCharacter((unsigned short)wParam);
return true;
case WM_DESTROY:
CleanupDevice();
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
void LoadFontsTexture()
{
// Load one or more font
ImGuiIO& io = ImGui::GetIO();
//ImFont* my_font1 = io.Fonts->AddFontDefault();
//ImFont* my_font2 = io.Fonts->AddFontFromFileTTF("extra_fonts/Karla-Regular.ttf", 15.0f);
//ImFont* my_font3 = io.Fonts->AddFontFromFileTTF("extra_fonts/ProggyClean.ttf", 13.0f); my_font3->DisplayOffset.y += 1;
//ImFont* my_font4 = io.Fonts->AddFontFromFileTTF("extra_fonts/ProggyTiny.ttf", 10.0f); my_font4->DisplayOffset.y += 1;
//ImFont* my_font5 = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 20.0f, io.Fonts->GetGlyphRangesJapanese());
// Build
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
// Create texture
D3D11_TEXTURE2D_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.Width = width;
desc.Height = height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
ID3D11Texture2D *pTexture = NULL;
D3D11_SUBRESOURCE_DATA subResource;
subResource.pSysMem = pixels;
subResource.SysMemPitch = desc.Width * 4;
subResource.SysMemSlicePitch = 0;
g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
// Create texture view
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
ZeroMemory(&srvDesc, sizeof(srvDesc));
srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = desc.MipLevels;
srvDesc.Texture2D.MostDetailedMip = 0;
ID3D11ShaderResourceView* font_texture_view = NULL;
g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &font_texture_view);
pTexture->Release();
// Store our identifier
io.Fonts->TexID = (void *)font_texture_view;
}
void InitImGui()
{
RECT rect;
GetClientRect(hWnd, &rect);
int display_w = (int)(rect.right - rect.left);
int display_h = (int)(rect.bottom - rect.top);
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = ImVec2((float)display_w, (float)display_h); // Display size, in pixels. For clamping windows positions.
io.DeltaTime = 1.0f/60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our time step is variable)
io.KeyMap[ImGuiKey_Tab] = VK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime.
io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
io.KeyMap[ImGuiKey_DownArrow] = VK_UP;
io.KeyMap[ImGuiKey_Home] = VK_HOME;
io.KeyMap[ImGuiKey_End] = VK_END;
io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
io.KeyMap[ImGuiKey_A] = 'A';
io.KeyMap[ImGuiKey_C] = 'C';
io.KeyMap[ImGuiKey_V] = 'V';
io.KeyMap[ImGuiKey_X] = 'X';
io.KeyMap[ImGuiKey_Y] = 'Y';
io.KeyMap[ImGuiKey_Z] = 'Z';
io.RenderDrawListsFn = ImImpl_RenderDrawLists;
// Create the vertex buffer
{
D3D11_BUFFER_DESC bufferDesc;
memset(&bufferDesc, 0, sizeof(D3D11_BUFFER_DESC));
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.ByteWidth = 100000 * sizeof(CUSTOMVERTEX); // Maybe we should handle that more dynamically?
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bufferDesc.MiscFlags = 0;
if (g_pd3dDevice->CreateBuffer(&bufferDesc, NULL, &g_pVB) < 0)
{
IM_ASSERT(0);
return;
}
}
// Load fonts
LoadFontsTexture();
// Create texture sampler
{
D3D11_SAMPLER_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
desc.MipLODBias = 0.f;
desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
desc.MinLOD = 0.f;
desc.MaxLOD = 0.f;
g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler);
}
}
INT64 ticks_per_second = 0;
INT64 last_time = 0;
void UpdateImGui()
{
ImGuiIO& io = ImGui::GetIO();
// Setup time step
INT64 current_time;
QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
io.DeltaTime = (float)(current_time - last_time) / ticks_per_second;
last_time = current_time;
// Setup inputs
// (we already got mouse position, buttons, wheel from the window message callback)
BYTE keystate[256];
GetKeyboardState(keystate);
for (int i = 0; i < 256; i++)
io.KeysDown[i] = (keystate[i] & 0x80) != 0;
io.KeyCtrl = (keystate[VK_CONTROL] & 0x80) != 0;
io.KeyShift = (keystate[VK_SHIFT] & 0x80) != 0;
// io.MousePos : filled by WM_MOUSEMOVE event
// io.MouseDown : filled by WM_*BUTTON* events
// io.MouseWheel : filled by WM_MOUSEWHEEL events
// Start the frame
ImGui::NewFrame();
}
int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int)
{
// Register the window class
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, LoadCursor(NULL, IDC_ARROW), NULL, NULL, L"ImGui Example", NULL };
RegisterClassEx(&wc);
// Create the application's window
hWnd = CreateWindow(L"ImGui Example", L"ImGui DirectX11 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
return 1;
if (!QueryPerformanceCounter((LARGE_INTEGER *)&last_time))
return 1;
// Initialize Direct3D
if (InitDeviceD3D(hWnd) < 0)
{
CleanupDevice();
UnregisterClass(L"ImGui Example", wc.hInstance);
return 1;
}
// Show the window
ShowWindow(hWnd, SW_SHOWDEFAULT);
UpdateWindow(hWnd);
InitImGui();
bool show_test_window = true;
bool show_another_window = false;
ImVec4 clear_col = ImColor(114, 144, 154);
// Enter the message loop
MSG msg;
ZeroMemory(&msg, sizeof(msg));
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
continue;
}
UpdateImGui();
// 1. Show a simple window
// Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
{
static float f;
ImGui::Text("Hello, world!");
ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
ImGui::ColorEdit3("clear color", (float*)&clear_col);
if (ImGui::Button("Test Window")) show_test_window ^= 1;
if (ImGui::Button("Another Window")) show_another_window ^= 1;
// Calculate and show frame rate
static float ms_per_frame[120] = { 0 };
static int ms_per_frame_idx = 0;
static float ms_per_frame_accum = 0.0f;
ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f;
ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
const float ms_per_frame_avg = ms_per_frame_accum / 120;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
}
// 2. Show another simple window, this time using an explicit Begin/End pair
if (show_another_window)
{
ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
ImGui::Text("Hello");
ImGui::End();
}
// 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
if (show_test_window)
{
ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCondition_FirstUseEver); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
ImGui::ShowTestWindow(&show_test_window);
}
// Rendering
g_pd3dDeviceImmediateContext->ClearRenderTargetView(g_mainRenderTargetView, (float*)&clear_col);
ImGui::Render();
g_pSwapChain->Present(0, 0);
}
ImGui::Shutdown();
UnregisterClass(L"ImGui Example", wc.hInstance);
return 0;
}

View File

@ -1,20 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "directx9_example", "directx9_example.vcxproj", "{4165A294-21F2-44CA-9B38-E3F935ABADF5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4165A294-21F2-44CA-9B38-E3F935ABADF5}.Debug|Win32.ActiveCfg = Debug|Win32
{4165A294-21F2-44CA-9B38-E3F935ABADF5}.Debug|Win32.Build.0 = Debug|Win32
{4165A294-21F2-44CA-9B38-E3F935ABADF5}.Release|Win32.ActiveCfg = Release|Win32
{4165A294-21F2-44CA-9B38-E3F935ABADF5}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -46,7 +46,7 @@
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>$(DXSDK_DIR)Lib\x86;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>d3d9.lib;d3dx9d.lib;dxerr.lib;dxguid.lib;winmm.lib;comctl32.lib;gdi32.lib;imm32.lib;user32.lib</AdditionalDependencies>
<AdditionalDependencies>d3d9.lib;d3dx9d.lib;dxerr.lib;dxguid.lib;imm32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<SubSystem>
</SubSystem>
</Link>
@ -64,7 +64,7 @@
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalLibraryDirectories>$(DXSDK_DIR)Lib\x86;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>d3d9.lib;d3dx9d.lib;dxerr.lib;dxguid.lib;winmm.lib;comctl32.lib;gdi32.lib;imm32.lib;user32.lib</AdditionalDependencies>
<AdditionalDependencies>d3d9.lib;d3dx9d.lib;dxerr.lib;dxguid.lib;imm32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<SubSystem>
</SubSystem>
</Link>
@ -76,10 +76,6 @@
<ItemGroup>
<ClInclude Include="..\..\imconfig.h" />
<ClInclude Include="..\..\imgui.h" />
<ClInclude Include="..\..\stb_textedit.h" />
</ItemGroup>
<ItemGroup>
<None Include="..\..\LICENSE" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">

View File

@ -1,13 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="imgui">
<UniqueIdentifier>{ac86c4ce-1d96-47a9-9ace-f8970c3bd485}</UniqueIdentifier>
</Filter>
<Filter Include="sources">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="imgui">
<UniqueIdentifier>{a82cba23-9de0-45c2-b1e3-2eb1666702de}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.cpp">
@ -24,13 +24,5 @@
<ClInclude Include="..\..\imgui.h">
<Filter>imgui</Filter>
</ClInclude>
<ClInclude Include="..\..\stb_textedit.h">
<Filter>imgui</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<None Include="..\..\LICENSE">
<Filter>imgui</Filter>
</None>
</ItemGroup>
</Project>

View File

@ -1,30 +1,30 @@
// ImGui - standalone example application for DirectX 9
#include <windows.h>
#include <imm.h>
#include <mmsystem.h>
#include "../../imgui.h"
// DirectX 9
#include <d3dx9.h>
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#include "../../imgui.h"
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strdup
static HWND hWnd;
static HWND hWnd;
static LPDIRECT3D9 g_pD3D = NULL; // Used to create the D3DDevice
static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; // Our rendering device
static LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL; // Buffer to hold vertices
static LPDIRECT3DTEXTURE9 g_pTexture = NULL; // Our texture
struct CUSTOMVERTEX
{
D3DXVECTOR3 position;
D3DCOLOR color;
float tu, tv;
D3DXVECTOR3 pos;
D3DCOLOR col;
D3DXVECTOR2 uv;
};
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
// If text or lines are blurry when integrating ImGui in your engine:
// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
// - try adjusting ImGui::GetIO().PixelCenterOffset to 0.5f or 0.375f
static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
{
size_t total_vtx_count = 0;
@ -35,7 +35,7 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c
// Copy and convert all vertices into a single contiguous buffer
CUSTOMVERTEX* vtx_dst;
if (g_pVB->Lock(0, total_vtx_count, (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
if (g_pVB->Lock(0, (UINT)total_vtx_count, (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
return;
for (int n = 0; n < cmd_lists_count; n++)
{
@ -43,12 +43,12 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c
const ImDrawVert* vtx_src = &cmd_list->vtx_buffer[0];
for (size_t i = 0; i < cmd_list->vtx_buffer.size(); i++)
{
vtx_dst->position.x = vtx_src->pos.x;
vtx_dst->position.y = vtx_src->pos.y;
vtx_dst->position.z = 0.0f;
vtx_dst->color = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000)>>16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9
vtx_dst->tu = vtx_src->uv.x;
vtx_dst->tv = vtx_src->uv.y;
vtx_dst->pos.x = vtx_src->pos.x;
vtx_dst->pos.y = vtx_src->pos.y;
vtx_dst->pos.z = 0.0f;
vtx_dst->col = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000)>>16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9
vtx_dst->uv.x = vtx_src->uv.x;
vtx_dst->uv.y = vtx_src->uv.y;
vtx_dst++;
vtx_src++;
}
@ -68,15 +68,13 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c
g_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
g_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
g_pd3dDevice->SetRenderState( D3DRS_SCISSORTESTENABLE, true );
// Setup texture
g_pd3dDevice->SetTexture( 0, g_pTexture );
g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE );
g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
// Setup orthographic projection matrix
D3DXMATRIXA16 mat;
@ -92,10 +90,11 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c
{
// Render command list
const ImDrawList* cmd_list = cmd_lists[n];
const ImDrawCmd* pcmd_end = cmd_list->commands.end();
for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++)
for (size_t cmd_i = 0; cmd_i < cmd_list->commands.size(); cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->commands[cmd_i];
const RECT r = { (LONG)pcmd->clip_rect.x, (LONG)pcmd->clip_rect.y, (LONG)pcmd->clip_rect.z, (LONG)pcmd->clip_rect.w };
g_pd3dDevice->SetTexture( 0, (LPDIRECT3DTEXTURE9)pcmd->texture_id );
g_pd3dDevice->SetScissorRect(&r);
g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, vtx_offset, pcmd->vtx_count/3);
vtx_offset += pcmd->vtx_count;
@ -103,7 +102,7 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c
}
}
HRESULT InitD3D(HWND hWnd)
HRESULT InitDeviceD3D(HWND hWnd)
{
if (NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)))
return E_FAIL;
@ -124,19 +123,19 @@ HRESULT InitD3D(HWND hWnd)
return S_OK;
}
void Cleanup()
void CleanupDevice()
{
if (g_pTexture != NULL)
g_pTexture->Release();
// InitImGui
if (g_pVB) g_pVB->Release();
if (g_pd3dDevice != NULL)
g_pd3dDevice->Release();
if (g_pD3D != NULL)
g_pD3D->Release();
// InitDeviceD3D
if (LPDIRECT3DTEXTURE9 tex = (LPDIRECT3DTEXTURE9)ImGui::GetIO().Fonts->TexID)
tex->Release();
if (g_pd3dDevice) g_pd3dDevice->Release();
if (g_pD3D) g_pD3D->Release();
}
LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
ImGuiIO& io = ImGui::GetIO();
switch (msg)
@ -154,8 +153,7 @@ LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
io.MouseDown[1] = false;
return true;
case WM_MOUSEWHEEL:
// Mouse wheel: -1,0,+1
io.MouseWheel = GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1 : -1;
io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
return true;
case WM_MOUSEMOVE:
// Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
@ -168,36 +166,62 @@ LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
io.AddInputCharacter((unsigned short)wParam);
return true;
case WM_DESTROY:
Cleanup();
CleanupDevice();
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
// Notify OS Input Method Editor of text input position (e.g. when using Japanese/Chinese inputs, otherwise this isn't needed)
static void ImImpl_ImeSetInputScreenPosFn(int x, int y)
void LoadFontsTexture()
{
if (HIMC himc = ImmGetContext(hWnd))
// Load one or more font
ImGuiIO& io = ImGui::GetIO();
//ImFont* my_font1 = io.Fonts->AddFontDefault();
//ImFont* my_font2 = io.Fonts->AddFontFromFileTTF("extra_fonts/Karla-Regular.ttf", 15.0f);
//ImFont* my_font3 = io.Fonts->AddFontFromFileTTF("extra_fonts/ProggyClean.ttf", 13.0f); my_font3->DisplayOffset.y += 1;
//ImFont* my_font4 = io.Fonts->AddFontFromFileTTF("extra_fonts/ProggyTiny.ttf", 10.0f); my_font4->DisplayOffset.y += 1;
//ImFont* my_font5 = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 20.0f, io.Fonts->GetGlyphRangesJapanese());
// Build
unsigned char* pixels;
int width, height, bytes_per_pixel;
io.Fonts->GetTexDataAsAlpha8(&pixels, &width, &height, &bytes_per_pixel);
// Create texture
LPDIRECT3DTEXTURE9 pTexture = NULL;
if (D3DXCreateTexture(g_pd3dDevice, width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8, D3DPOOL_DEFAULT, &pTexture) < 0)
{
COMPOSITIONFORM cf;
cf.ptCurrentPos.x = x;
cf.ptCurrentPos.y = y;
cf.dwStyle = CFS_FORCE_POSITION;
ImmSetCompositionWindow(himc, &cf);
IM_ASSERT(0);
return;
}
// Copy pixels
D3DLOCKED_RECT tex_locked_rect;
if (pTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK)
{
IM_ASSERT(0);
return;
}
for (int y = 0; y < height; y++)
memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel));
pTexture->UnlockRect(0);
// Store our identifier
io.Fonts->TexID = (void *)pTexture;
}
void InitImGui()
{
RECT rect;
GetClientRect(hWnd, &rect);
int display_w = (int)(rect.right - rect.left);
int display_h = (int)(rect.bottom - rect.top);
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top)); // Display size, in pixels. For clamping windows positions.
io.DeltaTime = 1.0f/60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our timestep is variable)
io.PixelCenterOffset = 0.0f; // Align Direct3D Texels
io.KeyMap[ImGuiKey_Tab] = VK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime.
io.DisplaySize = ImVec2((float)display_w, (float)display_h); // Display size, in pixels. For clamping windows positions.
io.DeltaTime = 1.0f/60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our time step is variable)
io.KeyMap[ImGuiKey_Tab] = VK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime.
io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
@ -216,7 +240,6 @@ void InitImGui()
io.KeyMap[ImGuiKey_Z] = 'Z';
io.RenderDrawListsFn = ImImpl_RenderDrawLists;
io.ImeSetInputScreenPosFn = ImImpl_ImeSetInputScreenPosFn;
// Create the vertex buffer
if (g_pd3dDevice->CreateVertexBuffer(10000 * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0)
@ -225,29 +248,21 @@ void InitImGui()
return;
}
// Load font texture
const void* png_data;
unsigned int png_size;
ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
if (D3DXCreateTextureFromFileInMemory(g_pd3dDevice, png_data, png_size, &g_pTexture) < 0)
{
IM_ASSERT(0);
return;
}
LoadFontsTexture();
}
INT64 ticks_per_second = 0;
INT64 time = 0;
INT64 last_time = 0;
void UpdateImGui()
{
ImGuiIO& io = ImGui::GetIO();
// Setup timestep
// Setup time step
INT64 current_time;
QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
io.DeltaTime = (float)(current_time - time) / ticks_per_second;
time = current_time;
io.DeltaTime = (float)(current_time - last_time) / ticks_per_second;
last_time = current_time;
// Setup inputs
// (we already got mouse position, buttons, wheel from the window message callback)
@ -268,7 +283,7 @@ void UpdateImGui()
int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int)
{
// Register the window class
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, L"ImGui Example", NULL };
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, LoadCursor(NULL, IDC_ARROW), NULL, NULL, L"ImGui Example", NULL };
RegisterClassEx(&wc);
// Create the application's window
@ -276,14 +291,13 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int)
if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
return 1;
if (!QueryPerformanceCounter((LARGE_INTEGER *)&time))
if (!QueryPerformanceCounter((LARGE_INTEGER *)&last_time))
return 1;
// Initialize Direct3D
if (InitD3D(hWnd) < 0)
if (InitDeviceD3D(hWnd) < 0)
{
if (g_pVB)
g_pVB->Release();
CleanupDevice();
UnregisterClass(L"ImGui Example", wc.hInstance);
return 1;
}
@ -294,6 +308,10 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int)
InitImGui();
bool show_test_window = true;
bool show_another_window = false;
ImVec4 clear_col = ImColor(114, 144, 154);
// Enter the message loop
MSG msg;
ZeroMemory(&msg, sizeof(msg));
@ -305,22 +323,19 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int)
DispatchMessage(&msg);
continue;
}
UpdateImGui();
static bool show_test_window = true;
static bool show_another_window = false;
// 1. Show a simple window
// Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
{
static float f;
ImGui::Text("Hello, world!");
ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
show_test_window ^= ImGui::Button("Test Window");
show_another_window ^= ImGui::Button("Another Window");
ImGui::ColorEdit3("clear color", (float*)&clear_col);
if (ImGui::Button("Test Window")) show_test_window ^= 1;
if (ImGui::Button("Another Window")) show_another_window ^= 1;
// Calculate and show framerate
// Calculate and show frame rate
static float ms_per_frame[120] = { 0 };
static int ms_per_frame_idx = 0;
static float ms_per_frame_accum = 0.0f;
@ -343,7 +358,7 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int)
// 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
if (show_test_window)
{
ImGui::SetNewWindowDefaultPos(ImVec2(650, 20)); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCondition_FirstUseEver);
ImGui::ShowTestWindow(&show_test_window);
}
@ -351,7 +366,8 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int)
g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);
g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false);
g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(204, 153, 153), 1.0f, 0);
D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_col.x*255.0f), (int)(clear_col.y*255.0f), (int)(clear_col.z*255.0f), (int)(clear_col.w*255.0f));
g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);
if (g_pd3dDevice->BeginScene() >= 0)
{
ImGui::Render();
@ -362,9 +378,6 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int)
ImGui::Shutdown();
if (g_pVB)
g_pVB->Release();
UnregisterClass(L"ImGui Example", wc.hInstance);
return 0;
}

View File

@ -0,0 +1,38 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "opengl_example", "opengl_example\opengl_example.vcxproj", "{9CDA7840-B7A5-496D-A527-E95571496D18}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "directx9_example", "directx9_example\directx9_example.vcxproj", "{4165A294-21F2-44CA-9B38-E3F935ABADF5}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "directx11_example", "directx11_example\directx11_example.vcxproj", "{9F316E83-5AE5-4939-A723-305A94F48005}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "opengl3_example", "opengl3_example\opengl3_example.vcxproj", "{4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9CDA7840-B7A5-496D-A527-E95571496D18}.Debug|Win32.ActiveCfg = Debug|Win32
{9CDA7840-B7A5-496D-A527-E95571496D18}.Debug|Win32.Build.0 = Debug|Win32
{9CDA7840-B7A5-496D-A527-E95571496D18}.Release|Win32.ActiveCfg = Release|Win32
{9CDA7840-B7A5-496D-A527-E95571496D18}.Release|Win32.Build.0 = Release|Win32
{4165A294-21F2-44CA-9B38-E3F935ABADF5}.Debug|Win32.ActiveCfg = Debug|Win32
{4165A294-21F2-44CA-9B38-E3F935ABADF5}.Debug|Win32.Build.0 = Debug|Win32
{4165A294-21F2-44CA-9B38-E3F935ABADF5}.Release|Win32.ActiveCfg = Release|Win32
{4165A294-21F2-44CA-9B38-E3F935ABADF5}.Release|Win32.Build.0 = Release|Win32
{9F316E83-5AE5-4939-A723-305A94F48005}.Debug|Win32.ActiveCfg = Debug|Win32
{9F316E83-5AE5-4939-A723-305A94F48005}.Debug|Win32.Build.0 = Debug|Win32
{9F316E83-5AE5-4939-A723-305A94F48005}.Release|Win32.ActiveCfg = Release|Win32
{9F316E83-5AE5-4939-A723-305A94F48005}.Release|Win32.Build.0 = Release|Win32
{4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}.Debug|Win32.ActiveCfg = Debug|Win32
{4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}.Debug|Win32.Build.0 = Debug|Win32
{4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}.Release|Win32.ActiveCfg = Release|Win32
{4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,52 @@
#
# Cross Platform Make file
#
# Compatible with Ubuntu 14.04.1 and Mac OS X
#
#
# if you using Mac OS X:
# You should install glew via homebrew
# brew install glew
# Also you'll need glfw
# http://www.glfw.org
#
#CXX = g++
OBJS = main.o
OBJS += ../../imgui.o
UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S), Linux) #LINUX
ECHO_MESSAGE = "Linux"
CXXFLAGS = -I../../ `pkg-config --cflags glfw3`
CXXFLAGS += -Wall
LIBS = `pkg-config --static --libs glfw3` -lGLEW
endif
ifeq ($(UNAME_S), Darwin) #APPLE
ECHO_MESSAGE = "Mac OS X"
LIBS = -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo
LIBS += -L/usr/local/Cellar/glew/1.10.0/lib -L/usr/local/lib
LIBS += -lglew -lglfw3
CXXFLAGS = -I../../ -I/usr/local/Cellar/glew/1.10.0/include -I/usr/local/include
CXXFLAGS += -Wall
# CXXFLAGS += -D__APPLE__
endif
.cpp.o:
$(CXX) $(CXXFLAGS) -c -o $@ $<
all:imgui_example
@echo Build complete for $(ECHO_MESSAGE)
imgui_example:$(OBJS)
$(CXX) -o imgui_example $(OBJS) $(CXXFLAGS) $(LIBS)
clean:
rm $(OBJS)

View File

@ -0,0 +1,398 @@
// ImGui - standalone example application for OpenGL 3, using programmable pipeline
#ifdef _MSC_VER
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#endif
#ifdef __clang__
#pragma clang diagnostic ignored "-Wunused-function" // warning: unused function
#endif
#include "../../imgui.h"
#include <stdio.h>
// Glfw/Glew
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
static GLFWwindow* window;
static bool mousePressed[2] = { false, false };
// Shader variables
static int shader_handle, vert_handle, frag_handle;
static int texture_location, proj_mtx_location;
static int position_location, uv_location, colour_location;
static size_t vbo_max_size = 20000;
static unsigned int vbo_handle, vao_handle;
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
// If text or lines are blurry when integrating ImGui in your engine:
// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
{
if (cmd_lists_count == 0)
return;
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glActiveTexture(GL_TEXTURE0);
// Setup orthographic projection matrix
const float width = ImGui::GetIO().DisplaySize.x;
const float height = ImGui::GetIO().DisplaySize.y;
const float ortho_projection[4][4] =
{
{ 2.0f/width, 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f/-height, 0.0f, 0.0f },
{ 0.0f, 0.0f, -1.0f, 0.0f },
{ -1.0f, 1.0f, 0.0f, 1.0f },
};
glUseProgram(shader_handle);
glUniform1i(texture_location, 0);
glUniformMatrix4fv(proj_mtx_location, 1, GL_FALSE, &ortho_projection[0][0]);
// Grow our buffer according to what we need
size_t total_vtx_count = 0;
for (int n = 0; n < cmd_lists_count; n++)
total_vtx_count += cmd_lists[n]->vtx_buffer.size();
glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
size_t neededBufferSize = total_vtx_count * sizeof(ImDrawVert);
if (neededBufferSize > vbo_max_size)
{
vbo_max_size = neededBufferSize + 5000; // Grow buffer
glBufferData(GL_ARRAY_BUFFER, vbo_max_size, NULL, GL_STREAM_DRAW);
}
// Copy and convert all vertices into a single contiguous buffer
unsigned char* buffer_data = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
if (!buffer_data)
return;
for (int n = 0; n < cmd_lists_count; n++)
{
const ImDrawList* cmd_list = cmd_lists[n];
memcpy(buffer_data, &cmd_list->vtx_buffer[0], cmd_list->vtx_buffer.size() * sizeof(ImDrawVert));
buffer_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert);
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(vao_handle);
int cmd_offset = 0;
for (int n = 0; n < cmd_lists_count; n++)
{
const ImDrawList* cmd_list = cmd_lists[n];
int vtx_offset = cmd_offset;
const ImDrawCmd* pcmd_end = cmd_list->commands.end();
for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++)
{
glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->texture_id);
glScissor((int)pcmd->clip_rect.x, (int)(height - pcmd->clip_rect.w), (int)(pcmd->clip_rect.z - pcmd->clip_rect.x), (int)(pcmd->clip_rect.w - pcmd->clip_rect.y));
glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count);
vtx_offset += pcmd->vtx_count;
}
cmd_offset = vtx_offset;
}
// Restore modified state
glBindVertexArray(0);
glUseProgram(0);
glDisable(GL_SCISSOR_TEST);
glBindTexture(GL_TEXTURE_2D, 0);
}
static const char* ImImpl_GetClipboardTextFn()
{
return glfwGetClipboardString(window);
}
static void ImImpl_SetClipboardTextFn(const char* text)
{
glfwSetClipboardString(window, text);
}
// GLFW callbacks to get events
static void glfw_error_callback(int error, const char* description)
{
fputs(description, stderr);
}
static void glfw_mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
if (action == GLFW_PRESS && button >= 0 && button < 2)
mousePressed[button] = true;
}
static void glfw_scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
ImGuiIO& io = ImGui::GetIO();
io.MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines.
}
static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
ImGuiIO& io = ImGui::GetIO();
if (action == GLFW_PRESS)
io.KeysDown[key] = true;
if (action == GLFW_RELEASE)
io.KeysDown[key] = false;
io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
}
static void glfw_char_callback(GLFWwindow* window, unsigned int c)
{
if (c > 0 && c < 0x10000)
ImGui::GetIO().AddInputCharacter((unsigned short)c);
}
void InitGL()
{
glfwSetErrorCallback(glfw_error_callback);
if (!glfwInit())
exit(1);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
window = glfwCreateWindow(1280, 720, "ImGui OpenGL3 example", NULL, NULL);
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, glfw_key_callback);
glfwSetMouseButtonCallback(window, glfw_mouse_button_callback);
glfwSetScrollCallback(window, glfw_scroll_callback);
glfwSetCharCallback(window, glfw_char_callback);
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if (GLEW_OK != err)
fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
const GLchar *vertex_shader =
"#version 330\n"
"uniform mat4 ProjMtx;\n"
"in vec2 Position;\n"
"in vec2 UV;\n"
"in vec4 Color;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* fragment_shader =
"#version 330\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
"}\n";
shader_handle = glCreateProgram();
vert_handle = glCreateShader(GL_VERTEX_SHADER);
frag_handle = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vert_handle, 1, &vertex_shader, 0);
glShaderSource(frag_handle, 1, &fragment_shader, 0);
glCompileShader(vert_handle);
glCompileShader(frag_handle);
glAttachShader(shader_handle, vert_handle);
glAttachShader(shader_handle, frag_handle);
glLinkProgram(shader_handle);
texture_location = glGetUniformLocation(shader_handle, "Texture");
proj_mtx_location = glGetUniformLocation(shader_handle, "ProjMtx");
position_location = glGetAttribLocation(shader_handle, "Position");
uv_location = glGetAttribLocation(shader_handle, "UV");
colour_location = glGetAttribLocation(shader_handle, "Color");
glGenBuffers(1, &vbo_handle);
glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
glBufferData(GL_ARRAY_BUFFER, vbo_max_size, NULL, GL_DYNAMIC_DRAW);
glGenVertexArrays(1, &vao_handle);
glBindVertexArray(vao_handle);
glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
glEnableVertexAttribArray(position_location);
glEnableVertexAttribArray(uv_location);
glEnableVertexAttribArray(colour_location);
glVertexAttribPointer(position_location, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
glVertexAttribPointer(uv_location, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
glVertexAttribPointer(colour_location, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void LoadFontsTexture()
{
ImGuiIO& io = ImGui::GetIO();
//ImFont* my_font1 = io.Fonts->AddFontDefault();
//ImFont* my_font2 = io.Fonts->AddFontFromFileTTF("extra_fonts/Karla-Regular.ttf", 15.0f);
//ImFont* my_font3 = io.Fonts->AddFontFromFileTTF("extra_fonts/ProggyClean.ttf", 13.0f); my_font3->DisplayOffset.y += 1;
//ImFont* my_font4 = io.Fonts->AddFontFromFileTTF("extra_fonts/ProggyTiny.ttf", 10.0f); my_font4->DisplayOffset.y += 1;
//ImFont* my_font5 = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 20.0f, io.Fonts->GetGlyphRangesJapanese());
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader.
GLuint tex_id;
glGenTextures(1, &tex_id);
glBindTexture(GL_TEXTURE_2D, tex_id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
// Store our identifier
io.Fonts->TexID = (void *)(intptr_t)tex_id;
}
void InitImGui()
{
ImGuiIO& io = ImGui::GetIO();
io.DeltaTime = 1.0f / 60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our timestep is variable)
io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
io.RenderDrawListsFn = ImImpl_RenderDrawLists;
io.SetClipboardTextFn = ImImpl_SetClipboardTextFn;
io.GetClipboardTextFn = ImImpl_GetClipboardTextFn;
LoadFontsTexture();
}
void UpdateImGui()
{
ImGuiIO& io = ImGui::GetIO();
// Setup resolution (every frame to accommodate for window resizing)
int w, h;
int display_w, display_h;
glfwGetWindowSize(window, &w, &h);
glfwGetFramebufferSize(window, &display_w, &display_h);
io.DisplaySize = ImVec2((float)display_w, (float)display_h); // Display size, in pixels. For clamping windows positions.
// Setup time step
static double time = 0.0f;
const double current_time = glfwGetTime();
io.DeltaTime = (float)(current_time - time);
time = current_time;
// Setup inputs
// (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
double mouse_x, mouse_y;
glfwGetCursorPos(window, &mouse_x, &mouse_y);
mouse_x *= (float)display_w / w; // Convert mouse coordinates to pixels
mouse_y *= (float)display_h / h;
io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
io.MouseDown[0] = mousePressed[0] || glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
io.MouseDown[1] = mousePressed[1] || glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0;
// Start the frame
ImGui::NewFrame();
}
// Application code
int main(int argc, char** argv)
{
InitGL();
InitImGui();
bool show_test_window = true;
bool show_another_window = false;
ImVec4 clear_col = ImColor(114, 144, 154);
while (!glfwWindowShouldClose(window))
{
ImGuiIO& io = ImGui::GetIO();
io.MouseWheel = 0;
mousePressed[0] = mousePressed[1] = false;
glfwPollEvents();
UpdateImGui();
// 1. Show a simple window
// Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
{
static float f;
ImGui::Text("Hello, world!");
ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
ImGui::ColorEdit3("clear color", (float*)&clear_col);
if (ImGui::Button("Test Window")) show_test_window ^= 1;
if (ImGui::Button("Another Window")) show_another_window ^= 1;
// Calculate and show frame rate
static float ms_per_frame[120] = { 0 };
static int ms_per_frame_idx = 0;
static float ms_per_frame_accum = 0.0f;
ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f;
ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
const float ms_per_frame_avg = ms_per_frame_accum / 120;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
}
// 2. Show another simple window, this time using an explicit Begin/End pair
if (show_another_window)
{
ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
ImGui::Text("Hello");
ImGui::End();
}
// 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
if (show_test_window)
{
ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCondition_FirstUseEver);
ImGui::ShowTestWindow(&show_test_window);
}
// Rendering
glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
glClearColor(clear_col.x, clear_col.y, clear_col.z, clear_col.w);
glClear(GL_COLOR_BUFFER_BIT);
ImGui::Render();
glfwSwapBuffers(window);
}
// Cleanup
if (vao_handle) glDeleteVertexArrays(1, &vao_handle);
if (vbo_handle) glDeleteBuffers(1, &vbo_handle);
glDetachShader(shader_handle, vert_handle);
glDetachShader(shader_handle, frag_handle);
glDeleteShader(vert_handle);
glDeleteShader(frag_handle);
glDeleteProgram(shader_handle);
ImGui::Shutdown();
glfwTerminate();
return 0;
}

View File

@ -0,0 +1,81 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{4a1fb5ea-22f5-42a8-ab92-1d2df5d47fb9}</ProjectGuid>
<RootNamespace>opengl3_example</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>$(ProjectDir)..\opengl_example\glfw\include;$(ProjectDir)..\opengl_example\glew\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>$(ProjectDir)..\opengl_example\glfw\lib-msvc100;$(ProjectDir)..\opengl_example\glew\lib\Release\Win32;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>opengl32.lib;imm32.lib;glfw3.lib;glew32s.lib;%(AdditionalDependencies)</AdditionalDependencies>
<SubSystem>NotSet</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<AdditionalIncludeDirectories>$(ProjectDir)..\opengl_example\glfw\include;$(ProjectDir)..\opengl_example\glew\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalLibraryDirectories>$(ProjectDir)..\opengl_example\glfw\lib-msvc100;$(ProjectDir)..\opengl_example\glew\lib\Release\Win32;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>opengl32.lib;imm32.lib;glfw3.lib;glew32s.lib;%(AdditionalDependencies)</AdditionalDependencies>
<SubSystem>NotSet</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\..\imgui.cpp" />
<ClCompile Include="main.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\imconfig.h" />
<ClInclude Include="..\..\imgui.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="imgui">
<UniqueIdentifier>{20b90ce4-7fcb-4731-b9a0-075f875de82d}</UniqueIdentifier>
</Filter>
<Filter Include="sources">
<UniqueIdentifier>{f18ab499-84e1-499f-8eff-9754361e0e52}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.cpp">
<Filter>sources</Filter>
</ClCompile>
<ClCompile Include="..\..\imgui.cpp">
<Filter>imgui</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\imconfig.h">
<Filter>imgui</Filter>
</ClInclude>
<ClInclude Include="..\..\imgui.h">
<Filter>imgui</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -11,7 +11,7 @@
# http://www.glfw.org
#
CXX = g++
#CXX = g++
OBJS = main.o
OBJS += ../../imgui.o
@ -22,6 +22,7 @@ UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S), Linux) #LINUX
ECHO_MESSAGE = "Linux"
CXXFLAGS = -I../../ `pkg-config --cflags glfw3`
CXXFLAGS += -Wall
LIBS = `pkg-config --static --libs glfw3` -lGLEW
endif
@ -32,11 +33,9 @@ ifeq ($(UNAME_S), Darwin) #APPLE
LIBS += -L/usr/local/Cellar/glew/1.10.0/lib -L/usr/local/lib
LIBS += -lglew -lglfw3
CXXFLAGS = -I/usr/local/Cellar/glew/1.10.0/include -I/usr/local/include
CXXFLAGS += -I../../
CXXFLAGS = -I../../ -I/usr/local/Cellar/glew/1.10.0/include -I/usr/local/include
CXXFLAGS += -Wall
# CXXFLAGS += -D__APPLE__
endif
.cpp.o:

Binary file not shown.

View File

@ -1,31 +1,27 @@
#ifdef _MSC_VER
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#include <Windows.h>
#include <Imm.h>
#endif
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h" // for .png loading
#include "../../imgui.h"
// ImGui - standalone example application for OpenGL 2, using fixed pipeline
// glew & glfw
#ifdef _MSC_VER
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#endif
#ifdef __clang__
#pragma clang diagnostic ignored "-Wunused-function" // warning: unused function
#endif
#include "../../imgui.h"
#include <stdio.h>
// Glfw/Glew
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#ifdef _MSC_VER
#define GLFW_EXPOSE_NATIVE_WIN32
#define GLFW_EXPOSE_NATIVE_WGL
#include <GLFW/glfw3native.h>
#endif
#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
static GLFWwindow* window;
static GLuint fontTex;
static bool mousePressed[2] = { false, false };
static ImVec2 mousePosScale(1.0f, 1.0f);
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
// If text or lines are blurry when integrating ImGui in your engine:
// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
// - try adjusting ImGui::GetIO().PixelCenterOffset to 0.5f or 0.375f
static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
{
if (cmd_lists_count == 0)
@ -34,6 +30,7 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c
// We are using the OpenGL fixed pipeline to make the example code simpler to read!
// A probable faster way to render would be to collate all vertices from all cmd_lists into a single vertex buffer.
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
@ -42,42 +39,48 @@ static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_c
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
// Setup texture
glBindTexture(GL_TEXTURE_2D, fontTex);
glEnable(GL_TEXTURE_2D);
// Setup orthographic projection matrix
const float width = ImGui::GetIO().DisplaySize.x;
const float height = ImGui::GetIO().DisplaySize.y;
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0.0f, width, height, 0.0f, -1.0f, +1.0f);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
// Render command lists
for (int n = 0; n < cmd_lists_count; n++)
{
const ImDrawList* cmd_list = cmd_lists[n];
const unsigned char* vtx_buffer = (const unsigned char*)cmd_list->vtx_buffer.begin();
glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer));
glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer+8));
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer+16));
const unsigned char* vtx_buffer = (const unsigned char*)&cmd_list->vtx_buffer.front();
glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, pos)));
glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, uv)));
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, col)));
int vtx_offset = 0;
const ImDrawCmd* pcmd_end = cmd_list->commands.end();
for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++)
for (size_t cmd_i = 0; cmd_i < cmd_list->commands.size(); cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->commands[cmd_i];
glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->texture_id);
glScissor((int)pcmd->clip_rect.x, (int)(height - pcmd->clip_rect.w), (int)(pcmd->clip_rect.z - pcmd->clip_rect.x), (int)(pcmd->clip_rect.w - pcmd->clip_rect.y));
glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count);
vtx_offset += pcmd->vtx_count;
}
}
glDisable(GL_SCISSOR_TEST);
// Restore modified state
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glPopAttrib();
}
// NB: ImGui already provide OS clipboard support for Windows so this isn't needed if you are using Windows only.
@ -91,22 +94,6 @@ static void ImImpl_SetClipboardTextFn(const char* text)
glfwSetClipboardString(window, text);
}
#ifdef _MSC_VER
// Notify OS Input Method Editor of text input position (e.g. when using Japanese/Chinese inputs, otherwise this isn't needed)
static void ImImpl_ImeSetInputScreenPosFn(int x, int y)
{
HWND hwnd = glfwGetWin32Window(window);
if (HIMC himc = ImmGetContext(hwnd))
{
COMPOSITIONFORM cf;
cf.ptCurrentPos.x = x;
cf.ptCurrentPos.y = y;
cf.dwStyle = CFS_FORCE_POSITION;
ImmSetCompositionWindow(himc, &cf);
}
}
#endif
// GLFW callbacks to get events
static void glfw_error_callback(int error, const char* description)
{
@ -122,7 +109,7 @@ static void glfw_mouse_button_callback(GLFWwindow* window, int button, int actio
static void glfw_scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
ImGuiIO& io = ImGui::GetIO();
io.MouseWheel = (yoffset != 0.0f) ? yoffset > 0.0f ? 1 : - 1 : 0; // Mouse wheel: -1,0,+1
io.MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines.
}
static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
@ -142,16 +129,13 @@ static void glfw_char_callback(GLFWwindow* window, unsigned int c)
ImGui::GetIO().AddInputCharacter((unsigned short)c);
}
// OpenGL code based on http://open.gl tutorials
void InitGL()
{
glfwSetErrorCallback(glfw_error_callback);
if (!glfwInit())
exit(1);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
window = glfwCreateWindow(1280, 720, "ImGui OpenGL example", NULL, NULL);
window = glfwCreateWindow(1280, 720, "ImGui OpenGL2 example", NULL, NULL);
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, glfw_key_callback);
glfwSetMouseButtonCallback(window, glfw_mouse_button_callback);
@ -161,20 +145,35 @@ void InitGL()
glewInit();
}
void LoadFontsTexture()
{
ImGuiIO& io = ImGui::GetIO();
//ImFont* my_font1 = io.Fonts->AddFontDefault();
//ImFont* my_font2 = io.Fonts->AddFontFromFileTTF("extra_fonts/Karla-Regular.ttf", 15.0f);
//ImFont* my_font3 = io.Fonts->AddFontFromFileTTF("extra_fonts/ProggyClean.ttf", 13.0f); my_font3->DisplayOffset.y += 1;
//ImFont* my_font4 = io.Fonts->AddFontFromFileTTF("extra_fonts/ProggyTiny.ttf", 10.0f); my_font4->DisplayOffset.y += 1;
//ImFont* my_font5 = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 20.0f, io.Fonts->GetGlyphRangesJapanese());
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsAlpha8(&pixels, &width, &height);
GLuint tex_id;
glGenTextures(1, &tex_id);
glBindTexture(GL_TEXTURE_2D, tex_id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, pixels);
// Store our identifier
io.Fonts->TexID = (void *)(intptr_t)tex_id;
}
void InitImGui()
{
int w, h;
int fb_w, fb_h;
glfwGetWindowSize(window, &w, &h);
glfwGetFramebufferSize(window, &fb_w, &fb_h);
mousePosScale.x = (float)fb_w / w; // Some screens e.g. Retina display have framebuffer size != from window size, and mouse inputs are given in window/screen coordinates.
mousePosScale.y = (float)fb_h / h;
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = ImVec2((float)fb_w, (float)fb_h); // Display size, in pixels. For clamping windows positions.
io.DeltaTime = 1.0f/60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our timestep is variable)
io.PixelCenterOffset = 0.0f; // Align OpenGL texels
io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
io.DeltaTime = 1.0f/60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our time step is variable)
io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
@ -195,53 +194,22 @@ void InitImGui()
io.RenderDrawListsFn = ImImpl_RenderDrawLists;
io.SetClipboardTextFn = ImImpl_SetClipboardTextFn;
io.GetClipboardTextFn = ImImpl_GetClipboardTextFn;
#ifdef _MSC_VER
io.ImeSetInputScreenPosFn = ImImpl_ImeSetInputScreenPosFn;
#endif
// Load font texture
glGenTextures(1, &fontTex);
glBindTexture(GL_TEXTURE_2D, fontTex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
#if 1
// Default font (embedded in code)
const void* png_data;
unsigned int png_size;
ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
int tex_x, tex_y, tex_comp;
void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0);
IM_ASSERT(tex_data != NULL);
#else
// Custom font from filesystem
io.Font = new ImBitmapFont();
io.Font->LoadFromFile("../../extra_fonts/mplus-2m-medium_18.fnt");
IM_ASSERT(io.Font->IsLoaded());
int tex_x, tex_y, tex_comp;
void* tex_data = stbi_load("../../extra_fonts/mplus-2m-medium_18.png", &tex_x, &tex_y, &tex_comp, 0);
IM_ASSERT(tex_data != NULL);
// Automatically find white pixel from the texture we just loaded
// (io.FontTexUvForWhite needs to contains UV coordinates pointing to a white pixel in order to render solid objects)
for (int tex_data_off = 0; tex_data_off < tex_x*tex_y; tex_data_off++)
if (((unsigned int*)tex_data)[tex_data_off] == 0xffffffff)
{
io.FontTexUvForWhite = ImVec2((float)(tex_data_off % tex_x)/(tex_x), (float)(tex_data_off / tex_x)/(tex_y));
break;
}
#endif
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data);
stbi_image_free(tex_data);
LoadFontsTexture();
}
void UpdateImGui()
{
ImGuiIO& io = ImGui::GetIO();
// Setup timestep
// Setup resolution (every frame to accommodate for window resizing)
int w, h;
int display_w, display_h;
glfwGetWindowSize(window, &w, &h);
glfwGetFramebufferSize(window, &display_w, &display_h);
io.DisplaySize = ImVec2((float)display_w, (float)display_h); // Display size, in pixels. For clamping windows positions.
// Setup time step
static double time = 0.0f;
const double current_time = glfwGetTime();
io.DeltaTime = (float)(current_time - time);
@ -251,7 +219,9 @@ void UpdateImGui()
// (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
double mouse_x, mouse_y;
glfwGetCursorPos(window, &mouse_x, &mouse_y);
io.MousePos = ImVec2((float)mouse_x * mousePosScale.x, (float)mouse_y * mousePosScale.y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
mouse_x *= (float)display_w / w; // Convert mouse coordinates to pixels
mouse_y *= (float)display_h / h;
io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
io.MouseDown[0] = mousePressed[0] || glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
io.MouseDown[1] = mousePressed[1] || glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0;
@ -265,27 +235,28 @@ int main(int argc, char** argv)
InitGL();
InitImGui();
bool show_test_window = true;
bool show_another_window = false;
ImVec4 clear_col = ImColor(114, 144, 154);
while (!glfwWindowShouldClose(window))
{
ImGuiIO& io = ImGui::GetIO();
mousePressed[0] = mousePressed[1] = false;
io.MouseWheel = 0;
glfwPollEvents();
UpdateImGui();
static bool show_test_window = true;
static bool show_another_window = false;
// 1. Show a simple window
// Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
{
static float f;
ImGui::Text("Hello, world!");
ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
show_test_window ^= ImGui::Button("Test Window");
show_another_window ^= ImGui::Button("Another Window");
ImGui::ColorEdit3("clear color", (float*)&clear_col);
if (ImGui::Button("Test Window")) show_test_window ^= 1;
if (ImGui::Button("Another Window")) show_another_window ^= 1;
// Calculate and show framerate
// Calculate and show frame rate
static float ms_per_frame[120] = { 0 };
static int ms_per_frame_idx = 0;
static float ms_per_frame_accum = 0.0f;
@ -308,19 +279,21 @@ int main(int argc, char** argv)
// 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
if (show_test_window)
{
ImGui::SetNewWindowDefaultPos(ImVec2(650, 20)); // Normally user code doesn't need/want to call this, because positions are saved in .ini file. Here we just want to make the demo initial state a bit more friendly!
ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCondition_FirstUseEver);
ImGui::ShowTestWindow(&show_test_window);
}
// Rendering
glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
glClearColor(0.8f, 0.6f, 0.6f, 1.0f);
glClearColor(clear_col.x, clear_col.y, clear_col.z, clear_col.w);
glClear(GL_COLOR_BUFFER_BIT);
ImGui::Render();
glfwSwapBuffers(window);
}
// Cleanup
ImGui::Shutdown();
glfwTerminate();
return 0;
}

View File

@ -1,20 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "opengl_example", "opengl_example.vcxproj", "{9CDA7840-B7A5-496D-A527-E95571496D18}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9CDA7840-B7A5-496D-A527-E95571496D18}.Debug|Win32.ActiveCfg = Debug|Win32
{9CDA7840-B7A5-496D-A527-E95571496D18}.Debug|Win32.Build.0 = Debug|Win32
{9CDA7840-B7A5-496D-A527-E95571496D18}.Release|Win32.ActiveCfg = Release|Win32
{9CDA7840-B7A5-496D-A527-E95571496D18}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -41,11 +41,11 @@
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>$(SolutionDir)\glfw\include;$(SolutionDir)\glew\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>$(ProjectDir)\glfw\include;$(ProjectDir)\glew\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>$(SolutionDir)\glfw\lib-msvc100;$(SolutionDir)\glew\lib\Release\Win32;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalLibraryDirectories>$(ProjectDir)\glfw\lib-msvc100;$(ProjectDir)\glew\lib\Release\Win32;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>opengl32.lib;imm32.lib;glfw3.lib;glew32s.lib;%(AdditionalDependencies)</AdditionalDependencies>
<SubSystem>NotSet</SubSystem>
</Link>
@ -56,13 +56,13 @@
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<AdditionalIncludeDirectories>$(SolutionDir)\glfw\include;$(SolutionDir)\glew\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>$(ProjectDir)\glfw\include;$(ProjectDir)\glew\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalLibraryDirectories>$(SolutionDir)\glfw\lib-msvc100;$(SolutionDir)\glew\lib\Release\Win32;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalLibraryDirectories>$(ProjectDir)\glfw\lib-msvc100;$(ProjectDir)\glew\lib\Release\Win32;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>opengl32.lib;imm32.lib;glfw3.lib;glew32s.lib;%(AdditionalDependencies)</AdditionalDependencies>
<SubSystem>NotSet</SubSystem>
</Link>
@ -74,11 +74,6 @@
<ItemGroup>
<ClInclude Include="..\..\imconfig.h" />
<ClInclude Include="..\..\imgui.h" />
<ClInclude Include="..\..\stb_textedit.h" />
<ClInclude Include="stb_image.h" />
</ItemGroup>
<ItemGroup>
<None Include="..\..\LICENSE" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">

View File

@ -18,22 +18,11 @@
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="stb_image.h">
<Filter>sources</Filter>
</ClInclude>
<ClInclude Include="..\..\imconfig.h">
<Filter>imgui</Filter>
</ClInclude>
<ClInclude Include="..\..\imgui.h">
<Filter>imgui</Filter>
</ClInclude>
<ClInclude Include="..\..\stb_textedit.h">
<Filter>imgui</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<None Include="..\..\LICENSE">
<Filter>imgui</Filter>
</None>
</ItemGroup>
</Project>

File diff suppressed because it is too large Load Diff

Binary file not shown.

BIN
extra_fonts/ProggyClean.ttf Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
extra_fonts/ProggyTiny.ttf Normal file

Binary file not shown.

View File

@ -1,100 +1,55 @@
Extra fonts for ImGui.
THOSE FONTS ARE OPTIONAL.
The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' that you can use without any external files.
ImGui embeds a copy of 'proggy_clean' that you can use without any external files.
Export your own font with bmfont (www.angelcode.com/products/bmfont).
---------------------------------
EXTRA FONTS FOR IMGUI
---------------------------------
bmfont reads fonts (.ttf, .fon, etc.) and output a .fnt file and a texture file, e.g:
ProggyClean.ttf
Copyright (c) 2004, 2005 Tristan Grimmer
MIT License
recommended loading setting in ImGui: Size = 13.0, DisplayOffset.Y = +1
proggy_clean.fon --> [bmfont] ---> proggy_clean_13.fnt
proggy_clean_13.png
ProggyTiny.ttf
Copyright (c) 2004, 2005 Tristan Grimmer
MIT License
recommended loading setting in ImGui: Size = 10.0, DisplayOffset.Y = +1
If you need a free font that supports chinese/japanese characters, you can use the M+ fonts.
TTF and sources are availables at http://mplus-fonts.sourceforge.jp/mplus-outline-fonts.
This directory include some of the M+ fonts converted by bmfont.
Karla-Regular
Copyright (c) 2012, Jonathan Pinhorn
SIL OPEN FONT LICENSE Version 1.1
//-----------------------------------------------------------------------------
---------------------------------
OTHER FONTS
---------------------------------
Configure bmfont:
For Japanese:
M+ fonts by Coji Morishita are free and include most useful Kanjis you would need.
mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html
For Japanese, Chinese, Korean:
You can use Arial Unicode or other Unicode fonts provided with Windows (not sure of their license).
Other suggestions?
- Export .fnt as Binary
- Output .png, 32-bits (or whatever is suitable for your loader/renderer)
- Tip: uncheck "Render from TrueType outline" and "Font Smoothing" for best result with non-anti-aliased type fonts.
But you can experiment with other settings if you want anti-aliased fonts.
- Tip: use pngout.exe (http://advsys.net/ken/utils.htm) to further reduce the file size of .png files
All files in this folder have been optimised with pngout.exe
---------------------------------
LOADING INSTRUCTIONS
---------------------------------
-----------------------------------------------------------------------------
Load .TTF file with:
(A) Use font data embedded in ImGui
ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels);
Add a third parameter to bake specific font ranges:
// Access embedded font data
const void* fnt_data; // pointer to FNT data
unsigned fnt_size; // size of FNT data
const void* png_data; // pointer to PNG data
unsigned int png_size; // size of PNG data
ImGui::GetDefaultFontData(&fnt_data, &fnt_size, &png_data, &png_size);
io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, io.Fonts->GetGlyphRangesDefault()); // Basic Latin, Extended Latin
io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, io.Fonts->GetGlyphRangesJapanese()); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs
io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, io.Fonts->GetGlyphRangesChinese()); // Include full set of about 21000 CJK Unified Ideographs
1. Load the .FNT data from 'fnt_data' (NB: this is done for you by default if you don't do anything)
Offset font by altering the io.Font->DisplayOffset value:
ImGuiIO& io = ImGui::GetIO();
io.Font = new ImBitmapFont();
io.Font->LoadFromMemory(fnt_data, fnt_size);
2. Load the .PNG data from 'png_data' into a texture
ImFont* font = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels);
font->DisplayOffset.y += 1; // Render 1 pixel down
//-----------------------------------------------------------------------------
(B) Use fonts from external files
You need to set io.FontTexUvForWhite to UV coordinates pointing to a white pixel in the texture.
You can either locate a white pixel manually or use code at runtime to find or write one.
The OpenGL example include sample code to find a white pixel given an uncompressed 32-bits texture:
// Automatically find white pixel from the texture we just loaded
// (io.FontTexUvForWhite needs to contains UV coordinates pointing to a white pixel in order to render solid objects)
for (int tex_data_off = 0; tex_data_off < tex_x*tex_y; tex_data_off++)
if (((unsigned int*)tex_data)[tex_data_off] == 0xffffffff)
{
io.FontTexUvForWhite = ImVec2((float)(tex_data_off % tex_x)/(tex_x), (float)(tex_data_off / tex_x)/(tex_y));
break;
}
1. Load the .FNT data, e.g.
ImGuiIO& io = ImGui::GetIO();
// proggy_clean_13 [default]
io.Font = new ImBitmapFont();
io.Font->LoadFromFile("proggy_clean_13.fnt");
IM_ASSERT(io.Font->IsLoaded());
io.FontTexUvForWhite = ImVec2(0.0f/256.0f,0.0f/128);
io.FontYOffset = +1;
// proggy_small_12
io.Font = new ImBitmapFont();
io.Font->LoadFromFile("proggy_small_12.fnt");
IM_ASSERT(io.Font->IsLoaded());
io.FontTexUvForWhite = ImVec2(84.0f/256.0f,20.0f/64);
io.FontYOffset = +2;
// proggy_small_14
io.Font = new ImBitmapFont();
io.Font->LoadFromFile("proggy_small_14.fnt");
IM_ASSERT(io.Font->IsLoaded());
io.FontTexUvForWhite = ImVec2(84.0f/256.0f,20.0f/64);
io.FontYOffset = +3;
// courier_new_16
io.Font->LoadFromFile("courier_new_16.fnt");
io.FontTexUvForWhite = ImVec2(1.0f/256.0f,4.0f/128);
// courier_new_18
io.Font->LoadFromFile("courier_new_18.fnt");
io.FontTexUvForWhite = ImVec2(4.0f/256.0f,5.0f/256);
2. Load the matching .PNG data into a texture
//-----------------------------------------------------------------------------

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 284 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 949 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 949 B

View File

@ -20,6 +20,9 @@
//---- Include imgui_user.inl at the end of imgui.cpp so you can include code that extends ImGui using its private data/functions.
//#define IMGUI_INCLUDE_IMGUI_USER_INL
//---- Include imgui_user.h at the end of imgui.h
//#define IMGUI_INCLUDE_IMGUI_USER_H
//---- Define implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4.
/*
#define IM_VEC2_CLASS_EXTRA \
@ -39,6 +42,6 @@ namespace ImGui
{
void Value(const char* prefix, const MyVec2& v, const char* float_format = NULL);
void Value(const char* prefix, const MyVec4& v, const char* float_format = NULL);
};
}
*/

5386
imgui.cpp

File diff suppressed because it is too large Load Diff

821
imgui.h

File diff suppressed because it is too large Load Diff

547
stb_rect_pack.h Normal file
View File

@ -0,0 +1,547 @@
// stb_rect_pack.h - v0.05 - public domain - rectangle packing
// Sean Barrett 2014
//
// Useful for e.g. packing rectangular textures into an atlas.
// Does not do rotation.
//
// Not necessarily the awesomest packing method, but better than
// the totally naive one in stb_truetype (which is primarily what
// this is meant to replace).
//
// Has only had a few tests run, may have issues.
//
// More docs to come.
//
// No memory allocations; uses qsort() and assert() from stdlib.
//
// This library currently uses the Skyline Bottom-Left algorithm.
//
// Please note: better rectangle packers are welcome! Please
// implement them to the same API, but with a different init
// function.
//
// Version history:
//
// 0.05: added STBRP_ASSERT to allow replacing assert
// 0.04: fixed minor bug in STBRP_LARGE_RECTS support
// 0.01: initial release
//////////////////////////////////////////////////////////////////////////////
//
// INCLUDE SECTION
//
#ifndef STB_INCLUDE_STB_RECT_PACK_H
#define STB_INCLUDE_STB_RECT_PACK_H
#define STB_RECT_PACK_VERSION 1
#ifdef STBRP_STATIC
#define STBRP_DEF static
#else
#define STBRP_DEF extern
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct stbrp_context stbrp_context;
typedef struct stbrp_node stbrp_node;
typedef struct stbrp_rect stbrp_rect;
#ifdef STBRP_LARGE_RECTS
typedef int stbrp_coord;
#else
typedef unsigned short stbrp_coord;
#endif
STBRP_DEF void stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
// Assign packed locations to rectangles. The rectangles are of type
// 'stbrp_rect' defined below, stored in the array 'rects', and there
// are 'num_rects' many of them.
//
// Rectangles which are successfully packed have the 'was_packed' flag
// set to a non-zero value and 'x' and 'y' store the minimum location
// on each axis (i.e. bottom-left in cartesian coordinates, top-left
// if you imagine y increasing downwards). Rectangles which do not fit
// have the 'was_packed' flag set to 0.
//
// You should not try to access the 'rects' array from another thread
// while this function is running, as the function temporarily reorders
// the array while it executes.
//
// To pack into another rectangle, you need to call stbrp_init_target
// again. To continue packing into the same rectangle, you can call
// this function again. Calling this multiple times with multiple rect
// arrays will probably produce worse packing results than calling it
// a single time with the full rectangle array, but the option is
// available.
struct stbrp_rect
{
// reserved for your use:
int id;
// input:
stbrp_coord w, h;
// output:
stbrp_coord x, y;
int was_packed; // non-zero if valid packing
}; // 16 bytes, nominally
STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
// Initialize a rectangle packer to:
// pack a rectangle that is 'width' by 'height' in dimensions
// using temporary storage provided by the array 'nodes', which is 'num_nodes' long
//
// You must call this function every time you start packing into a new target.
//
// There is no "shutdown" function. The 'nodes' memory must stay valid for
// the following stbrp_pack_rects() call (or calls), but can be freed after
// the call (or calls) finish.
//
// Note: to guarantee best results, either:
// 1. make sure 'num_nodes' >= 'width'
// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
//
// If you don't do either of the above things, widths will be quantized to multiples
// of small integers to guarantee the algorithm doesn't run out of temporary storage.
//
// If you do #2, then the non-quantized algorithm will be used, but the algorithm
// may run out of temporary storage and be unable to pack some rectangles.
STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
// Optionally call this function after init but before doing any packing to
// change the handling of the out-of-temp-memory scenario, described above.
// If you call init again, this will be reset to the default (false).
STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
// Optionally select which packing heuristic the library should use. Different
// heuristics will produce better/worse results for different data sets.
// If you call init again, this will be reset to the default.
enum
{
STBRP_HEURISTIC_Skyline_default=0,
STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
STBRP_HEURISTIC_Skyline_BF_sortHeight
};
//////////////////////////////////////////////////////////////////////////////
//
// the details of the following structures don't matter to you, but they must
// be visible so you can handle the memory allocations for them
struct stbrp_node
{
stbrp_coord x,y;
stbrp_node *next;
};
struct stbrp_context
{
int width;
int height;
int align;
int init_mode;
int heuristic;
int num_nodes;
stbrp_node *active_head;
stbrp_node *free_head;
stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
};
#ifdef __cplusplus
}
#endif
#endif
//////////////////////////////////////////////////////////////////////////////
//
// IMPLEMENTATION SECTION
//
#ifdef STB_RECT_PACK_IMPLEMENTATION
#include <stdlib.h>
#ifndef STBRP_ASSERT
#include <assert.h>
#define STBRP_ASSERT assert
#endif
enum
{
STBRP__INIT_skyline = 1
};
STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
{
switch (context->init_mode) {
case STBRP__INIT_skyline:
STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
context->heuristic = heuristic;
break;
default:
STBRP_ASSERT(0);
}
}
STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
{
if (allow_out_of_mem)
// if it's ok to run out of memory, then don't bother aligning them;
// this gives better packing, but may fail due to OOM (even though
// the rectangles easily fit). @TODO a smarter approach would be to only
// quantize once we've hit OOM, then we could get rid of this parameter.
context->align = 1;
else {
// if it's not ok to run out of memory, then quantize the widths
// so that num_nodes is always enough nodes.
//
// I.e. num_nodes * align >= width
// align >= width / num_nodes
// align = ceil(width/num_nodes)
context->align = (context->width + context->num_nodes-1) / context->num_nodes;
}
}
STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
{
int i;
#ifndef STBRP_LARGE_RECTS
STBRP_ASSERT(width <= 0xffff && height <= 0xffff);
#endif
for (i=0; i < num_nodes-1; ++i)
nodes[i].next = &nodes[i+1];
nodes[i].next = NULL;
context->init_mode = STBRP__INIT_skyline;
context->heuristic = STBRP_HEURISTIC_Skyline_default;
context->free_head = &nodes[0];
context->active_head = &context->extra[0];
context->width = width;
context->height = height;
context->num_nodes = num_nodes;
stbrp_setup_allow_out_of_mem(context, 0);
// node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
context->extra[0].x = 0;
context->extra[0].y = 0;
context->extra[0].next = &context->extra[1];
context->extra[1].x = (stbrp_coord) width;
#ifdef STBRP_LARGE_RECTS
context->extra[1].y = (1<<30);
#else
context->extra[1].y = 65535;
#endif
context->extra[1].next = NULL;
}
// find minimum y position if it starts at x1
static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
{
(void)c;
stbrp_node *node = first;
int x1 = x0 + width;
int min_y, visited_width, waste_area;
STBRP_ASSERT(first->x <= x0);
#if 0
// skip in case we're past the node
while (node->next->x <= x0)
++node;
#else
STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
#endif
STBRP_ASSERT(node->x <= x0);
min_y = 0;
waste_area = 0;
visited_width = 0;
while (node->x < x1) {
if (node->y > min_y) {
// raise min_y higher.
// we've accounted for all waste up to min_y,
// but we'll now add more waste for everything we've visted
waste_area += visited_width * (node->y - min_y);
min_y = node->y;
// the first time through, visited_width might be reduced
if (node->x < x0)
visited_width += node->next->x - x0;
else
visited_width += node->next->x - node->x;
} else {
// add waste area
int under_width = node->next->x - node->x;
if (under_width + visited_width > width)
under_width = width - visited_width;
waste_area += under_width * (min_y - node->y);
visited_width += under_width;
}
node = node->next;
}
*pwaste = waste_area;
return min_y;
}
typedef struct
{
int x,y;
stbrp_node **prev_link;
} stbrp__findresult;
static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
{
int best_waste = (1<<30), best_x, best_y = (1 << 30);
stbrp__findresult fr;
stbrp_node **prev, *node, *tail, **best = NULL;
// align to multiple of c->align
width = (width + c->align - 1);
width -= width % c->align;
STBRP_ASSERT(width % c->align == 0);
node = c->active_head;
prev = &c->active_head;
while (node->x + width <= c->width) {
int y,waste;
y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
// bottom left
if (y < best_y) {
best_y = y;
best = prev;
}
} else {
// best-fit
if (y + height <= c->height) {
// can only use it if it first vertically
if (y < best_y || (y == best_y && waste < best_waste)) {
best_y = y;
best_waste = waste;
best = prev;
}
}
}
prev = &node->next;
node = node->next;
}
best_x = (best == NULL) ? 0 : (*best)->x;
// if doing best-fit (BF), we also have to try aligning right edge to each node position
//
// e.g, if fitting
//
// ____________________
// |____________________|
//
// into
//
// | |
// | ____________|
// |____________|
//
// then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
//
// This makes BF take about 2x the time
if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
tail = c->active_head;
node = c->active_head;
prev = &c->active_head;
// find first node that's admissible
while (tail->x < width)
tail = tail->next;
while (tail) {
int xpos = tail->x - width;
int y,waste;
STBRP_ASSERT(xpos >= 0);
// find the left position that matches this
while (node->next->x <= xpos) {
prev = &node->next;
node = node->next;
}
STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
if (y + height < c->height) {
if (y <= best_y) {
if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
best_x = xpos;
STBRP_ASSERT(y <= best_y);
best_y = y;
best_waste = waste;
best = prev;
}
}
}
tail = tail->next;
}
}
fr.prev_link = best;
fr.x = best_x;
fr.y = best_y;
return fr;
}
static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
{
// find best position according to heuristic
stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
stbrp_node *node, *cur;
// bail if:
// 1. it failed
// 2. the best node doesn't fit (we don't always check this)
// 3. we're out of memory
if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
res.prev_link = NULL;
return res;
}
// on success, create new node
node = context->free_head;
node->x = (stbrp_coord) res.x;
node->y = (stbrp_coord) (res.y + height);
context->free_head = node->next;
// insert the new node into the right starting point, and
// let 'cur' point to the remaining nodes needing to be
// stiched back in
cur = *res.prev_link;
if (cur->x < res.x) {
// preserve the existing one, so start testing with the next one
stbrp_node *next = cur->next;
cur->next = node;
cur = next;
} else {
*res.prev_link = node;
}
// from here, traverse cur and free the nodes, until we get to one
// that shouldn't be freed
while (cur->next && cur->next->x <= res.x + width) {
stbrp_node *next = cur->next;
// move the current node to the free list
cur->next = context->free_head;
context->free_head = cur;
cur = next;
}
// stitch the list back in
node->next = cur;
if (cur->x < res.x + width)
cur->x = (stbrp_coord) (res.x + width);
#ifdef _DEBUG
cur = context->active_head;
while (cur->x < context->width) {
STBRP_ASSERT(cur->x < cur->next->x);
cur = cur->next;
}
STBRP_ASSERT(cur->next == NULL);
{
stbrp_node *L1 = NULL, *L2 = NULL;
int count=0;
cur = context->active_head;
while (cur) {
L1 = cur;
cur = cur->next;
++count;
}
cur = context->free_head;
while (cur) {
L2 = cur;
cur = cur->next;
++count;
}
STBRP_ASSERT(count == context->num_nodes+2);
}
#endif
return res;
}
static int rect_height_compare(const void *a, const void *b)
{
stbrp_rect *p = (stbrp_rect *) a;
stbrp_rect *q = (stbrp_rect *) b;
if (p->h > q->h)
return -1;
if (p->h < q->h)
return 1;
return (p->w > q->w) ? -1 : (p->w < q->w);
}
static int rect_width_compare(const void *a, const void *b)
{
stbrp_rect *p = (stbrp_rect *) a;
stbrp_rect *q = (stbrp_rect *) b;
if (p->w > q->w)
return -1;
if (p->w < q->w)
return 1;
return (p->h > q->h) ? -1 : (p->h < q->h);
}
static int rect_original_order(const void *a, const void *b)
{
stbrp_rect *p = (stbrp_rect *) a;
stbrp_rect *q = (stbrp_rect *) b;
return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
}
#ifdef STBRP_LARGE_RECTS
#define STBRP__MAXVAL 0xffffffff
#else
#define STBRP__MAXVAL 0xffff
#endif
STBRP_DEF void stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
{
int i;
// we use the 'was_packed' field internally to allow sorting/unsorting
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = i;
#ifndef STBRP_LARGE_RECTS
STBRP_ASSERT(rects[i].w <= 0xffff && rects[i].h <= 0xffff);
#endif
}
// sort according to heuristic
qsort(rects, num_rects, sizeof(rects[0]), rect_height_compare);
for (i=0; i < num_rects; ++i) {
stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
if (fr.prev_link) {
rects[i].x = (stbrp_coord) fr.x;
rects[i].y = (stbrp_coord) fr.y;
} else {
rects[i].x = rects[i].y = STBRP__MAXVAL;
}
}
// unsort
qsort(rects, num_rects, sizeof(rects[0]), rect_original_order);
// set was_packed flags
for (i=0; i < num_rects; ++i)
rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
}
#endif

View File

@ -1008,13 +1008,13 @@ static void stb_textedit_discard_undo(StbUndoState *state)
int n = state->undo_rec[0].insert_length, i;
// delete n characters from all other records
state->undo_char_point = state->undo_char_point - (short) n; // vsnet05
memmove(state->undo_char, state->undo_char + n, (size_t) (state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE)));
memmove(state->undo_char, state->undo_char + n, (size_t) ((size_t)state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE)));
for (i=0; i < state->undo_point; ++i)
if (state->undo_rec[i].char_storage >= 0)
state->undo_rec[i].char_storage = state->undo_rec[i].char_storage - (short) n; // vsnet05 // @OPTIMIZE: get rid of char_storage and infer it
}
--state->undo_point;
memmove(state->undo_rec, state->undo_rec+1, (size_t) (state->undo_point*sizeof(state->undo_rec[0])));
memmove(state->undo_rec, state->undo_rec+1, (size_t) ((size_t)state->undo_point*sizeof(state->undo_rec[0])));
}
}
@ -1032,13 +1032,13 @@ static void stb_textedit_discard_redo(StbUndoState *state)
int n = state->undo_rec[k].insert_length, i;
// delete n characters from all other records
state->redo_char_point = state->redo_char_point + (short) n; // vsnet05
memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE)));
memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE)));
for (i=state->redo_point; i < k; ++i)
if (state->undo_rec[i].char_storage >= 0)
state->undo_rec[i].char_storage = state->undo_rec[i].char_storage + (short) n; // vsnet05
}
++state->redo_point;
memmove(state->undo_rec + state->redo_point-1, state->undo_rec + state->redo_point, (size_t) ((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0])));
memmove(state->undo_rec + state->redo_point-1, state->undo_rec + state->redo_point, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0])));
}
}

2658
stb_truetype.h Normal file

File diff suppressed because it is too large Load Diff

BIN
web/examples_01.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

BIN
web/examples_02.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

BIN
web/performance_01.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.3 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.4 KiB

After

Width:  |  Height:  |  Size: 16 KiB