update imgui, home-made code viewer (not editor!)
Some checks are pending
build-story-editor / build_linux (push) Waiting to run
build-story-editor / build_win32 (push) Waiting to run
Deploy / deploy (push) Waiting to run

This commit is contained in:
anthony@rabine.fr 2024-12-29 00:29:21 +01:00
parent 6e3143c880
commit 6305b06d53
93 changed files with 1089 additions and 76138 deletions

View file

@ -25,7 +25,7 @@ find_package(OpenGL REQUIRED)
# set(OPENSSL_ROOT_DIR /libs/openssl)
# find_package(OpenSSL REQUIRED)
set(IMGUI_VERSION 1.90)
set(IMGUI_VERSION 1.91.6)
include(FetchContent)
@ -93,6 +93,20 @@ add_compile_definitions(CUSTOM_IMGUIFILEDIALOG_CONFIG="${CMAKE_SOURCE_DIR}/src/C
add_compile_definitions(IMGUI_INCLUDE="imgui.h")
add_subdirectory(libs/ImGuiFileDialog)
# =========================================================================================================================
# ImGui Text editor
# =========================================================================================================================
# FetchContent_Declare(
# te
# GIT_REPOSITORY https://github.com/ChemistAion/ImTextEdit
# GIT_TAG 81ec756b5627dd351fe0dac26a7403982349df68
# GIT_SHALLOW TRUE
# GIT_PROGRESS TRUE
# )
# FetchContent_MakeAvailable(te)
# =========================================================================================================================
# SDL2
# =========================================================================================================================
@ -115,7 +129,7 @@ add_subdirectory(libs/ImGuiFileDialog)
FetchContent_Declare(
sdl3
GIT_REPOSITORY https://github.com/libsdl-org/SDL.git
GIT_TAG prerelease-3.1.0
GIT_TAG 78cc5c173404488d80751af226d1eaf67033bcc4 # === preview-3.1.6
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
)
@ -132,7 +146,7 @@ include_directories(${sdl3_SOURCE_DIR}/include)
FetchContent_Declare(
sdl3_mixer
GIT_REPOSITORY https://github.com/libsdl-org/SDL_mixer.git
GIT_TAG cc78718f6e87354fee8ffe4dc516a20f608c2d65
GIT_TAG d4eba31e4ac23a81fffad02e91b17dcb2449a2cb
# GIT_SHALLOW TRUE
# GIT_PROGRESS TRUE
# GIT_SUBMODULES ""
@ -151,7 +165,7 @@ include_directories(${sdl3_mixer_SOURCE_DIR}/include)
FetchContent_Declare(
sdl_image
GIT_REPOSITORY https://github.com/libsdl-org/SDL_image.git
GIT_TAG ff62eb68aebe9801f06695c86a67292c6f166b16
GIT_TAG bcc97c044266080256ef6ed0d690859677212b2b
GIT_PROGRESS TRUE
)
@ -220,8 +234,7 @@ set(SRCS
src/importers/pack_archive.cpp
src/importers/ni_parser.c
libs/ImGuiColorTextEdit/TextEditor.cpp
libs/ImGuiColorTextEdit/TextEditor.h
libs/imgui-node-editor/imgui_node_editor.cpp
libs/imgui-node-editor/imgui_canvas.cpp
libs/imgui-node-editor/imgui_node_editor_api.cpp
@ -288,7 +301,9 @@ endif()
target_include_directories(${STORY_EDITOR_PROJECT} PUBLIC
${imgui_SOURCE_DIR}
${sdl2_SOURCE_DIR}/include
libs/ImGuiColorTextEdit/
# ${te_SOURCE_DIR}
${imgui_SOURCE_DIR}/backends
libs/ImGuiFileDialog
libs/imgui-node-editor

View file

@ -0,0 +1 @@
{"nodes":{"node:1":{"location":{"x":0,"y":0}},"node:11":{"location":{"x":0,"y":0}},"node:14":{"location":{"x":0,"y":0}},"node:21":{"location":{"x":326,"y":24}},"node:5":{"location":{"x":0,"y":0}},"node:8":{"location":{"x":0,"y":0}}},"selection":null,"view":{"scroll":{"x":30.620513916015625,"y":0},"visible_rect":{"max":{"x":501.620513916015625,"y":301},"min":{"x":30.620513916015625,"y":0}},"zoom":1}}

198
story-editor/imgui.ini Normal file
View file

@ -0,0 +1,198 @@
[Window][DockSpaceViewport_11111111]
Pos=60,26
Size=1220,694
Collapsed=0
[Window][Debug##Default]
Pos=260,575
Size=32,42
Collapsed=0
[Window][Library Manager]
Pos=466,26
Size=814,262
Collapsed=0
DockId=0x00000003,3
[Window][Console]
Pos=60,623
Size=1220,97
Collapsed=0
DockId=0x00000006,0
[Window][Emulator]
Pos=466,26
Size=814,262
Collapsed=0
DockId=0x00000003,2
[Window][Code editor]
Pos=466,290
Size=814,331
Collapsed=0
DockId=0x00000004,0
[Window][Resources]
Pos=466,26
Size=814,262
Collapsed=0
DockId=0x00000003,0
[Window][Properties]
Pos=466,26
Size=814,262
Collapsed=0
DockId=0x00000003,1
[Window][Node editor]
Pos=60,26
Size=404,595
Collapsed=0
DockId=0x00000002,0
[Window][QuitConfirm]
Pos=479,312
Size=321,96
Collapsed=0
[Window][ToolBar]
Pos=0,26
Size=60,694
Collapsed=0
[Window][ProjectPropertiesPopup]
Pos=381,236
Size=518,248
Collapsed=0
[Window][AboutPopup]
Pos=540,272
Size=408,249
Collapsed=0
[Window][Choose an output directory##ChooseOutputDirDialog]
Pos=307,121
Size=757,506
Collapsed=0
[Window][Import story##LoadBinarySoryDlgKey]
Pos=278,146
Size=838,498
Collapsed=0
[Window][Choose a binary story##LoadBinarySoryDlgKey]
Pos=82,80
Size=951,564
Collapsed=0
[Window][CPU]
Pos=466,26
Size=814,262
Collapsed=0
DockId=0x00000003,4
[Window][Choose File##ChooseFileDlgKey]
Pos=121,114
Size=1021,495
Collapsed=0
[Window][TOOLBAR]
Pos=73,64
Size=79,42
Collapsed=0
[Window][WindowOverViewport_11111111]
Pos=60,26
Size=1220,694
Collapsed=0
[Table][0x54B1A511,5]
RefScale=20
Column 0 Width=197 Sort=0v
Column 1 Width=72
Column 2 Width=104
Column 3 Width=54
Column 4 Width=75
[Table][0xF08E291D,3]
RefScale=20
Column 0 Width=267 Sort=0v
Column 1 Width=88
Column 2 Width=124
[Table][0x7DCCCE7C,4]
RefScale=20
Column 0 Sort=0v
[Table][0x93B9C489,4]
RefScale=20
Column 0 Sort=0v
[Table][0x93085AFC,4]
RefScale=20
Column 0 Sort=0v
[Table][0xB1418086,4]
RefScale=20
Column 0 Sort=0v
[Table][0x37890D83,4]
RefScale=20
Column 0 Sort=0v
[Table][0xA1962243,2]
RefScale=20
Column 0 Width=22 Sort=0v
Column 1 Width=98
[Table][0x266F6FA3,4]
RefScale=20
Column 0 Sort=0v
[Table][0x8DB57DAE,4]
RefScale=20
Column 0 Sort=0v
[Table][0x464EAF99,4]
RefScale=20
Column 0 Sort=0v
[Table][0xED94BD94,4]
RefScale=20
Column 0 Sort=0v
[Table][0x1CBE9632,4]
RefScale=20
Column 0 Width=51 Sort=0v
Column 1 Width=104
Column 2 Width=47
Column 3 Width=93
[Table][0x30BF8F98,3]
RefScale=20
Column 0 Width=267 Sort=0v
Column 1 Width=88
Column 2 Width=124
[Table][0x7728942D,5]
RefScale=20
Column 0 Width=313 Sort=0v
Column 1 Width=72
Column 2 Width=104
Column 3 Width=54
Column 4 Width=75
[Table][0x69D69F59,2]
RefScale=20
Column 0 Width=22 Sort=0v
Column 1 Width=96
[Docking][Data]
DockSpace ID=0x08BD597D Window=0x1BBC0F80 Pos=60,26 Size=1220,694 Split=Y
DockNode ID=0x00000005 Parent=0x08BD597D SizeRef=1220,595 Split=X
DockNode ID=0x00000002 Parent=0x00000005 SizeRef=574,694 CentralNode=1 Selected=0xBB79A587
DockNode ID=0x00000001 Parent=0x00000005 SizeRef=814,694 Split=Y Selected=0x63869CAF
DockNode ID=0x00000003 Parent=0x00000001 SizeRef=543,294 Selected=0x4B07C626
DockNode ID=0x00000004 Parent=0x00000001 SizeRef=543,372 Selected=0x7563A968
DockNode ID=0x00000006 Parent=0x08BD597D SizeRef=1220,97 Selected=0xEA83D666

View file

@ -1,36 +0,0 @@
# Prerequisites
*.d
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
*.smod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
TextEditor.cpp.bak
*.bak
Save/TextEditor.h
Save/TextEditor.cpp

View file

@ -1,11 +0,0 @@
# Contributing
Pull requests are welcome, feel free to contribute if you have implemented something which might be useful for the general audience of this little piece of software. Apparently, it became kind of a community project now. :)
Whem contributing, please follow the following guidelines. I will keep it updated as we bump into something which worth doing better.
- Try to follow the same coding and naming conventions you find in the source already. I know that everyone has its own preference/taste in coding, but please keep the source consistent in style.
- Please submit to the 'dev' branch first for testing, and it will be merged to 'main' if it seems to work fine. I would like try keep 'master' in a good working condition, as more and more people are using it.
- Please send your submissions in small, well defined requests, i. e. do not accumulate many unrelated changes in one large pull request. Keep your submissions as small as possible, it will make everyone's life easier.
- Avoid using ImGui internal since it would make the source fragile against internal changes in ImGui.
- Try to keep the perormance high within the render function. Try to avoid doing anything which leads to memory allocations (like using temporary std::string, std::vector variables), or complex algorithm. If you really have to, try to amortise it between frames.
Thank you. :)

View file

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2017 BalazsJako
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,33 +0,0 @@
# ImGuiColorTextEdit
Syntax highlighting text editor for ImGui
![Screenshot](https://github.com/BalazsJako/ImGuiColorTextEdit/wiki/ImGuiTextEdit.png "Screenshot")
Demo project: https://github.com/BalazsJako/ColorTextEditorDemo
This started as my attempt to write a relatively simple widget which provides text editing functionality with syntax highlighting. Now there are other contributors who provide valuable additions.
While it relies on Omar Cornut's https://github.com/ocornut/imgui, it does not follow the "pure" one widget - one function approach. Since the editor has to maintain a relatively complex and large internal state, it did not seem to be practical to try and enforce fully immediate mode. It stores its internal state in an object instance which is reused across frames.
The code is (still) work in progress, please report if you find any issues.
# Main features
- approximates typical code editor look and feel (essential mouse/keyboard commands work - I mean, the commands _I_ normally use :))
- undo/redo
- UTF-8 support
- works with both fixed and variable-width fonts
- extensible syntax highlighting for multiple languages
- identifier declarations: a small piece of description can be associated with an identifier. The editor displays it in a tooltip when the mouse cursor is hovered over the identifier
- error markers: the user can specify a list of error messages together the line of occurence, the editor will highligh the lines with red backround and display error message in a tooltip when the mouse cursor is hovered over the line
- large files: there is no explicit limit set on file size or number of lines (below 2GB, performance is not affected when large files are loaded (except syntax coloring, see below)
- color palette support: you can switch between different color palettes, or even define your own
- whitespace indicators (TAB, space)
# Known issues
- syntax highligthing of most languages - except C/C++ and Lua - is based on std::regex, which is diasppointingly slow. Because of that, the highlighting process is amortized between multiple frames. C/C++ and Lua have a hand-written tokenizer which is much faster.
Please post your screenshots if you find this little piece of software useful. :)
# Contribute
If you want to contribute, please refer to CONTRIBUTE file.

File diff suppressed because it is too large Load diff

View file

@ -1,413 +0,0 @@
#pragma once
#include <string>
#include <vector>
#include <array>
#include <memory>
#include <unordered_set>
#include <unordered_map>
#include <map>
#include <regex>
#include "imgui.h"
class TextEditor
{
public:
enum class PaletteIndex
{
Default,
Keyword,
Number,
String,
CharLiteral,
Punctuation,
Preprocessor,
Identifier,
KnownIdentifier,
PreprocIdentifier,
Comment,
MultiLineComment,
Background,
Cursor,
Selection,
ErrorMarker,
ControlCharacter,
Breakpoint,
LineNumber,
CurrentLineFill,
CurrentLineFillInactive,
CurrentLineEdge,
WhiteSpace,
WhiteSpaceTab,
Max
};
enum class SelectionMode
{
Normal,
Word,
Line
};
struct Breakpoint
{
int mLine;
bool mEnabled;
std::string mCondition;
Breakpoint()
: mLine(-1)
, mEnabled(false)
{}
};
// Represents a character coordinate from the user's point of view,
// i. e. consider an uniform grid (assuming fixed-width font) on the
// screen as it is rendered, and each cell has its own coordinate, starting from 0.
// Tabs are counted as [1..mTabSize] count empty spaces, depending on
// how many space is necessary to reach the next tab stop.
// For example, coordinate (1, 5) represents the character 'B' in a line "\tABC", when mTabSize = 4,
// because it is rendered as " ABC" on the screen.
struct Coordinates
{
int mLine, mColumn;
Coordinates() : mLine(0), mColumn(0) {}
Coordinates(int aLine, int aColumn) : mLine(aLine), mColumn(aColumn)
{
assert(aLine >= 0);
assert(aColumn >= 0);
}
static Coordinates Invalid() { static Coordinates invalid(-1, -1); return invalid; }
bool operator ==(const Coordinates& o) const
{
return
mLine == o.mLine &&
mColumn == o.mColumn;
}
bool operator !=(const Coordinates& o) const
{
return
mLine != o.mLine ||
mColumn != o.mColumn;
}
bool operator <(const Coordinates& o) const
{
if (mLine != o.mLine)
return mLine < o.mLine;
return mColumn < o.mColumn;
}
bool operator >(const Coordinates& o) const
{
if (mLine != o.mLine)
return mLine > o.mLine;
return mColumn > o.mColumn;
}
bool operator <=(const Coordinates& o) const
{
if (mLine != o.mLine)
return mLine < o.mLine;
return mColumn <= o.mColumn;
}
bool operator >=(const Coordinates& o) const
{
if (mLine != o.mLine)
return mLine > o.mLine;
return mColumn >= o.mColumn;
}
};
struct Identifier
{
Coordinates mLocation;
std::string mDeclaration;
};
typedef std::string String;
typedef std::unordered_map<std::string, Identifier> Identifiers;
typedef std::unordered_set<std::string> Keywords;
typedef std::map<int, std::string> ErrorMarkers;
typedef std::unordered_set<int> Breakpoints;
typedef std::array<ImU32, (unsigned)PaletteIndex::Max> Palette;
typedef uint8_t Char;
struct Glyph
{
Char mChar;
PaletteIndex mColorIndex = PaletteIndex::Default;
bool mComment : 1;
bool mMultiLineComment : 1;
bool mPreprocessor : 1;
Glyph(Char aChar, PaletteIndex aColorIndex) : mChar(aChar), mColorIndex(aColorIndex),
mComment(false), mMultiLineComment(false), mPreprocessor(false) {}
};
typedef std::vector<Glyph> Line;
typedef std::vector<Line> Lines;
struct LanguageDefinition
{
typedef std::pair<std::string, PaletteIndex> TokenRegexString;
typedef std::vector<TokenRegexString> TokenRegexStrings;
typedef bool(*TokenizeCallback)(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end, PaletteIndex & paletteIndex);
std::string mName;
Keywords mKeywords;
Identifiers mIdentifiers;
Identifiers mPreprocIdentifiers;
std::string mCommentStart, mCommentEnd, mSingleLineComment;
char mPreprocChar;
bool mAutoIndentation;
TokenizeCallback mTokenize;
TokenRegexStrings mTokenRegexStrings;
bool mCaseSensitive;
LanguageDefinition()
: mPreprocChar('#'), mAutoIndentation(true), mTokenize(nullptr), mCaseSensitive(true)
{
}
static const LanguageDefinition& CPlusPlus();
static const LanguageDefinition& HLSL();
static const LanguageDefinition& GLSL();
static const LanguageDefinition& C();
static const LanguageDefinition& SQL();
static const LanguageDefinition& AngelScript();
static const LanguageDefinition& Lua();
};
struct EditorState
{
Coordinates mSelectionStart;
Coordinates mSelectionEnd;
Coordinates mCursorPosition;
};
class UndoRecord
{
public:
UndoRecord() {}
~UndoRecord() {}
UndoRecord(
const std::string& aAdded,
const TextEditor::Coordinates aAddedStart,
const TextEditor::Coordinates aAddedEnd,
const std::string& aRemoved,
const TextEditor::Coordinates aRemovedStart,
const TextEditor::Coordinates aRemovedEnd,
TextEditor::EditorState& aBefore,
TextEditor::EditorState& aAfter);
UndoRecord(const UndoRecord& undoRecord);
void Undo(TextEditor* aEditor);
void Redo(TextEditor* aEditor);
std::string mAdded;
Coordinates mAddedStart;
Coordinates mAddedEnd;
std::string mRemoved;
Coordinates mRemovedStart;
Coordinates mRemovedEnd;
EditorState mBefore;
EditorState mAfter;
};
class ExternalUndoBufferInterface
{
public:
virtual void AddUndo(UndoRecord&) = 0;
};
typedef std::vector<UndoRecord> UndoBuffer;
TextEditor();
~TextEditor();
void SetLanguageDefinition(const LanguageDefinition& aLanguageDef);
const LanguageDefinition& GetLanguageDefinition() const { return mLanguageDefinition; }
const Palette& GetPalette() const { return mPaletteBase; }
void SetPalette(const Palette& aValue);
void SetErrorMarkers(const ErrorMarkers& aMarkers) { mErrorMarkers = aMarkers; }
void SetBreakpoints(const Breakpoints& aMarkers) { mBreakpoints = aMarkers; }
void SetExecutionMarker(int line) {
mExecutionMarker = line;
}
void Render(const char* aTitle, const ImVec2& aSize = ImVec2(), bool aBorder = false);
void SetText(const std::string& aText);
std::string GetText() const;
void SetTextLines(const std::vector<std::string>& aLines);
std::vector<std::string> GetTextLines() const;
std::string GetSelectedText() const;
std::string GetCurrentLineText()const;
int GetTotalLines() const { return (int)mLines.size(); }
bool IsOverwrite() const { return mOverwrite; }
void SetReadOnly(bool aValue);
bool IsReadOnly() const { return mReadOnly; }
bool IsTextChanged() const { return mTextChanged; }
bool IsCursorPositionChanged() const { return mCursorPositionChanged; }
bool IsColorizerEnabled() const { return mColorizerEnabled; }
void SetColorizerEnable(bool aValue);
Coordinates GetCursorPosition() const { return GetActualCursorCoordinates(); }
void SetCursorPosition(const Coordinates& aPosition);
inline void SetHandleMouseInputs (bool aValue){ mHandleMouseInputs = aValue;}
inline bool IsHandleMouseInputsEnabled() const { return mHandleKeyboardInputs; }
inline void SetHandleKeyboardInputs (bool aValue){ mHandleKeyboardInputs = aValue;}
inline bool IsHandleKeyboardInputsEnabled() const { return mHandleKeyboardInputs; }
inline void SetImGuiChildIgnored (bool aValue){ mIgnoreImGuiChild = aValue;}
inline bool IsImGuiChildIgnored() const { return mIgnoreImGuiChild; }
inline void SetShowWhitespaces(bool aValue) { mShowWhitespaces = aValue; }
inline bool IsShowingWhitespaces() const { return mShowWhitespaces; }
inline void SetShowShortTabGlyphs(bool aValue) { mShowShortTabGlyphs = aValue; }
inline bool IsShowingShortTabGlyphs() const { return mShowShortTabGlyphs; }
void SetTabSize(int aValue);
inline int GetTabSize() const { return mTabSize; }
void InsertText(const std::string& aValue, bool aSelect = false);
void InsertText(const char* aValue, bool aSelect = false);
void MoveUp(int aAmount = 1, bool aSelect = false);
void MoveDown(int aAmount = 1, bool aSelect = false);
void MoveLeft(int aAmount = 1, bool aSelect = false, bool aWordMode = false);
void MoveRight(int aAmount = 1, bool aSelect = false, bool aWordMode = false);
void MoveTop(bool aSelect = false);
void MoveBottom(bool aSelect = false);
void MoveHome(bool aSelect = false);
void MoveEnd(bool aSelect = false);
void SetSelectionStart(const Coordinates& aPosition);
void SetSelectionEnd(const Coordinates& aPosition);
const Coordinates GetSelectionStart()const;
const Coordinates GetSelectionEnd()const;
void SetSelection(const Coordinates& aStart, const Coordinates& aEnd, SelectionMode aMode = SelectionMode::Normal);
void SelectWordUnderCursor();
void SelectAll();
bool HasSelection() const;
void Copy();
void Cut();
void Paste();
void Delete();
bool CanUndo() const;
bool CanRedo() const;
void Undo(int aSteps = 1);
void Redo(int aSteps = 1);
void SetExternalUndoBuffer(ExternalUndoBufferInterface*);
static const Palette& GetDarkPalette();
static const Palette& GetLightPalette();
static const Palette& GetRetroBluePalette();
private:
typedef std::vector<std::pair<std::regex, PaletteIndex>> RegexList;
void ProcessInputs();
void Colorize(int aFromLine = 0, int aCount = -1);
void ColorizeRange(int aFromLine = 0, int aToLine = 0);
void ColorizeInternal();
float TextDistanceToLineStart(const Coordinates& aFrom) const;
void EnsureCursorVisible();
int GetPageSize() const;
std::string GetText(const Coordinates& aStart, const Coordinates& aEnd) const;
Coordinates GetActualCursorCoordinates() const;
Coordinates SanitizeCoordinates(const Coordinates& aValue) const;
void Advance(Coordinates& aCoordinates) const;
void DeleteRange(const Coordinates& aStart, const Coordinates& aEnd);
int InsertTextAt(Coordinates& aWhere, const char* aValue);
void AddUndo(UndoRecord& aValue);
Coordinates ScreenPosToCoordinates(const ImVec2& aPosition, bool aInsertionMode = false) const;
Coordinates FindWordStart(const Coordinates& aFrom) const;
Coordinates FindWordEnd(const Coordinates& aFrom) const;
Coordinates FindNextWord(const Coordinates& aFrom) const;
int GetCharacterIndex(const Coordinates& aCoordinates) const;
int GetCharacterColumn(int aLine, int aIndex) const;
int GetLineCharacterCount(int aLine) const;
int GetLineMaxColumn(int aLine) const;
bool IsOnWordBoundary(const Coordinates& aAt) const;
void RemoveLine(int aStart, int aEnd);
void RemoveLine(int aIndex);
Line& InsertLine(int aIndex);
void EnterCharacter(ImWchar aChar, bool aShift);
void Backspace();
void DeleteSelection();
std::string GetWordUnderCursor() const;
std::string GetWordAt(const Coordinates& aCoords) const;
ImU32 GetGlyphColor(const Glyph& aGlyph) const;
void HandleKeyboardInputs();
void HandleMouseInputs();
void UpdatePalette();
void Render();
float mLineSpacing;
Lines mLines;
EditorState mState;
UndoBuffer mUndoBuffer;
int mUndoIndex;
ExternalUndoBufferInterface* mExternalUndoBuffer;
int mTabSize;
bool mOverwrite;
bool mReadOnly;
bool mWithinRender;
bool mScrollToCursor;
bool mScrollToTop;
bool mTextChanged;
bool mColorizerEnabled;
float mTextStart; // position (in pixels) where a code line starts relative to the left of the TextEditor.
int mLeftMargin;
bool mCursorPositionChanged;
int mColorRangeMin, mColorRangeMax;
SelectionMode mSelectionMode;
bool mHandleKeyboardInputs{true};
bool mHandleMouseInputs{true};
bool mIgnoreImGuiChild{false};
bool mShowWhitespaces{true};
bool mShowShortTabGlyphs;
Palette mPaletteBase;
Palette mPalette;
LanguageDefinition mLanguageDefinition;
RegexList mRegexList;
bool mCheckComments;
Breakpoints mBreakpoints;
ErrorMarkers mErrorMarkers;
ImVec2 mCharAdvance;
Coordinates mInteractiveStart, mInteractiveEnd;
std::string mLineBuffer;
uint64_t mStartTime;
float mLastClick;
int mExecutionMarker{-1};
};

View file

@ -20,42 +20,37 @@ env:
jobs:
Windows:
runs-on: windows-2019
env:
VS_PATH: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\
MSBUILD_PATH: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Configure CMake
run: cmake -S examples -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
- name: Build
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}}
macOS:
runs-on: macos-latest
steps:
- name: Install Dependencies
run: |
brew install glfw3
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Configure CMake
run: cmake -S examples -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
- name: Build
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}}
Linux:
runs-on: ubuntu-latest
steps:
- name: Install Dependencies
- uses: actions/checkout@v4
- name: Install dependencies
run: |
sudo apt-get update
sudo apt-get install -y libglfw3-dev
- uses: actions/checkout@v2
sudo apt update
sudo apt install libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libxext-dev libwayland-dev libxkbcommon-dev mesa-common-dev libgl1-mesa-dev
- name: Configure CMake
run: cmake -S examples -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
- name: Build
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}}

View file

@ -147,28 +147,28 @@ private:
# undef CRUDE_MAX4
# undef CRUDE_MAX3
# undef CRUDE_MAX2
using storage_t = std::aligned_storage<max_size, max_align>::type;
struct storage_t { alignas(max_align) unsigned char data[max_size]; };
static object* object_ptr( storage_t& storage) { return reinterpret_cast< object*>(&storage); }
static const object* object_ptr(const storage_t& storage) { return reinterpret_cast<const object*>(&storage); }
static array* array_ptr( storage_t& storage) { return reinterpret_cast< array*>(&storage); }
static const array* array_ptr(const storage_t& storage) { return reinterpret_cast<const array*>(&storage); }
static string* string_ptr( storage_t& storage) { return reinterpret_cast< string*>(&storage); }
static const string* string_ptr(const storage_t& storage) { return reinterpret_cast<const string*>(&storage); }
static boolean* boolean_ptr( storage_t& storage) { return reinterpret_cast< boolean*>(&storage); }
static const boolean* boolean_ptr(const storage_t& storage) { return reinterpret_cast<const boolean*>(&storage); }
static number* number_ptr( storage_t& storage) { return reinterpret_cast< number*>(&storage); }
static const number* number_ptr(const storage_t& storage) { return reinterpret_cast<const number*>(&storage); }
static object* object_ptr( storage_t& storage) { return reinterpret_cast< object*>(storage.data); }
static const object* object_ptr(const storage_t& storage) { return reinterpret_cast<const object*>(storage.data); }
static array* array_ptr( storage_t& storage) { return reinterpret_cast< array*>(storage.data); }
static const array* array_ptr(const storage_t& storage) { return reinterpret_cast<const array*>(storage.data); }
static string* string_ptr( storage_t& storage) { return reinterpret_cast< string*>(storage.data); }
static const string* string_ptr(const storage_t& storage) { return reinterpret_cast<const string*>(storage.data); }
static boolean* boolean_ptr( storage_t& storage) { return reinterpret_cast< boolean*>(storage.data); }
static const boolean* boolean_ptr(const storage_t& storage) { return reinterpret_cast<const boolean*>(storage.data); }
static number* number_ptr( storage_t& storage) { return reinterpret_cast< number*>(storage.data); }
static const number* number_ptr(const storage_t& storage) { return reinterpret_cast<const number*>(storage.data); }
static type_t construct(storage_t& storage, type_t type)
{
switch (type)
{
case type_t::object: new (&storage) object(); break;
case type_t::array: new (&storage) array(); break;
case type_t::string: new (&storage) string(); break;
case type_t::boolean: new (&storage) boolean(); break;
case type_t::number: new (&storage) number(); break;
case type_t::object: new (storage.data) object(); break;
case type_t::array: new (storage.data) array(); break;
case type_t::string: new (storage.data) string(); break;
case type_t::boolean: new (storage.data) boolean(); break;
case type_t::number: new (storage.data) number(); break;
default: break;
}
@ -176,15 +176,15 @@ private:
}
static type_t construct(storage_t& storage, null) { (void)storage; return type_t::null; }
static type_t construct(storage_t& storage, object&& value) { new (&storage) object(std::forward<object>(value)); return type_t::object; }
static type_t construct(storage_t& storage, const object& value) { new (&storage) object(value); return type_t::object; }
static type_t construct(storage_t& storage, array&& value) { new (&storage) array(std::forward<array>(value)); return type_t::array; }
static type_t construct(storage_t& storage, const array& value) { new (&storage) array(value); return type_t::array; }
static type_t construct(storage_t& storage, string&& value) { new (&storage) string(std::forward<string>(value)); return type_t::string; }
static type_t construct(storage_t& storage, const string& value) { new (&storage) string(value); return type_t::string; }
static type_t construct(storage_t& storage, const char* value) { new (&storage) string(value); return type_t::string; }
static type_t construct(storage_t& storage, boolean value) { new (&storage) boolean(value); return type_t::boolean; }
static type_t construct(storage_t& storage, number value) { new (&storage) number(value); return type_t::number; }
static type_t construct(storage_t& storage, object&& value) { new (storage.data) object(std::forward<object>(value)); return type_t::object; }
static type_t construct(storage_t& storage, const object& value) { new (storage.data) object(value); return type_t::object; }
static type_t construct(storage_t& storage, array&& value) { new (storage.data) array(std::forward<array>(value)); return type_t::array; }
static type_t construct(storage_t& storage, const array& value) { new (storage.data) array(value); return type_t::array; }
static type_t construct(storage_t& storage, string&& value) { new (storage.data) string(std::forward<string>(value)); return type_t::string; }
static type_t construct(storage_t& storage, const string& value) { new (storage.data) string(value); return type_t::string; }
static type_t construct(storage_t& storage, const char* value) { new (storage.data) string(value); return type_t::string; }
static type_t construct(storage_t& storage, boolean value) { new (storage.data) boolean(value); return type_t::boolean; }
static type_t construct(storage_t& storage, number value) { new (storage.data) number(value); return type_t::number; }
static void destruct(storage_t& storage, type_t type)
{

View file

@ -1,3 +1,37 @@
v0.10.0 (WIP):
BREAKING: Editor: Ensure CreateItemAction is not activated fom invalid state, thanks @pthom
From this point ed::EndCreate() and ed::EndDelete() can only be called when
ed::BeginCreate() and ed::BeginDelete() calls were successful.
BREAKING: Editor: Minimum supported version is now Dear ImGui 1.89 (August 2022)
BREAKING: Canvas: Minimum supported version is now Dear ImGui 1.89 (August 2022)
BREAKING: Examples: Minimum supported version is now Dear ImGui 1.89 (August 2022)
RESTRUCTURE:
Removed local copy of all dependencies in favor of auto checkout. This should also reduce
user confusion and attempt to use ancient version of ImGui embedded in the repository.
NEW: Canvas: Add example of zooming at fixed point (#270)
NEW: Editor: Add smooth zoom (#266)
CHANGE: Canvas: Use ImDrawCallback_ImCanvas macro as draw callback sentinel (#256), thanks @nspitko
BUGFIX: Examples: Call ed::EndCreate() and ed::EndDelete() only when ed::BeginCreate() and ed::BeginDelete() returned true
BUGFIX: Canvas: Ensure SentinelDrawCallback cleanup (#255)
BUGFIX: Editor: Don't call Reasume/Suspend on invisible canvas (#255)
BUGFIX: Canvas: Remember index of first command buffer to not miss updating any used (#260)
BUGFIX: Editor: Don't duplicated ImVec2/ImVec3 == != operators defined since ImGui r19002 (#268)
BUGFIX: Examples: Use imgui_impl_opengl3_loader.h instead of gl3w (#264)
v0.9.2 (2023-09-01):
NEW: Editor: Add offset of hover/select to style (thanks @MultiPain)

View file

@ -67,9 +67,7 @@ Node Editor sources are located in root project directory. To use it, simply cop
[Examples](../examples) can be build with CMake:
```
Windows:
cmake -S examples -B build -G "Visual Studio 15 2017 Win64"
or
cmake -S examples -B build -G "Visual Studio 16 2019" -A x64
cmake -S examples -B build -G "Visual Studio 17 2022"
macOS:
cmake -S examples -B build -G "Xcode"

View file

@ -1,24 +1,20 @@
cmake_minimum_required(VERSION 3.12)
project(imgui-node-editor)
project(imgui-node-editor-examples)
# Define IMGUI_NODE_EDITOR_ROOT_DIR pointing to project root directory
get_filename_component(IMGUI_NODE_EDITOR_ROOT_DIR ${CMAKE_SOURCE_DIR}/.. ABSOLUTE CACHE)
get_filename_component(IMGUI_NODE_EDITOR_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/.. ABSOLUTE CACHE)
# Enable solution folders in Visual Studio and Folders in Xcode
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
# Point CMake where to look for module files.
list(APPEND CMAKE_MODULE_PATH ${IMGUI_NODE_EDITOR_ROOT_DIR}/misc/cmake-modules)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
# Node editor use C++14
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED YES)
# Macro that will configure an example application
macro(add_example_executable name)
project(${name})
@ -132,3 +128,5 @@ add_subdirectory(simple-example)
add_subdirectory(widgets-example)
add_subdirectory(basic-interaction-example)
add_subdirectory(blueprints-example)
set_property(DIRECTORY PROPERTY VS_STARTUP_PROJECT blueprints-example)

View file

@ -4,7 +4,6 @@ set(_Application_Sources
include/application.h
source/application.cpp
source/entry_point.cpp
source/imgui_extra_keys.h
source/config.h.in
source/setup.h
source/platform.h
@ -19,78 +18,25 @@ add_library(application STATIC)
target_include_directories(application PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
find_package(imgui REQUIRED)
find_package(stb_image REQUIRED)
find_package(ScopeGuard REQUIRED)
target_link_libraries(application PUBLIC imgui)
target_link_libraries(application PRIVATE stb_image ScopeGuard)
set(imgui_components)
if (WIN32)
list(APPEND _Application_Sources
source/imgui_impl_dx11.cpp
source/imgui_impl_dx11.h
source/imgui_impl_win32.cpp
source/imgui_impl_win32.h
)
set(_DXSDK_Dir ${IMGUI_NODE_EDITOR_ROOT_DIR}/external/DXSDK)
set(_DXSDK_Arch x86)
if (${CMAKE_SIZEOF_VOID_P} EQUAL 8)
set(_DXSDK_Arch x64)
endif()
add_library(dxerr STATIC ${_DXSDK_Dir}/src/dxerr.cpp)
target_include_directories(dxerr PUBLIC "${_DXSDK_Dir}/include")
set_property(TARGET dxerr PROPERTY FOLDER "external")
add_library(d3dx11 UNKNOWN IMPORTED)
set_target_properties(d3dx11 PROPERTIES
IMPORTED_LOCATION "${_DXSDK_Dir}/lib/${_DXSDK_Arch}/d3dx11.lib"
IMPORTED_LOCATION_DEBUG "${_DXSDK_Dir}/lib/${_DXSDK_Arch}/d3dx11d.lib"
INTERFACE_INCLUDE_DIRECTORIES "${_DXSDK_Dir}/include"
INTERFACE_LINK_LIBRARIES "$<$<CONFIG:Debug>:dxerr>"
)
target_link_libraries(application PRIVATE d3d11.lib d3dcompiler.lib d3dx11)
list(APPEND imgui_components win32 dx11)
target_link_libraries(application PRIVATE imgui::win32 imgui::dx11)
else()
find_package(OpenGL REQUIRED)
find_package(glfw3 3 REQUIRED)
if (APPLE)
target_link_libraries(application PRIVATE
"-framework CoreFoundation"
"-framework Cocoa"
"-framework IOKit"
"-framework CoreVideo"
)
endif()
find_package(glfw REQUIRED)
list(APPEND imgui_components glfw opengl3)
target_link_libraries(application PRIVATE imgui::glfw imgui::opengl3)
set(HAVE_GLFW3 YES)
endif()
find_package(imgui REQUIRED COMPONENTS ${imgui_components})
find_package(stb REQUIRED COMPONENTS image)
target_link_libraries(application PUBLIC imgui)
target_link_libraries(application PRIVATE stb::image)
if (OpenGL_FOUND)
set(HAVE_OPENGL YES)
find_package(gl3w REQUIRED)
# Explicitly select embedded GL3W loader
target_compile_definitions(application PRIVATE IMGUI_IMPL_OPENGL_LOADER_GL3W)
target_include_directories(application PRIVATE ${OPENGL_INCLUDE_DIR})
target_link_libraries(application PRIVATE ${OPENGL_gl_LIBRARY} gl3w)
list(APPEND _Application_Sources
source/imgui_impl_opengl3.cpp
source/imgui_impl_opengl3.h
)
endif()
if (glfw3_FOUND)
set(HAVE_GLFW3 YES)
list(APPEND _Application_Sources
source/imgui_impl_glfw.cpp
source/imgui_impl_glfw.h
)
target_link_libraries(application PRIVATE
glfw
)
endif()
configure_file(
@ -109,4 +55,4 @@ source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" FILES ${_Application_Sources})
target_sources(application PRIVATE ${_Application_Sources})
set_property(TARGET application PROPERTY FOLDER "examples")
set_property(TARGET application PROPERTY FOLDER "lib")

View file

@ -2,13 +2,7 @@
# include "setup.h"
# include "platform.h"
# include "renderer.h"
extern "C" {
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_STATIC
#include "stb_image.h"
}
# include "stb_image.h"
Application::Application(const char* name)
: Application(name, 0, nullptr)
@ -94,9 +88,8 @@ void Application::RecreateFontAtlas()
io.Fonts = IM_NEW(ImFontAtlas);
ImFontConfig config;
config.OversampleH = 4;
config.OversampleV = 4;
config.PixelSnapH = false;
config.PixelSnapH = true;
config.RasterizerDensity = m_Platform->GetFramebufferScale();
m_DefaultFont = io.Fonts->AddFontFromFileTTF("data/Play-Regular.ttf", 18.0f, &config);
m_HeaderFont = io.Fonts->AddFontFromFileTTF("data/Cuprum-Bold.ttf", 20.0f, &config);
@ -113,29 +106,19 @@ void Application::Frame()
if (m_Platform->HasFramebufferScaleChanged())
{
m_Renderer->InvalidateResources();
RecreateFontAtlas();
m_Renderer->UpdateResources();
m_Platform->AcknowledgeFramebufferScaleChanged();
}
const float windowScale = m_Platform->GetWindowScale();
const float framebufferScale = m_Platform->GetFramebufferScale();
if (io.WantSetMousePos)
{
io.MousePos.x *= windowScale;
io.MousePos.y *= windowScale;
}
m_Platform->NewFrame();
// Don't touch "uninitialized" mouse position
if (io.MousePos.x > -FLT_MAX && io.MousePos.y > -FLT_MAX)
{
io.MousePos.x /= windowScale;
io.MousePos.y /= windowScale;
}
io.DisplaySize.x /= windowScale;
io.DisplaySize.y /= windowScale;
io.DisplaySize.x *= windowScale;
io.DisplaySize.y *= windowScale;
io.DisplayFramebufferScale.x = framebufferScale;
io.DisplayFramebufferScale.y = framebufferScale;
@ -163,7 +146,30 @@ void Application::Frame()
// Rendering
m_Renderer->Clear(ImColor(32, 32, 32, 255));
ImGui::Render();
m_Renderer->RenderDrawData(ImGui::GetDrawData());
// Manually scale the draw data, because ImGui backends are not yet
// consistent in handling FramebufferScale
auto drawData = ImGui::GetDrawData();
drawData->DisplaySize.x *= framebufferScale;
drawData->DisplaySize.y *= framebufferScale;
for (int i = 0; i < drawData->CmdListsCount; i++)
{
auto& cmdList = drawData->CmdLists[i];
for (auto& vtx : cmdList->VtxBuffer)
{
vtx.pos.x *= framebufferScale;
vtx.pos.y *= framebufferScale;
}
}
drawData->ScaleClipRects(drawData->FramebufferScale);
drawData->FramebufferScale.x = 1.0f;
drawData->FramebufferScale.y = 1.0f;
m_Renderer->RenderDrawData(drawData);
m_Platform->FinishFrame();
}

View file

@ -1,65 +0,0 @@
# pragma once
# include <imgui.h>
# if !defined(IMGUI_VERSION_NUM) || (IMGUI_VERSION_NUM < 18822)
# include <type_traits>
// https://stackoverflow.com/a/8597498
# define DECLARE_HAS_NESTED(Name, Member) \
\
template<class T> \
struct has_nested_ ## Name \
{ \
typedef char yes; \
typedef yes(&no)[2]; \
\
template<class U> static yes test(decltype(U::Member)*); \
template<class U> static no test(...); \
\
static bool const value = sizeof(test<T>(0)) == sizeof(yes); \
};
# define DECLARE_KEY_TESTER(Key) \
DECLARE_HAS_NESTED(Key, Key) \
struct KeyTester_ ## Key \
{ \
template <typename T> \
static int Get(typename std::enable_if<has_nested_ ## Key<ImGuiKey_>::value, T>::type*) \
{ \
return T::Key; \
} \
\
template <typename T> \
static int Get(typename std::enable_if<!has_nested_ ## Key<ImGuiKey_>::value, T>::type*) \
{ \
return -1; \
} \
}
DECLARE_KEY_TESTER(ImGuiKey_F);
DECLARE_KEY_TESTER(ImGuiKey_D);
static inline int GetEnumValueForF()
{
return KeyTester_ImGuiKey_F::Get<ImGuiKey_>(nullptr);
}
static inline int GetEnumValueForD()
{
return KeyTester_ImGuiKey_D::Get<ImGuiKey_>(nullptr);
}
# else
static inline ImGuiKey GetEnumValueForF()
{
return ImGuiKey_F;
}
static inline ImGuiKey GetEnumValueForD()
{
return ImGuiKey_D;
}
# endif

View file

@ -1,681 +0,0 @@
// dear imgui: Renderer for DirectX11
// This needs to be used along with a Platform Binding (e.g. Win32)
// Implemented features:
// [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp.
// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices.
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp
// https://github.com/ocornut/imgui
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2019-05-29: DirectX11: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
// 2019-04-30: DirectX11: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
// 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
// 2018-08-01: DirectX11: Querying for IDXGIFactory instead of IDXGIFactory1 to increase compatibility.
// 2018-07-13: DirectX11: Fixed unreleased resources in Init and Shutdown functions.
// 2018-06-08: Misc: Extracted imgui_impl_dx11.cpp/.h away from the old combined DX11+Win32 example.
// 2018-06-08: DirectX11: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX11_RenderDrawData() in the .h file so you can call it yourself.
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
// 2016-05-07: DirectX11: Disabling depth-write.
#include "imgui.h"
#include "imgui_impl_dx11.h"
// DirectX
struct IUnknown;
#include <stdio.h>
#include <d3d11.h>
#include <d3dcompiler.h>
#ifdef _MSC_VER
#pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
#endif
struct TEXTURE;
// DirectX data
static ID3D11Device* g_pd3dDevice = NULL;
static ID3D11DeviceContext* g_pd3dDeviceContext = NULL;
static IDXGIFactory* g_pFactory = NULL;
static ID3D11Buffer* g_pVB = NULL;
static ID3D11Buffer* g_pIB = NULL;
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 ImTextureID g_pFontTextureID = NULL;
static ID3D11RasterizerState* g_pRasterizerState = NULL;
static ID3D11BlendState* g_pBlendState = NULL;
static ID3D11DepthStencilState* g_pDepthStencilState = NULL;
static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
static ImVector<TEXTURE*> g_Textures;
struct VERTEX_CONSTANT_BUFFER
{
float mvp[4][4];
};
struct TEXTURE
{
TEXTURE()
{
View = NULL;
Width = 0;
Height = 0;
}
ID3D11ShaderResourceView* View;
int Width;
int Height;
ImVector<unsigned char> Data;
};
// Forward Declarations
static bool ImGui_UploadTexture(TEXTURE* texture);
static void ImGui_ReleaseTexture(TEXTURE* texture);
static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceContext* ctx)
{
// Setup viewport
D3D11_VIEWPORT vp;
memset(&vp, 0, sizeof(D3D11_VIEWPORT));
vp.Width = draw_data->DisplaySize.x * draw_data->FramebufferScale.x;
vp.Height = draw_data->DisplaySize.y * draw_data->FramebufferScale.y;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = vp.TopLeftY = 0;
ctx->RSSetViewports(1, &vp);
// Setup shader and vertex buffers
unsigned int stride = sizeof(ImDrawVert);
unsigned int offset = 0;
ctx->IASetInputLayout(g_pInputLayout);
ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
ctx->VSSetShader(g_pVertexShader, NULL, 0);
ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
ctx->PSSetShader(g_pPixelShader, NULL, 0);
ctx->PSSetSamplers(0, 1, &g_pFontSampler);
// Setup blend state
const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff);
ctx->OMSetDepthStencilState(g_pDepthStencilState, 0);
ctx->RSSetState(g_pRasterizerState);
}
// Render function
// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
{
// Avoid rendering when minimized
if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
return;
ID3D11DeviceContext* ctx = g_pd3dDeviceContext;
// Create and grow vertex/index buffers if needed
if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
{
if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
D3D11_BUFFER_DESC desc;
memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVB) < 0)
return;
}
if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
{
if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
D3D11_BUFFER_DESC desc;
memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pIB) < 0)
return;
}
// Upload vertex/index data into a single contiguous GPU buffer
D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
if (ctx->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
return;
if (ctx->Map(g_pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
return;
ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
vtx_dst += cmd_list->VtxBuffer.Size;
idx_dst += cmd_list->IdxBuffer.Size;
}
ctx->Unmap(g_pVB, 0);
ctx->Unmap(g_pIB, 0);
// Setup orthographic projection matrix into our constant buffer
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
{
D3D11_MAPPED_SUBRESOURCE mapped_resource;
if (ctx->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
return;
VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData;
float L = draw_data->DisplayPos.x;
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
float T = draw_data->DisplayPos.y;
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
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(&constant_buffer->mvp, mvp, sizeof(mvp));
ctx->Unmap(g_pVertexConstantBuffer, 0);
}
// Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
struct BACKUP_DX11_STATE
{
UINT ScissorRectsCount, ViewportsCount;
D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
ID3D11RasterizerState* RS;
ID3D11BlendState* BlendState;
FLOAT BlendFactor[4];
UINT SampleMask;
UINT StencilRef;
ID3D11DepthStencilState* DepthStencilState;
ID3D11ShaderResourceView* PSShaderResource;
ID3D11SamplerState* PSSampler;
ID3D11PixelShader* PS;
ID3D11VertexShader* VS;
UINT PSInstancesCount, VSInstancesCount;
ID3D11ClassInstance* PSInstances[256], *VSInstances[256]; // 256 is max according to PSSetShader documentation
D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
DXGI_FORMAT IndexBufferFormat;
ID3D11InputLayout* InputLayout;
};
BACKUP_DX11_STATE old;
old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
ctx->RSGetState(&old.RS);
ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
ctx->PSGetSamplers(0, 1, &old.PSSampler);
old.PSInstancesCount = old.VSInstancesCount = 256;
ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
ctx->IAGetInputLayout(&old.InputLayout);
// Setup desired DX state
ImGui_ImplDX11_SetupRenderState(draw_data, ctx);
// Render command lists
// (Because we merged all buffers into a single one, we maintain our own offset into them)
int global_idx_offset = 0;
int global_vtx_offset = 0;
// Will project scissor/clipping rectangles into framebuffer space
ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback != NULL)
{
// User callback, registered via ImDrawList::AddCallback()
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
ImGui_ImplDX11_SetupRenderState(draw_data, ctx);
else
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
ImVec4 clip_rect;
clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x;
clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y;
clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x;
clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y;
// Apply scissor/clipping rectangle
const D3D11_RECT r = { (LONG)clip_rect.x, (LONG)clip_rect.y, (LONG)clip_rect.z, (LONG)clip_rect.w };
ctx->RSSetScissorRects(1, &r);
// Bind texture, Draw
TEXTURE* texture = (TEXTURE*)pcmd->TextureId;
ID3D11ShaderResourceView* textureView = texture ? texture->View : nullptr;
ctx->PSSetShaderResources(0, 1, &textureView);
ctx->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
}
}
global_idx_offset += cmd_list->IdxBuffer.Size;
global_vtx_offset += cmd_list->VtxBuffer.Size;
}
// Restore modified DX state
ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
}
static void ImGui_ImplDX11_CreateFontsTexture()
{
// Build texture atlas
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
g_pFontTextureID = ImGui_CreateTexture(pixels, width, height);
io.Fonts->TexID = g_pFontTextureID;
// 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);
}
}
bool ImGui_ImplDX11_CreateDeviceObjects()
{
if (!g_pd3dDevice)
return false;
if (g_pFontSampler)
ImGui_ImplDX11_InvalidateDeviceObjects();
// By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
// If you would like to use this DX11 sample code but remove this dependency you can:
// 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
// 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
// See https://github.com/ocornut/imgui/pull/638 for sources and details.
// Create the vertex shader
{
static const char* vertexShader =
"cbuffer vertexBuffer : register(b0) \
{\
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_4_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 false;
if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK)
return false;
// Create the input layout
D3D11_INPUT_ELEMENT_DESC local_layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
return false;
// Create the constant buffer
{
D3D11_BUFFER_DESC desc;
desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
g_pd3dDevice->CreateBuffer(&desc, 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); \
out_col.rgb *= out_col.a; \
return out_col; \
}";
D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_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 false;
if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK)
return false;
}
// 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_ONE;
desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
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_pBlendState);
}
// Create the rasterizer state
{
D3D11_RASTERIZER_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.FillMode = D3D11_FILL_SOLID;
desc.CullMode = D3D11_CULL_NONE;
desc.ScissorEnable = true;
desc.DepthClipEnable = true;
g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState);
}
// Create depth-stencil State
{
D3D11_DEPTH_STENCIL_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.DepthEnable = false;
desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
desc.StencilEnable = false;
desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
desc.BackFace = desc.FrontFace;
g_pd3dDevice->CreateDepthStencilState(&desc, &g_pDepthStencilState);
}
ImGui_ImplDX11_CreateFontsTexture();
for (auto& texture : g_Textures)
ImGui_UploadTexture(texture);
return true;
}
void ImGui_ImplDX11_InvalidateDeviceObjects()
{
if (!g_pd3dDevice)
return;
for (auto& texture : g_Textures)
ImGui_ReleaseTexture(texture);
if (g_pFontTextureID)
{
ImGui_DestroyTexture(g_pFontTextureID);
g_pFontTextureID = NULL;
}
if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
if (g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; }
if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; }
if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; }
if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; }
if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; }
if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; }
if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; }
if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
}
bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context)
{
// Setup back-end capabilities flags
ImGuiIO& io = ImGui::GetIO();
io.BackendRendererName = "imgui_impl_dx11";
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
// Get factory from device
IDXGIDevice* pDXGIDevice = NULL;
IDXGIAdapter* pDXGIAdapter = NULL;
IDXGIFactory* pFactory = NULL;
if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK)
if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK)
if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK)
{
g_pd3dDevice = device;
g_pd3dDeviceContext = device_context;
g_pFactory = pFactory;
}
if (pDXGIDevice) pDXGIDevice->Release();
if (pDXGIAdapter) pDXGIAdapter->Release();
g_pd3dDevice->AddRef();
g_pd3dDeviceContext->AddRef();
g_Textures.reserve(16);
return true;
}
void ImGui_ImplDX11_Shutdown()
{
ImGui_ImplDX11_InvalidateDeviceObjects();
if (g_pFactory) { g_pFactory->Release(); g_pFactory = NULL; }
if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = NULL; }
}
void ImGui_ImplDX11_NewFrame()
{
if (!g_pFontSampler)
ImGui_ImplDX11_CreateDeviceObjects();
}
extern "C" {
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_STATIC
#include "stb_image.h"
}
ImTextureID ImGui_LoadTexture(const char* path)
{
int width = 0, height = 0, component = 0;
if (auto data = stbi_load(path, &width, &height, &component, 4))
{
auto texture = ImGui_CreateTexture(data, width, height);
stbi_image_free(data);
return texture;
}
else
return nullptr;
}
ImTextureID ImGui_CreateTexture(const void* data, int width, int height)
{
auto texture = IM_NEW(TEXTURE);
texture->Width = width;
texture->Height = height;
texture->Data.resize(width * height * 4);
memcpy(texture->Data.Data, data, texture->Data.Size);
if (!ImGui_UploadTexture(texture))
{
IM_DELETE(texture);
return nullptr;
}
g_Textures.push_back(texture);
return (ImTextureID)texture;
}
void ImGui_DestroyTexture(ImTextureID texture)
{
if (!texture)
return;
TEXTURE* texture_object = (TEXTURE*)(texture);
ImGui_ReleaseTexture(texture_object);
for (TEXTURE** it = g_Textures.begin(), **itEnd = g_Textures.end(); it != itEnd; ++it)
{
if (*it == texture_object)
{
g_Textures.erase(it);
break;
}
}
IM_DELETE(texture_object);
}
static bool ImGui_UploadTexture(TEXTURE* texture)
{
if (!g_pd3dDevice || !texture)
return false;
if (texture->View)
return true;
D3D11_TEXTURE2D_DESC desc = {};
desc.Width = texture->Width;
desc.Height = texture->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;
D3D11_SUBRESOURCE_DATA subResource = {};
subResource.pSysMem = texture->Data.Data;
subResource.SysMemPitch = desc.Width * 4;
subResource.SysMemSlicePitch = 0;
ID3D11Texture2D *pTexture = nullptr;
g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
if (!pTexture)
return false;
// Create texture view
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = desc.MipLevels;
srvDesc.Texture2D.MostDetailedMip = 0;
g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &texture->View);
pTexture->Release();
return true;
}
static void ImGui_ReleaseTexture(TEXTURE* texture)
{
if (texture)
{
if (texture->View)
{
texture->View->Release();
texture->View = nullptr;
}
}
}
int ImGui_GetTextureWidth(ImTextureID texture)
{
if (TEXTURE* tex = (TEXTURE*)(texture))
return tex->Width;
else
return 0;
}
int ImGui_GetTextureHeight(ImTextureID texture)
{
if (TEXTURE* tex = (TEXTURE*)(texture))
return tex->Height;
else
return 0;
}

View file

@ -1,29 +0,0 @@
// dear imgui: Renderer for DirectX11
// This needs to be used along with a Platform Binding (e.g. Win32)
// Implemented features:
// [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp.
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui
#pragma once
struct ID3D11Device;
struct ID3D11DeviceContext;
IMGUI_IMPL_API bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context);
IMGUI_IMPL_API void ImGui_ImplDX11_Shutdown();
IMGUI_IMPL_API void ImGui_ImplDX11_NewFrame();
IMGUI_IMPL_API void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data);
// Use if you want to reset your rendering device without losing ImGui state.
IMGUI_IMPL_API void ImGui_ImplDX11_InvalidateDeviceObjects();
IMGUI_IMPL_API bool ImGui_ImplDX11_CreateDeviceObjects();
IMGUI_IMPL_API ImTextureID ImGui_LoadTexture(const char* path);
IMGUI_IMPL_API ImTextureID ImGui_CreateTexture(const void* data, int width, int height);
IMGUI_IMPL_API void ImGui_DestroyTexture(ImTextureID texture);
IMGUI_IMPL_API int ImGui_GetTextureWidth(ImTextureID texture);
IMGUI_IMPL_API int ImGui_GetTextureHeight(ImTextureID texture);

View file

@ -1,382 +0,0 @@
// dear imgui: Platform Binding for GLFW
// This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan..)
// (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
// (Requires: GLFW 3.1+)
// Implemented features:
// [X] Platform: Clipboard support.
// [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+).
// [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE).
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2020-01-17: Inputs: Disable error callback while assigning mouse cursors because some X11 setup don't have them and it generates errors.
// 2019-12-05: Inputs: Added support for new mouse cursors added in GLFW 3.4+ (resizing cursors, not allowed cursor).
// 2019-10-18: Misc: Previously installed user callbacks are now restored on shutdown.
// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
// 2019-05-11: Inputs: Don't filter value from character callback before calling AddInputCharacter().
// 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized.
// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
// 2018-11-07: Inputs: When installing our GLFW callbacks, we save user's previously installed ones - if any - and chain call them.
// 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls.
// 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
// 2018-06-08: Misc: Extracted imgui_impl_glfw.cpp/.h away from the old combined GLFW+OpenGL/Vulkan examples.
// 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
// 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value, passed to glfwSetCursor()).
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
// 2018-01-25: Inputs: Added gamepad support if ImGuiConfigFlags_NavEnableGamepad is set.
// 2018-01-25: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set).
// 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
// 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
// 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
// 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_extra_keys.h"
// GLFW
#include <GLFW/glfw3.h>
#ifdef _WIN32
#undef APIENTRY
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h> // for glfwGetWin32Window
#endif
#define GLFW_HAS_WINDOW_TOPMOST (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ GLFW_FLOATING
#define GLFW_HAS_WINDOW_HOVERED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ GLFW_HOVERED
#define GLFW_HAS_WINDOW_ALPHA (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwSetWindowOpacity
#define GLFW_HAS_PER_MONITOR_DPI (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwGetMonitorContentScale
#define GLFW_HAS_VULKAN (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ glfwCreateWindowSurface
#ifdef GLFW_RESIZE_NESW_CURSOR // let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2019-11-29 (cursors defines) // FIXME: Remove when GLFW 3.4 is released?
#define GLFW_HAS_NEW_CURSORS (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3400) // 3.4+ GLFW_RESIZE_ALL_CURSOR, GLFW_RESIZE_NESW_CURSOR, GLFW_RESIZE_NWSE_CURSOR, GLFW_NOT_ALLOWED_CURSOR
#else
#define GLFW_HAS_NEW_CURSORS (0)
#endif
// Data
enum GlfwClientApi
{
GlfwClientApi_Unknown,
GlfwClientApi_OpenGL,
GlfwClientApi_Vulkan
};
static GLFWwindow* g_Window = NULL; // Main window
static GlfwClientApi g_ClientApi = GlfwClientApi_Unknown;
static double g_Time = 0.0;
static bool g_MouseJustPressed[ImGuiMouseButton_COUNT] = {};
static GLFWcursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = {};
static bool g_InstalledCallbacks = false;
// Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
static GLFWmousebuttonfun g_PrevUserCallbackMousebutton = NULL;
static GLFWscrollfun g_PrevUserCallbackScroll = NULL;
static GLFWkeyfun g_PrevUserCallbackKey = NULL;
static GLFWcharfun g_PrevUserCallbackChar = NULL;
static const char* ImGui_ImplGlfw_GetClipboardText(void* user_data)
{
return glfwGetClipboardString((GLFWwindow*)user_data);
}
static void ImGui_ImplGlfw_SetClipboardText(void* user_data, const char* text)
{
glfwSetClipboardString((GLFWwindow*)user_data, text);
}
void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods)
{
if (g_PrevUserCallbackMousebutton != NULL)
g_PrevUserCallbackMousebutton(window, button, action, mods);
if (action == GLFW_PRESS && button >= 0 && button < IM_ARRAYSIZE(g_MouseJustPressed))
g_MouseJustPressed[button] = true;
}
void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset)
{
if (g_PrevUserCallbackScroll != NULL)
g_PrevUserCallbackScroll(window, xoffset, yoffset);
ImGuiIO& io = ImGui::GetIO();
io.MouseWheelH += (float)xoffset;
io.MouseWheel += (float)yoffset;
}
void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (g_PrevUserCallbackKey != NULL)
g_PrevUserCallbackKey(window, key, scancode, action, mods);
ImGuiIO& io = ImGui::GetIO();
if (action == GLFW_PRESS)
io.KeysDown[key] = true;
if (action == GLFW_RELEASE)
io.KeysDown[key] = false;
// Modifiers are not reliable across systems
io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL];
io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT];
io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT];
#ifdef _WIN32
io.KeySuper = false;
#else
io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER];
#endif
}
void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c)
{
if (g_PrevUserCallbackChar != NULL)
g_PrevUserCallbackChar(window, c);
ImGuiIO& io = ImGui::GetIO();
io.AddInputCharacter(c);
}
static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api)
{
g_Window = window;
g_Time = 0.0;
// Setup back-end capabilities flags
ImGuiIO& io = ImGui::GetIO();
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
io.BackendPlatformName = "imgui_impl_glfw";
// Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array.
io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB;
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_PageUp] = GLFW_KEY_PAGE_UP;
io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
io.KeyMap[ImGuiKey_Insert] = GLFW_KEY_INSERT;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Space] = GLFW_KEY_SPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
io.KeyMap[ImGuiKey_KeyPadEnter] = GLFW_KEY_KP_ENTER;
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;
int f_index = GetEnumValueForF();
int d_index = GetEnumValueForD();
if (f_index >= 0)
io.KeyMap[f_index] = GLFW_KEY_F;
if (d_index >= 0)
io.KeyMap[d_index] = GLFW_KEY_D;
io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;
io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;
io.ClipboardUserData = g_Window;
#if defined(_WIN32)
//io.ImeWindowHandle = (void*)glfwGetWin32Window(g_Window);
#endif
// Create mouse cursors
// (By design, on X11 cursors are user configurable and some cursors may be missing. When a cursor doesn't exist,
// GLFW will emit an error which will often be printed by the app, so we temporarily disable error reporting.
// Missing cursors will return NULL and our _UpdateMouseCursor() function will use the Arrow cursor instead.)
GLFWerrorfun prev_error_callback = glfwSetErrorCallback(NULL);
g_MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
g_MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);
g_MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);
g_MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);
g_MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR);
#if GLFW_HAS_NEW_CURSORS
g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR);
g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR);
g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR);
g_MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR);
#else
g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
g_MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
#endif
glfwSetErrorCallback(prev_error_callback);
// Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
g_PrevUserCallbackMousebutton = NULL;
g_PrevUserCallbackScroll = NULL;
g_PrevUserCallbackKey = NULL;
g_PrevUserCallbackChar = NULL;
if (install_callbacks)
{
g_InstalledCallbacks = true;
g_PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);
g_PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);
g_PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);
g_PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);
}
g_ClientApi = client_api;
return true;
}
bool ImGui_ImplGlfw_InitForNone(GLFWwindow* window, bool install_callbacks)
{
return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Unknown);
}
bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks)
{
return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL);
}
bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks)
{
return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Vulkan);
}
void ImGui_ImplGlfw_Shutdown()
{
if (g_InstalledCallbacks)
{
glfwSetMouseButtonCallback(g_Window, g_PrevUserCallbackMousebutton);
glfwSetScrollCallback(g_Window, g_PrevUserCallbackScroll);
glfwSetKeyCallback(g_Window, g_PrevUserCallbackKey);
glfwSetCharCallback(g_Window, g_PrevUserCallbackChar);
g_InstalledCallbacks = false;
}
for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
{
glfwDestroyCursor(g_MouseCursors[cursor_n]);
g_MouseCursors[cursor_n] = NULL;
}
g_ClientApi = GlfwClientApi_Unknown;
}
static void ImGui_ImplGlfw_UpdateMousePosAndButtons()
{
// Update buttons
ImGuiIO& io = ImGui::GetIO();
for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
{
// 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[i] = g_MouseJustPressed[i] || glfwGetMouseButton(g_Window, i) != 0;
g_MouseJustPressed[i] = false;
}
// Update mouse position
const ImVec2 mouse_pos_backup = io.MousePos;
io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
#ifdef __EMSCRIPTEN__
const bool focused = true; // Emscripten
#else
const bool focused = glfwGetWindowAttrib(g_Window, GLFW_FOCUSED) != 0;
#endif
if (focused)
{
if (io.WantSetMousePos)
{
glfwSetCursorPos(g_Window, (double)mouse_pos_backup.x, (double)mouse_pos_backup.y);
}
else
{
double mouse_x, mouse_y;
glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
io.MousePos = ImVec2((float)mouse_x, (float)mouse_y);
}
}
}
static void ImGui_ImplGlfw_UpdateMouseCursor()
{
ImGuiIO& io = ImGui::GetIO();
if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) || glfwGetInputMode(g_Window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED)
return;
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
{
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
glfwSetInputMode(g_Window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
}
else
{
// Show OS mouse cursor
// FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here.
glfwSetCursor(g_Window, g_MouseCursors[imgui_cursor] ? g_MouseCursors[imgui_cursor] : g_MouseCursors[ImGuiMouseCursor_Arrow]);
glfwSetInputMode(g_Window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
}
static void ImGui_ImplGlfw_UpdateGamepads()
{
ImGuiIO& io = ImGui::GetIO();
memset(io.NavInputs, 0, sizeof(io.NavInputs));
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
return;
// Update gamepad inputs
#define MAP_BUTTON(NAV_NO, BUTTON_NO) { if (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS) io.NavInputs[NAV_NO] = 1.0f; }
#define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); if (v > 1.0f) v = 1.0f; if (io.NavInputs[NAV_NO] < v) io.NavInputs[NAV_NO] = v; }
int axes_count = 0, buttons_count = 0;
const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count);
const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count);
MAP_BUTTON(ImGuiNavInput_Activate, 0); // Cross / A
MAP_BUTTON(ImGuiNavInput_Cancel, 1); // Circle / B
MAP_BUTTON(ImGuiNavInput_Menu, 2); // Square / X
MAP_BUTTON(ImGuiNavInput_Input, 3); // Triangle / Y
MAP_BUTTON(ImGuiNavInput_DpadLeft, 13); // D-Pad Left
MAP_BUTTON(ImGuiNavInput_DpadRight, 11); // D-Pad Right
MAP_BUTTON(ImGuiNavInput_DpadUp, 10); // D-Pad Up
MAP_BUTTON(ImGuiNavInput_DpadDown, 12); // D-Pad Down
MAP_BUTTON(ImGuiNavInput_FocusPrev, 4); // L1 / LB
MAP_BUTTON(ImGuiNavInput_FocusNext, 5); // R1 / RB
MAP_BUTTON(ImGuiNavInput_TweakSlow, 4); // L1 / LB
MAP_BUTTON(ImGuiNavInput_TweakFast, 5); // R1 / RB
MAP_ANALOG(ImGuiNavInput_LStickLeft, 0, -0.3f, -0.9f);
MAP_ANALOG(ImGuiNavInput_LStickRight,0, +0.3f, +0.9f);
MAP_ANALOG(ImGuiNavInput_LStickUp, 1, +0.3f, +0.9f);
MAP_ANALOG(ImGuiNavInput_LStickDown, 1, -0.3f, -0.9f);
#undef MAP_BUTTON
#undef MAP_ANALOG
if (axes_count > 0 && buttons_count > 0)
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
else
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
}
void ImGui_ImplGlfw_NewFrame()
{
ImGuiIO& io = ImGui::GetIO();
IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame().");
// Setup display size (every frame to accommodate for window resizing)
int w, h;
int display_w, display_h;
glfwGetWindowSize(g_Window, &w, &h);
glfwGetFramebufferSize(g_Window, &display_w, &display_h);
io.DisplaySize = ImVec2((float)w, (float)h);
if (w > 0 && h > 0)
io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h);
// Setup time step
double current_time = glfwGetTime();
io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f);
g_Time = current_time;
ImGui_ImplGlfw_UpdateMousePosAndButtons();
ImGui_ImplGlfw_UpdateMouseCursor();
// Update game controllers (if enabled and available)
ImGui_ImplGlfw_UpdateGamepads();
}

View file

@ -1,36 +0,0 @@
// dear imgui: Platform Binding for GLFW
// This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan..)
// (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
// Implemented features:
// [X] Platform: Clipboard support.
// [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [x] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: 3 cursors types are missing from GLFW.
// [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE).
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui
// About GLSL version:
// The 'glsl_version' initialization parameter defaults to "#version 150" if NULL.
// Only override if your GL version doesn't handle this GLSL version. Keep NULL if unsure!
#pragma once
#include "imgui.h" // IMGUI_IMPL_API
struct GLFWwindow;
IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForNone(GLFWwindow* window, bool install_callbacks);
IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks);
IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks);
IMGUI_IMPL_API void ImGui_ImplGlfw_Shutdown();
IMGUI_IMPL_API void ImGui_ImplGlfw_NewFrame();
// GLFW callbacks
// - When calling Init with 'install_callbacks=true': GLFW callbacks will be installed for you. They will call user's previously installed callbacks, if any.
// - When calling Init with 'install_callbacks=false': GLFW callbacks won't be installed. You will need to call those function yourself from your own GLFW callbacks.
IMGUI_IMPL_API void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
IMGUI_IMPL_API void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset);
IMGUI_IMPL_API void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
IMGUI_IMPL_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c);

View file

@ -1,690 +0,0 @@
// dear imgui: Renderer for modern OpenGL with shaders / programmatic pipeline
// - Desktop GL: 2.x 3.x 4.x
// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
// This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..)
// Implemented features:
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
// [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bit indices.
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2020-07-10: OpenGL: Added support for glad2 OpenGL loader.
// 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX.
// 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix.
// 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset.
// 2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader.
// 2020-01-07: OpenGL: Added support for glbinding 3.x OpenGL loader.
// 2019-10-25: OpenGL: Using a combination of GL define and runtime GL version to decide whether to use glDrawElementsBaseVertex(). Fix building with pre-3.2 GL loaders.
// 2019-09-22: OpenGL: Detect default GL loader using __has_include compiler facility.
// 2019-09-16: OpenGL: Tweak initialization code to allow application calling ImGui_ImplOpenGL3_CreateFontsTexture() before the first NewFrame() call.
// 2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
// 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
// 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop.
// 2019-03-15: OpenGL: Added a GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early.
// 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0).
// 2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if defined by the headers/loader.
// 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
// 2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450).
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
// 2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT) / GL_CLIP_ORIGIN.
// 2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used.
// 2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version default to "#version 300 ES".
// 2018-07-30: OpenGL: Support for GLSL 300 ES and 410 core. Fixes for Emscripten compilation.
// 2018-07-10: OpenGL: Support for more GLSL versions (based on the GLSL version string). Added error output when shaders fail to compile/link.
// 2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old combined GLFW/SDL+OpenGL3 examples.
// 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
// 2018-05-25: OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since this is part of the VAO state.
// 2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a NULL pointer.
// 2018-03-06: OpenGL: Added const char* glsl_version parameter to ImGui_ImplOpenGL3_Init() so user can override the GLSL version e.g. "#version 150".
// 2018-02-23: OpenGL: Create the VAO in the render function so the setup can more easily be used with multiple shared GL context.
// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself.
// 2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150.
// 2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current polygon mode.
// 2017-05-01: OpenGL: Fixed save and restore of current blend func state.
// 2017-05-01: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE.
// 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
// 2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because SDL changes it. (#752)
//----------------------------------------
// OpenGL GLSL GLSL
// version version string
//----------------------------------------
// 2.0 110 "#version 110"
// 2.1 120 "#version 120"
// 3.0 130 "#version 130"
// 3.1 140 "#version 140"
// 3.2 150 "#version 150"
// 3.3 330 "#version 330 core"
// 4.0 400 "#version 400 core"
// 4.1 410 "#version 410 core"
// 4.2 420 "#version 410 core"
// 4.3 430 "#version 430 core"
// ES 2.0 100 "#version 100" = WebGL 1.0
// ES 3.0 300 "#version 300 es" = WebGL 2.0
//----------------------------------------
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#include "imgui_impl_opengl3.h"
#include <stdio.h>
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
// GL includes
#if defined(IMGUI_IMPL_OPENGL_ES2)
#include <GLES2/gl2.h>
#elif defined(IMGUI_IMPL_OPENGL_ES3)
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV))
#include <OpenGLES/ES3/gl.h> // Use GL ES 3
#else
#include <GLES3/gl3.h> // Use GL ES 3
#endif
#else
// About Desktop OpenGL function loaders:
// Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers.
// Helper libraries are often used for this purpose! Here we are supporting a few common ones (gl3w, glew, glad).
// You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own.
#if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W)
#include <GL/gl3w.h> // Needs to be initialized with gl3wInit() in user's code
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW)
#include <GL/glew.h> // Needs to be initialized with glewInit() in user's code.
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD)
#include <glad/glad.h> // Needs to be initialized with gladLoadGL() in user's code.
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2)
#include <glad/gl.h> // Needs to be initialized with gladLoadGL(...) or gladLoaderLoadGL() in user's code.
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2)
#ifndef GLFW_INCLUDE_NONE
#define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors.
#endif
#include <glbinding/Binding.h> // Needs to be initialized with glbinding::Binding::initialize() in user's code.
#include <glbinding/gl/gl.h>
using namespace gl;
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3)
#ifndef GLFW_INCLUDE_NONE
#define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors.
#endif
#include <glbinding/glbinding.h>// Needs to be initialized with glbinding::initialize() in user's code.
#include <glbinding/gl/gl.h>
using namespace gl;
#else
#include IMGUI_IMPL_OPENGL_LOADER_CUSTOM
#endif
#endif
// Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have.
#if defined(IMGUI_IMPL_OPENGL_ES2) || defined(IMGUI_IMPL_OPENGL_ES3) || !defined(GL_VERSION_3_2)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET 0
#else
#define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET 1
#endif
// OpenGL Data
static GLuint g_GlVersion = 0; // Extracted at runtime using GL_MAJOR_VERSION, GL_MINOR_VERSION queries (e.g. 320 for GL 3.2)
static char g_GlslVersionString[32] = ""; // Specified by user or detected based on compile time GL settings.
static GLuint g_FontTexture = 0;
static GLuint g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
static GLint g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; // Uniforms location
static GLuint g_AttribLocationVtxPos = 0, g_AttribLocationVtxUV = 0, g_AttribLocationVtxColor = 0; // Vertex attributes location
static unsigned int g_VboHandle = 0, g_ElementsHandle = 0;
// Functions
bool ImGui_ImplOpenGL3_Init(const char* glsl_version)
{
// Query for GL version (e.g. 320 for GL 3.2)
#if !defined(IMGUI_IMPL_OPENGL_ES2)
GLint major, minor;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
g_GlVersion = (GLuint)(major * 100 + minor * 10);
#else
g_GlVersion = 200; // GLES 2
#endif
// Setup back-end capabilities flags
ImGuiIO& io = ImGui::GetIO();
io.BackendRendererName = "imgui_impl_opengl3";
#if IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
if (g_GlVersion >= 320)
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
#endif
// Store GLSL version string so we can refer to it later in case we recreate shaders.
// Note: GLSL version is NOT the same as GL version. Leave this to NULL if unsure.
#if defined(IMGUI_IMPL_OPENGL_ES2)
if (glsl_version == NULL)
glsl_version = "#version 100";
#elif defined(IMGUI_IMPL_OPENGL_ES3)
if (glsl_version == NULL)
glsl_version = "#version 300 es";
#elif defined(__APPLE__)
if (glsl_version == NULL)
glsl_version = "#version 150";
#else
if (glsl_version == NULL)
glsl_version = "#version 130";
#endif
IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(g_GlslVersionString));
strcpy(g_GlslVersionString, glsl_version);
strcat(g_GlslVersionString, "\n");
// Debugging construct to make it easily visible in the IDE and debugger which GL loader has been selected.
// The code actually never uses the 'gl_loader' variable! It is only here so you can read it!
// If auto-detection fails or doesn't select the same GL loader file as used by your application,
// you are likely to get a crash below.
// You can explicitly select a loader by using '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line.
const char* gl_loader = "Unknown";
IM_UNUSED(gl_loader);
#if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W)
gl_loader = "GL3W";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW)
gl_loader = "GLEW";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD)
gl_loader = "GLAD";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2)
gl_loader = "GLAD2";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2)
gl_loader = "glbinding2";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3)
gl_loader = "glbinding3";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
gl_loader = "custom";
#else
gl_loader = "none";
#endif
// Make an arbitrary GL call (we don't actually need the result)
// IF YOU GET A CRASH HERE: it probably means that you haven't initialized the OpenGL function loader used by this code.
// Desktop OpenGL 3/4 need a function loader. See the IMGUI_IMPL_OPENGL_LOADER_xxx explanation above.
GLint current_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &current_texture);
return true;
}
void ImGui_ImplOpenGL3_Shutdown()
{
ImGui_ImplOpenGL3_DestroyDeviceObjects();
}
void ImGui_ImplOpenGL3_NewFrame()
{
if (!g_ShaderHandle)
ImGui_ImplOpenGL3_CreateDeviceObjects();
}
static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object)
{
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
#ifdef GL_POLYGON_MODE
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
#endif
// Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT)
bool clip_origin_lower_left = true;
#if defined(GL_CLIP_ORIGIN) && !defined(__APPLE__)
GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)&current_clip_origin);
if (current_clip_origin == GL_UPPER_LEFT)
clip_origin_lower_left = false;
#endif
// Setup viewport, orthographic projection matrix
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
float L = draw_data->DisplayPos.x;
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
float T = draw_data->DisplayPos.y;
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left
const float ortho_projection[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, -1.0f, 0.0f },
{ (R+L)/(L-R), (T+B)/(B-T), 0.0f, 1.0f },
};
glUseProgram(g_ShaderHandle);
glUniform1i(g_AttribLocationTex, 0);
glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
#ifdef GL_SAMPLER_BINDING
glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise.
#endif
(void)vertex_array_object;
#ifndef IMGUI_IMPL_OPENGL_ES2
glBindVertexArray(vertex_array_object);
#endif
// Bind vertex/index buffers and setup attributes for ImDrawVert
glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
glEnableVertexAttribArray(g_AttribLocationVtxPos);
glEnableVertexAttribArray(g_AttribLocationVtxUV);
glEnableVertexAttribArray(g_AttribLocationVtxColor);
glVertexAttribPointer(g_AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos));
glVertexAttribPointer(g_AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv));
glVertexAttribPointer(g_AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col));
}
// OpenGL3 Render function.
// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so.
void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
if (fb_width <= 0 || fb_height <= 0)
return;
// Backup GL state
GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture);
glActiveTexture(GL_TEXTURE0);
GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program);
GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture);
#ifdef GL_SAMPLER_BINDING
GLuint last_sampler; glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler);
#endif
GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer);
#ifndef IMGUI_IMPL_OPENGL_ES2
GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object);
#endif
#ifdef GL_POLYGON_MODE
GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
#endif
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb);
GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb);
GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha);
GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha);
GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb);
GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha);
GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
// Setup desired GL state
// Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)
// The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.
GLuint vertex_array_object = 0;
#ifndef IMGUI_IMPL_OPENGL_ES2
glGenVertexArrays(1, &vertex_array_object);
#endif
ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
// Will project scissor/clipping rectangles into framebuffer space
ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
// Render command lists
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
// Upload vertex/index buffers
glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * (int)sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW);
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback != NULL)
{
// User callback, registered via ImDrawList::AddCallback()
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
else
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// Project scissor/clipping rectangles into framebuffer space
ImVec4 clip_rect;
clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x;
clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y;
clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x;
clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y;
if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f)
{
// Apply scissor/clipping rectangle
glScissor((int)clip_rect.x, (int)(fb_height - clip_rect.w), (int)(clip_rect.z - clip_rect.x), (int)(clip_rect.w - clip_rect.y));
// Bind texture, Draw
glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
#if IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
if (g_GlVersion >= 320)
glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)), (GLint)pcmd->VtxOffset);
else
#endif
glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)));
}
}
}
}
// Destroy the temporary VAO
#ifndef IMGUI_IMPL_OPENGL_ES2
glDeleteVertexArrays(1, &vertex_array_object);
#endif
// Restore modified GL state
glUseProgram(last_program);
glBindTexture(GL_TEXTURE_2D, last_texture);
#ifdef GL_SAMPLER_BINDING
glBindSampler(0, last_sampler);
#endif
glActiveTexture(last_active_texture);
#ifndef IMGUI_IMPL_OPENGL_ES2
glBindVertexArray(last_vertex_array_object);
#endif
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
#ifdef GL_POLYGON_MODE
glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]);
#endif
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
}
bool ImGui_ImplOpenGL3_CreateFontsTexture()
{
// Build texture atlas
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
// Upload texture to graphics system
GLint last_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGenTextures(1, &g_FontTexture);
glBindTexture(GL_TEXTURE_2D, g_FontTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#ifdef GL_UNPACK_ROW_LENGTH
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
#endif
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
// Store our identifier
io.Fonts->TexID = (ImTextureID)(intptr_t)g_FontTexture;
// Restore state
glBindTexture(GL_TEXTURE_2D, last_texture);
return true;
}
void ImGui_ImplOpenGL3_DestroyFontsTexture()
{
if (g_FontTexture)
{
ImGuiIO& io = ImGui::GetIO();
glDeleteTextures(1, &g_FontTexture);
io.Fonts->TexID = 0;
g_FontTexture = 0;
}
}
// If you get an error please report on github. You may try different GL context version or GLSL version. See GL<>GLSL version table at the top of this file.
static bool CheckShader(GLuint handle, const char* desc)
{
GLint status = 0, log_length = 0;
glGetShaderiv(handle, GL_COMPILE_STATUS, &status);
glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length);
if ((GLboolean)status == GL_FALSE)
fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s!\n", desc);
if (log_length > 1)
{
ImVector<char> buf;
buf.resize((int)(log_length + 1));
glGetShaderInfoLog(handle, log_length, NULL, (GLchar*)buf.begin());
fprintf(stderr, "%s\n", buf.begin());
}
return (GLboolean)status == GL_TRUE;
}
// If you get an error please report on GitHub. You may try different GL context version or GLSL version.
static bool CheckProgram(GLuint handle, const char* desc)
{
GLint status = 0, log_length = 0;
glGetProgramiv(handle, GL_LINK_STATUS, &status);
glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length);
if ((GLboolean)status == GL_FALSE)
fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! (with GLSL '%s')\n", desc, g_GlslVersionString);
if (log_length > 1)
{
ImVector<char> buf;
buf.resize((int)(log_length + 1));
glGetProgramInfoLog(handle, log_length, NULL, (GLchar*)buf.begin());
fprintf(stderr, "%s\n", buf.begin());
}
return (GLboolean)status == GL_TRUE;
}
bool ImGui_ImplOpenGL3_CreateDeviceObjects()
{
// Backup GL state
GLint last_texture, last_array_buffer;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
#ifndef IMGUI_IMPL_OPENGL_ES2
GLint last_vertex_array;
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
#endif
// Parse GLSL version string
int glsl_version = 130;
sscanf(g_GlslVersionString, "#version %d", &glsl_version);
const GLchar* vertex_shader_glsl_120 =
"uniform mat4 ProjMtx;\n"
"attribute vec2 Position;\n"
"attribute vec2 UV;\n"
"attribute vec4 Color;\n"
"varying vec2 Frag_UV;\n"
"varying 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* vertex_shader_glsl_130 =
"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* vertex_shader_glsl_300_es =
"precision mediump float;\n"
"layout (location = 0) in vec2 Position;\n"
"layout (location = 1) in vec2 UV;\n"
"layout (location = 2) in vec4 Color;\n"
"uniform mat4 ProjMtx;\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* vertex_shader_glsl_410_core =
"layout (location = 0) in vec2 Position;\n"
"layout (location = 1) in vec2 UV;\n"
"layout (location = 2) in vec4 Color;\n"
"uniform mat4 ProjMtx;\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_glsl_120 =
"#ifdef GL_ES\n"
" precision mediump float;\n"
"#endif\n"
"uniform sampler2D Texture;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" vec4 col = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
" col.xyz *= col.w;"
" gl_FragColor = col;\n"
"}\n";
const GLchar* fragment_shader_glsl_130 =
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" vec4 col = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
" col.xyz *= col.w;"
" gl_FragColor = col;\n"
"}\n";
const GLchar* fragment_shader_glsl_300_es =
"precision mediump float;\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"layout (location = 0) out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" vec4 col = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
" col.xyz *= col.w;"
" gl_FragColor = col;\n"
"}\n";
const GLchar* fragment_shader_glsl_410_core =
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"uniform sampler2D Texture;\n"
"layout (location = 0) out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" vec4 col = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
" col.xyz *= col.w;"
" gl_FragColor = col;\n"
"}\n";
// Select shaders matching our GLSL versions
const GLchar* vertex_shader = NULL;
const GLchar* fragment_shader = NULL;
if (glsl_version < 130)
{
vertex_shader = vertex_shader_glsl_120;
fragment_shader = fragment_shader_glsl_120;
}
else if (glsl_version >= 410)
{
vertex_shader = vertex_shader_glsl_410_core;
fragment_shader = fragment_shader_glsl_410_core;
}
else if (glsl_version == 300)
{
vertex_shader = vertex_shader_glsl_300_es;
fragment_shader = fragment_shader_glsl_300_es;
}
else
{
vertex_shader = vertex_shader_glsl_130;
fragment_shader = fragment_shader_glsl_130;
}
// Create shaders
const GLchar* vertex_shader_with_version[2] = { g_GlslVersionString, vertex_shader };
g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(g_VertHandle, 2, vertex_shader_with_version, NULL);
glCompileShader(g_VertHandle);
CheckShader(g_VertHandle, "vertex shader");
const GLchar* fragment_shader_with_version[2] = { g_GlslVersionString, fragment_shader };
g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(g_FragHandle, 2, fragment_shader_with_version, NULL);
glCompileShader(g_FragHandle);
CheckShader(g_FragHandle, "fragment shader");
g_ShaderHandle = glCreateProgram();
glAttachShader(g_ShaderHandle, g_VertHandle);
glAttachShader(g_ShaderHandle, g_FragHandle);
glLinkProgram(g_ShaderHandle);
CheckProgram(g_ShaderHandle, "shader program");
g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
g_AttribLocationVtxPos = (GLuint)glGetAttribLocation(g_ShaderHandle, "Position");
g_AttribLocationVtxUV = (GLuint)glGetAttribLocation(g_ShaderHandle, "UV");
g_AttribLocationVtxColor = (GLuint)glGetAttribLocation(g_ShaderHandle, "Color");
// Create buffers
glGenBuffers(1, &g_VboHandle);
glGenBuffers(1, &g_ElementsHandle);
ImGui_ImplOpenGL3_CreateFontsTexture();
// Restore modified GL state
glBindTexture(GL_TEXTURE_2D, last_texture);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
#ifndef IMGUI_IMPL_OPENGL_ES2
glBindVertexArray(last_vertex_array);
#endif
return true;
}
void ImGui_ImplOpenGL3_DestroyDeviceObjects()
{
if (g_VboHandle) { glDeleteBuffers(1, &g_VboHandle); g_VboHandle = 0; }
if (g_ElementsHandle) { glDeleteBuffers(1, &g_ElementsHandle); g_ElementsHandle = 0; }
if (g_ShaderHandle && g_VertHandle) { glDetachShader(g_ShaderHandle, g_VertHandle); }
if (g_ShaderHandle && g_FragHandle) { glDetachShader(g_ShaderHandle, g_FragHandle); }
if (g_VertHandle) { glDeleteShader(g_VertHandle); g_VertHandle = 0; }
if (g_FragHandle) { glDeleteShader(g_FragHandle); g_FragHandle = 0; }
if (g_ShaderHandle) { glDeleteProgram(g_ShaderHandle); g_ShaderHandle = 0; }
ImGui_ImplOpenGL3_DestroyFontsTexture();
}

View file

@ -1,87 +0,0 @@
// dear imgui: Renderer for modern OpenGL with shaders / programmatic pipeline
// - Desktop GL: 2.x 3.x 4.x
// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
// This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..)
// Implemented features:
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
// [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bit indices.
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui
// About Desktop OpenGL function loaders:
// Modern Desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers.
// Helper libraries are often used for this purpose! Here we are supporting a few common ones (gl3w, glew, glad).
// You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own.
// About GLSL version:
// The 'glsl_version' initialization parameter should be NULL (default) or a "#version XXX" string.
// On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es"
// Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp.
#pragma once
#include "imgui.h" // IMGUI_IMPL_API
// Backend API
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = NULL);
IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data);
// (Optional) Called by Init/NewFrame/Shutdown
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateFontsTexture();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture();
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects();
// Specific OpenGL ES versions
//#define IMGUI_IMPL_OPENGL_ES2 // Auto-detected on Emscripten
//#define IMGUI_IMPL_OPENGL_ES3 // Auto-detected on iOS/Android
// Attempt to auto-detect the default Desktop GL loader based on available header files.
// If auto-detection fails or doesn't select the same GL loader file as used by your application,
// you are likely to get a crash in ImGui_ImplOpenGL3_Init().
// You can explicitly select a loader by using one of the '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line.
#if !defined(IMGUI_IMPL_OPENGL_ES2) \
&& !defined(IMGUI_IMPL_OPENGL_ES3) \
&& !defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) \
&& !defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) \
&& !defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) \
&& !defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) \
&& !defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) \
&& !defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3) \
&& !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
// Try to detect GLES on matching platforms
#if defined(__APPLE__)
#include "TargetConditionals.h"
#endif
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__))
#define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es"
#elif defined(__EMSCRIPTEN__)
#define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100"
// Otherwise try to detect supported Desktop OpenGL loaders..
#elif defined(__has_include)
#if __has_include(<GL/glew.h>)
#define IMGUI_IMPL_OPENGL_LOADER_GLEW
#elif __has_include(<glad/glad.h>)
#define IMGUI_IMPL_OPENGL_LOADER_GLAD
#elif __has_include(<glad/gl.h>)
#define IMGUI_IMPL_OPENGL_LOADER_GLAD2
#elif __has_include(<GL/gl3w.h>)
#define IMGUI_IMPL_OPENGL_LOADER_GL3W
#elif __has_include(<glbinding/glbinding.h>)
#define IMGUI_IMPL_OPENGL_LOADER_GLBINDING3
#elif __has_include(<glbinding/Binding.h>)
#define IMGUI_IMPL_OPENGL_LOADER_GLBINDING2
#else
#error "Cannot detect OpenGL loader!"
#endif
#else
#define IMGUI_IMPL_OPENGL_LOADER_GL3W // Default to GL3W embedded in our repository
#endif
#endif

View file

@ -1,462 +0,0 @@
// dear imgui: Platform Binding for Windows (standard windows API for 32 and 64 bits applications)
// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
// Implemented features:
// [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui)
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
// [X] Platform: Keyboard arrays indexed using VK_* Virtual Key Codes, e.g. ImGui::IsKeyPressed(VK_SPACE).
// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
#include "imgui.h"
#include "imgui_impl_win32.h"
#include "imgui_extra_keys.h"
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <tchar.h>
// Using XInput library for gamepad (with recent Windows SDK this may leads to executables which won't run on Windows 7)
#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
#include <XInput.h>
#else
#define IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT
#endif
#if defined(_MSC_VER) && !defined(IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT)
#pragma comment(lib, "xinput")
//#pragma comment(lib, "Xinput9_1_0")
#endif
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2020-03-03: Inputs: Calling AddInputCharacterUTF16() to support surrogate pairs leading to codepoint >= 0x10000 (for more complete CJK inputs)
// 2020-02-17: Added ImGui_ImplWin32_EnableDpiAwareness(), ImGui_ImplWin32_GetDpiScaleForHwnd(), ImGui_ImplWin32_GetDpiScaleForMonitor() helper functions.
// 2020-01-14: Inputs: Added support for #define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD/IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT.
// 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
// 2019-05-11: Inputs: Don't filter value from WM_CHAR before calling AddInputCharacter().
// 2019-01-17: Misc: Using GetForegroundWindow()+IsChild() instead of GetActiveWindow() to be compatible with windows created in a different thread or parent.
// 2019-01-17: Inputs: Added support for mouse buttons 4 and 5 via WM_XBUTTON* messages.
// 2019-01-15: Inputs: Added support for XInput gamepads (if ImGuiConfigFlags_NavEnableGamepad is set by user application).
// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
// 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
// 2018-06-10: Inputs: Fixed handling of mouse wheel messages to support fine position messages (typically sent by track-pads).
// 2018-06-08: Misc: Extracted imgui_impl_win32.cpp/.h away from the old combined DX9/DX10/DX11/DX12 examples.
// 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag.
// 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling).
// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
// 2018-02-06: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set).
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
// 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
// 2018-01-08: Inputs: Added mapping for ImGuiKey_Insert.
// 2018-01-05: Inputs: Added WM_LBUTTONDBLCLK double-click handlers for window classes with the CS_DBLCLKS flag.
// 2017-10-23: Inputs: Added WM_SYSKEYDOWN / WM_SYSKEYUP handlers so e.g. the VK_MENU key can be read.
// 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging.
// 2016-11-12: Inputs: Only call Win32 ::SetCursor(NULL) when io.MouseDrawCursor is set.
// Win32 Data
static HWND g_hWnd = NULL;
static INT64 g_Time = 0;
static INT64 g_TicksPerSecond = 0;
static ImGuiMouseCursor g_LastMouseCursor = ImGuiMouseCursor_COUNT;
static bool g_HasGamepad = false;
static bool g_WantUpdateHasGamepad = true;
// Functions
bool ImGui_ImplWin32_Init(void* hwnd)
{
if (!::QueryPerformanceFrequency((LARGE_INTEGER*)&g_TicksPerSecond))
return false;
if (!::QueryPerformanceCounter((LARGE_INTEGER*)&g_Time))
return false;
// Setup back-end capabilities flags
g_hWnd = (HWND)hwnd;
ImGuiIO& io = ImGui::GetIO();
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
io.BackendPlatformName = "imgui_impl_win32";
//io.ImeWindowHandle = hwnd;
// Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array that we will update during the application lifetime.
io.KeyMap[ImGuiKey_Tab] = VK_TAB;
io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
io.KeyMap[ImGuiKey_Home] = VK_HOME;
io.KeyMap[ImGuiKey_End] = VK_END;
io.KeyMap[ImGuiKey_Insert] = VK_INSERT;
io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
io.KeyMap[ImGuiKey_Space] = VK_SPACE;
io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
# if defined(IMGUI_VERSION_NUM) && (IMGUI_VERSION_NUM >= 18604)
io.KeyMap[ImGuiKey_KeypadEnter] = VK_RETURN;
# else
io.KeyMap[ImGuiKey_KeyPadEnter] = VK_RETURN;
# endif
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';
int f_index = GetEnumValueForF();
int d_index = GetEnumValueForD();
if (f_index >= 0)
io.KeyMap[f_index] = 'F';
if (d_index >= 0)
io.KeyMap[d_index] = 'D';
return true;
}
void ImGui_ImplWin32_Shutdown()
{
g_hWnd = (HWND)0;
}
static bool ImGui_ImplWin32_UpdateMouseCursor()
{
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
return false;
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
{
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
::SetCursor(NULL);
}
else
{
// Show OS mouse cursor
LPTSTR win32_cursor = IDC_ARROW;
switch (imgui_cursor)
{
case ImGuiMouseCursor_Arrow: win32_cursor = IDC_ARROW; break;
case ImGuiMouseCursor_TextInput: win32_cursor = IDC_IBEAM; break;
case ImGuiMouseCursor_ResizeAll: win32_cursor = IDC_SIZEALL; break;
case ImGuiMouseCursor_ResizeEW: win32_cursor = IDC_SIZEWE; break;
case ImGuiMouseCursor_ResizeNS: win32_cursor = IDC_SIZENS; break;
case ImGuiMouseCursor_ResizeNESW: win32_cursor = IDC_SIZENESW; break;
case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break;
case ImGuiMouseCursor_Hand: win32_cursor = IDC_HAND; break;
case ImGuiMouseCursor_NotAllowed: win32_cursor = IDC_NO; break;
}
::SetCursor(::LoadCursor(NULL, win32_cursor));
}
return true;
}
static void ImGui_ImplWin32_UpdateMousePos()
{
ImGuiIO& io = ImGui::GetIO();
// Set OS mouse position if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
if (io.WantSetMousePos)
{
POINT pos = { (int)(io.MousePos.x), (int)(io.MousePos.y) };
::ClientToScreen(g_hWnd, &pos);
::SetCursorPos(pos.x, pos.y);
}
// Set mouse position
io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
POINT pos;
if (HWND active_window = ::GetForegroundWindow())
if (active_window == g_hWnd || ::IsChild(active_window, g_hWnd))
if (::GetCursorPos(&pos) && ::ScreenToClient(g_hWnd, &pos))
io.MousePos = ImVec2((float)pos.x, (float)pos.y);
}
// Gamepad navigation mapping
static void ImGui_ImplWin32_UpdateGamepads()
{
#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
ImGuiIO& io = ImGui::GetIO();
memset(io.NavInputs, 0, sizeof(io.NavInputs));
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
return;
// Calling XInputGetState() every frame on disconnected gamepads is unfortunately too slow.
// Instead we refresh gamepad availability by calling XInputGetCapabilities() _only_ after receiving WM_DEVICECHANGE.
if (g_WantUpdateHasGamepad)
{
XINPUT_CAPABILITIES caps;
g_HasGamepad = (XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &caps) == ERROR_SUCCESS);
g_WantUpdateHasGamepad = false;
}
XINPUT_STATE xinput_state;
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
if (g_HasGamepad && XInputGetState(0, &xinput_state) == ERROR_SUCCESS)
{
const XINPUT_GAMEPAD& gamepad = xinput_state.Gamepad;
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
#define MAP_BUTTON(NAV_NO, BUTTON_ENUM) { io.NavInputs[NAV_NO] = (gamepad.wButtons & BUTTON_ENUM) ? 1.0f : 0.0f; }
#define MAP_ANALOG(NAV_NO, VALUE, V0, V1) { float vn = (float)(VALUE - V0) / (float)(V1 - V0); if (vn > 1.0f) vn = 1.0f; if (vn > 0.0f && io.NavInputs[NAV_NO] < vn) io.NavInputs[NAV_NO] = vn; }
MAP_BUTTON(ImGuiNavInput_Activate, XINPUT_GAMEPAD_A); // Cross / A
MAP_BUTTON(ImGuiNavInput_Cancel, XINPUT_GAMEPAD_B); // Circle / B
MAP_BUTTON(ImGuiNavInput_Menu, XINPUT_GAMEPAD_X); // Square / X
MAP_BUTTON(ImGuiNavInput_Input, XINPUT_GAMEPAD_Y); // Triangle / Y
MAP_BUTTON(ImGuiNavInput_DpadLeft, XINPUT_GAMEPAD_DPAD_LEFT); // D-Pad Left
MAP_BUTTON(ImGuiNavInput_DpadRight, XINPUT_GAMEPAD_DPAD_RIGHT); // D-Pad Right
MAP_BUTTON(ImGuiNavInput_DpadUp, XINPUT_GAMEPAD_DPAD_UP); // D-Pad Up
MAP_BUTTON(ImGuiNavInput_DpadDown, XINPUT_GAMEPAD_DPAD_DOWN); // D-Pad Down
MAP_BUTTON(ImGuiNavInput_FocusPrev, XINPUT_GAMEPAD_LEFT_SHOULDER); // L1 / LB
MAP_BUTTON(ImGuiNavInput_FocusNext, XINPUT_GAMEPAD_RIGHT_SHOULDER); // R1 / RB
MAP_BUTTON(ImGuiNavInput_TweakSlow, XINPUT_GAMEPAD_LEFT_SHOULDER); // L1 / LB
MAP_BUTTON(ImGuiNavInput_TweakFast, XINPUT_GAMEPAD_RIGHT_SHOULDER); // R1 / RB
MAP_ANALOG(ImGuiNavInput_LStickLeft, gamepad.sThumbLX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768);
MAP_ANALOG(ImGuiNavInput_LStickRight, gamepad.sThumbLX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
MAP_ANALOG(ImGuiNavInput_LStickUp, gamepad.sThumbLY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
MAP_ANALOG(ImGuiNavInput_LStickDown, gamepad.sThumbLY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32767);
#undef MAP_BUTTON
#undef MAP_ANALOG
}
#endif // #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
}
void ImGui_ImplWin32_NewFrame()
{
ImGuiIO& io = ImGui::GetIO();
IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame().");
// Setup display size (every frame to accommodate for window resizing)
RECT rect;
::GetClientRect(g_hWnd, &rect);
io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
// Setup time step
INT64 current_time;
::QueryPerformanceCounter((LARGE_INTEGER*)&current_time);
io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
g_Time = current_time;
// Read keyboard modifiers inputs
io.KeyCtrl = (::GetKeyState(VK_CONTROL) & 0x8000) != 0;
io.KeyShift = (::GetKeyState(VK_SHIFT) & 0x8000) != 0;
io.KeyAlt = (::GetKeyState(VK_MENU) & 0x8000) != 0;
io.KeySuper = false;
// io.KeysDown[], io.MousePos, io.MouseDown[], io.MouseWheel: filled by the WndProc handler below.
// Update OS mouse position
ImGui_ImplWin32_UpdateMousePos();
// Update OS mouse cursor with the cursor requested by imgui
ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
if (g_LastMouseCursor != mouse_cursor)
{
g_LastMouseCursor = mouse_cursor;
ImGui_ImplWin32_UpdateMouseCursor();
}
// Update game controllers (if enabled and available)
ImGui_ImplWin32_UpdateGamepads();
}
// Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions.
#ifndef WM_MOUSEHWHEEL
#define WM_MOUSEHWHEEL 0x020E
#endif
#ifndef DBT_DEVNODES_CHANGED
#define DBT_DEVNODES_CHANGED 0x0007
#endif
// Win32 message handler (process Win32 mouse/keyboard inputs, etc.)
// Call from your application's message handler.
// When implementing your own back-end, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if Dear ImGui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
// Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags.
// PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinates when dragging mouse outside of our window bounds.
// PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag.
#if 0
// Copy this line into your .cpp file to forward declare the function.
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
#endif
IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (ImGui::GetCurrentContext() == NULL)
return 0;
ImGuiIO& io = ImGui::GetIO();
switch (msg)
{
case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK:
{
int button = 0;
if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) { button = 0; }
if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) { button = 1; }
if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) { button = 2; }
if (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONDBLCLK) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; }
if (!ImGui::IsAnyMouseDown() && ::GetCapture() == NULL)
::SetCapture(hwnd);
io.MouseDown[button] = true;
return 0;
}
case WM_LBUTTONUP:
case WM_RBUTTONUP:
case WM_MBUTTONUP:
case WM_XBUTTONUP:
{
int button = 0;
if (msg == WM_LBUTTONUP) { button = 0; }
if (msg == WM_RBUTTONUP) { button = 1; }
if (msg == WM_MBUTTONUP) { button = 2; }
if (msg == WM_XBUTTONUP) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; }
io.MouseDown[button] = false;
if (!ImGui::IsAnyMouseDown() && ::GetCapture() == hwnd)
::ReleaseCapture();
return 0;
}
case WM_MOUSEWHEEL:
io.MouseWheel += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA;
return 0;
case WM_MOUSEHWHEEL:
io.MouseWheelH += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA;
return 0;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
if (wParam < 256)
io.KeysDown[wParam] = 1;
return 0;
case WM_KEYUP:
case WM_SYSKEYUP:
if (wParam < 256)
io.KeysDown[wParam] = 0;
return 0;
case WM_CHAR:
// You can also use ToAscii()+GetKeyboardState() to retrieve characters.
if (wParam > 0 && wParam < 0x10000)
io.AddInputCharacterUTF16((unsigned short)wParam);
return 0;
case WM_SETCURSOR:
if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor())
return 1;
return 0;
case WM_DEVICECHANGE:
if ((UINT)wParam == DBT_DEVNODES_CHANGED)
g_WantUpdateHasGamepad = true;
return 0;
case WM_KILLFOCUS:
for (int n = 0; n < IM_ARRAYSIZE(io.KeysDown); n++)
io.KeysDown[n] = false;
break;
}
return 0;
}
//--------------------------------------------------------------------------------------------------------
// DPI-related helpers (optional)
//--------------------------------------------------------------------------------------------------------
// - Use to enable DPI awareness without having to create an application manifest.
// - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps.
// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc.
// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime,
// neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies.
//---------------------------------------------------------------------------------------------------------
// This is the scheme successfully used by GLFW (from which we borrowed some of the code) and other apps aiming to be highly portable.
// ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it automatically.
// If you are trying to implement your own back-end for your own engine, you may ignore that noise.
//---------------------------------------------------------------------------------------------------------
// Implement some of the functions and types normally declared in recent Windows SDK.
#if !defined(_versionhelpers_H_INCLUDED_) && !defined(_INC_VERSIONHELPERS)
static BOOL IsWindowsVersionOrGreater(WORD major, WORD minor, WORD sp)
{
OSVERSIONINFOEXW osvi = { sizeof(osvi), major, minor, 0, 0, { 0 }, sp, 0, 0, 0, 0 };
DWORD mask = VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR;
ULONGLONG cond = ::VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL);
cond = ::VerSetConditionMask(cond, VER_MINORVERSION, VER_GREATER_EQUAL);
cond = ::VerSetConditionMask(cond, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
return ::VerifyVersionInfoW(&osvi, mask, cond);
}
#define IsWindows8Point1OrGreater() IsWindowsVersionOrGreater(HIBYTE(0x0602), LOBYTE(0x0602), 0) // _WIN32_WINNT_WINBLUE
#endif
#ifndef DPI_ENUMS_DECLARED
typedef enum { PROCESS_DPI_UNAWARE = 0, PROCESS_SYSTEM_DPI_AWARE = 1, PROCESS_PER_MONITOR_DPI_AWARE = 2 } PROCESS_DPI_AWARENESS;
typedef enum { MDT_EFFECTIVE_DPI = 0, MDT_ANGULAR_DPI = 1, MDT_RAW_DPI = 2, MDT_DEFAULT = MDT_EFFECTIVE_DPI } MONITOR_DPI_TYPE;
#endif
#ifndef _DPI_AWARENESS_CONTEXTS_
DECLARE_HANDLE(DPI_AWARENESS_CONTEXT);
#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE (DPI_AWARENESS_CONTEXT)-3
#endif
#ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 (DPI_AWARENESS_CONTEXT)-4
#endif
typedef HRESULT(WINAPI* PFN_SetProcessDpiAwareness)(PROCESS_DPI_AWARENESS); // Shcore.lib + dll, Windows 8.1+
typedef HRESULT(WINAPI* PFN_GetDpiForMonitor)(HMONITOR, MONITOR_DPI_TYPE, UINT*, UINT*); // Shcore.lib + dll, Windows 8.1+
typedef DPI_AWARENESS_CONTEXT(WINAPI* PFN_SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT); // User32.lib + dll, Windows 10 v1607+ (Creators Update)
// Helper function to enable DPI awareness without setting up a manifest
void ImGui_ImplWin32_EnableDpiAwareness()
{
// if (IsWindows10OrGreater()) // This needs a manifest to succeed. Instead we try to grab the function pointer!
{
static HINSTANCE user32_dll = ::LoadLibraryA("user32.dll"); // Reference counted per-process
if (PFN_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContextFn = (PFN_SetThreadDpiAwarenessContext)::GetProcAddress(user32_dll, "SetThreadDpiAwarenessContext"))
{
SetThreadDpiAwarenessContextFn(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
return;
}
}
if (IsWindows8Point1OrGreater())
{
static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
if (PFN_SetProcessDpiAwareness SetProcessDpiAwarenessFn = (PFN_SetProcessDpiAwareness)::GetProcAddress(shcore_dll, "SetProcessDpiAwareness"))
{
SetProcessDpiAwarenessFn(PROCESS_PER_MONITOR_DPI_AWARE);
return;
}
}
#if _WIN32_WINNT >= 0x0600
::SetProcessDPIAware();
#endif
}
#if defined(_MSC_VER) && !defined(NOGDI)
#pragma comment(lib, "gdi32") // Link with gdi32.lib for GetDeviceCaps()
#endif
float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor)
{
UINT xdpi = 96, ydpi = 96;
static BOOL bIsWindows8Point1OrGreater = IsWindows8Point1OrGreater();
if (bIsWindows8Point1OrGreater)
{
static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
if (PFN_GetDpiForMonitor GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor"))
GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi);
}
#ifndef NOGDI
else
{
const HDC dc = ::GetDC(NULL);
xdpi = ::GetDeviceCaps(dc, LOGPIXELSX);
ydpi = ::GetDeviceCaps(dc, LOGPIXELSY);
::ReleaseDC(NULL, dc);
}
#endif
IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert!
return xdpi / 96.0f;
}
float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd)
{
HMONITOR monitor = ::MonitorFromWindow((HWND)hwnd, MONITOR_DEFAULTTONEAREST);
return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor);
}
//---------------------------------------------------------------------------------------------------------

View file

@ -1,37 +0,0 @@
// dear imgui: Platform Binding for Windows (standard windows API for 32 and 64 bits applications)
// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
// Implemented features:
// [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui)
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
// [X] Platform: Keyboard arrays indexed using VK_* Virtual Key Codes, e.g. ImGui::IsKeyPressed(VK_SPACE).
// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
#pragma once
#include "imgui.h" // IMGUI_IMPL_API
IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd);
IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown();
IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame();
// Configuration
// - Disable gamepad support or linking with xinput.lib
//#define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
//#define IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT
// Win32 message handler your application need to call.
// - Intentionally commented out in a '#if 0' block to avoid dragging dependencies on <windows.h> from this helper.
// - You should COPY the line below into your .cpp code to forward declare the function and then you can call it.
#if 0
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
#endif
// DPI-related helpers (optional)
// - Use to enable DPI awareness without having to create an application manifest.
// - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps.
// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc.
// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime,
// neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies.
IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness();
IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd); // HWND hwnd
IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); // HMONITOR monitor

View file

@ -14,6 +14,7 @@
# endif
# include <imgui.h>
# include <imgui_internal.h>
# include "imgui_impl_glfw.h"
struct PlatformGLFW final
@ -45,6 +46,7 @@ struct PlatformGLFW final
bool m_IsMinimized = false;
bool m_WasMinimized = false;
Renderer* m_Renderer = nullptr;
ImU32 m_LastEventId = 0;
};
std::unique_ptr<Platform> CreatePlatform(Application& application)
@ -97,9 +99,10 @@ bool PlatformGLFW::OpenMainWindow(const char* title, int width, int height)
initializer = &ImGui_ImplGlfw_InitForOpenGL;
# else
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
initializer = &ImGui_ImplGlfw_InitForNone;
initializer = &ImGui_ImplGlfw_InitForOther;
# endif
glfwWindowHint(GLFW_SCALE_TO_MONITOR, GL_TRUE);
glfwWindowHint(GLFW_SCALE_FRAMEBUFFER, GL_TRUE);
width = width < 0 ? 1440 : width;
height = height < 0 ? 800 : height;
@ -241,8 +244,32 @@ void PlatformGLFW::SetRenderer(Renderer* renderer)
void PlatformGLFW::NewFrame()
{
auto& io = ImGui::GetIO();
auto& ctx = *ImGui::GetCurrentContext();
ImGui_ImplGlfw_NewFrame();
auto inputEventCountAfterUpdate = ctx.InputEventsQueue.Size;
auto windowScale = GetWindowScale();
for (auto& event : ctx.InputEventsQueue)
{
if (event.EventId <= m_LastEventId)
continue;
m_LastEventId = event.EventId;
if (event.Type == ImGuiInputEventType_MousePos)
{
if (event.MousePos.PosX > -FLT_MAX && event.MousePos.PosY > -FLT_MAX)
{
event.MousePos.PosX *= windowScale;
event.MousePos.PosY *= windowScale;
}
}
}
if (m_WasMinimized)
{
ImGui::GetIO().DeltaTime = 0.1e-6f;
@ -279,7 +306,7 @@ void PlatformGLFW::UpdatePixelDensity()
float framebufferScale = scale;
# endif
SetWindowScale(windowScale); // this is how windows is scaled, not window content
SetWindowScale(1.0f / windowScale); // this is how windows is scaled, not window content
SetFramebufferScale(framebufferScale);
}

View file

@ -13,6 +13,7 @@
# include <string>
# include <imgui.h>
# include <imgui_internal.h>
# include "imgui_impl_win32.h"
# if defined(_UNICODE)
@ -53,7 +54,7 @@ struct PlatformWin32 final
void FinishFrame() override;
void Quit() override;
void SetDpiScale(float dpiScale);
//void SetDpiScale(float dpiScale);
LRESULT WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
@ -64,6 +65,7 @@ struct PlatformWin32 final
bool m_WasMinimized = false;
bool m_CanCloseResult = false;
Renderer* m_Renderer = nullptr;
ImU32 m_LastEventId = 0;
};
std::unique_ptr<Platform> CreatePlatform(Application& application)
@ -85,6 +87,8 @@ bool PlatformWin32::ApplicationStart(int argc, char** argv)
s_Instance = this;
ImGui_ImplWin32_EnableDpiAwareness();
auto winProc = [](HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) -> LRESULT
{
return s_Instance->WinProc(hWnd, msg, wParam, lParam);
@ -114,8 +118,6 @@ bool PlatformWin32::ApplicationStart(int argc, char** argv)
return false;
}
ImGui_ImplWin32_EnableDpiAwareness();
return true;
}
@ -135,26 +137,73 @@ bool PlatformWin32::OpenMainWindow(const char* title, int width, int height)
if (m_MainWindowHandle)
return false;
m_MainWindowHandle = CreateWindow(
const auto windowStyle = WS_OVERLAPPEDWINDOW;
const auto windowStyleEx = WS_EX_OVERLAPPEDWINDOW;
RECT rect;
rect.left = 0;
rect.top = 0;
rect.right = width;
rect.bottom = height;
AdjustWindowRectEx(&rect, windowStyle, false, windowStyleEx);
auto windowWidth = rect.right - rect.left;
auto windowHeight = rect.bottom - rect.top;
m_MainWindowHandle = CreateWindowEx(
WS_EX_OVERLAPPEDWINDOW,
m_WindowClass.lpszClassName,
Utf8ToNative(title).c_str(),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
width < 0 ? CW_USEDEFAULT : width,
height < 0 ? CW_USEDEFAULT : height,
width < 0 ? CW_USEDEFAULT : windowWidth,
height < 0 ? CW_USEDEFAULT : windowHeight,
nullptr, nullptr, m_WindowClass.hInstance, nullptr);
if (!m_MainWindowHandle)
return false;
# if RENDERER(IMGUI_OGL3)
if (!ImGui_ImplWin32_InitForOpenGL(m_MainWindowHandle))
# else
if (!ImGui_ImplWin32_Init(m_MainWindowHandle))
# endif
{
DestroyWindow(m_MainWindowHandle);
m_MainWindowHandle = nullptr;
return false;
}
SetDpiScale(ImGui_ImplWin32_GetDpiScaleForHwnd(m_MainWindowHandle));
const auto windowScale = ImGui_ImplWin32_GetDpiScaleForHwnd(m_MainWindowHandle);
RECT clientRect;
GetClientRect(m_MainWindowHandle, &clientRect);
POINT origin = { clientRect.left, clientRect.top };
ClientToScreen(m_MainWindowHandle, &origin);
// move rect by origin
clientRect.right += origin.x - clientRect.left;
clientRect.bottom += origin.y - clientRect.top;
clientRect.left = origin.x;
clientRect.top = origin.y;
if (width >= 0)
clientRect.right = static_cast<int>((clientRect.right - clientRect.left) * windowScale) + clientRect.left;
if (height >= 0)
clientRect.bottom = static_cast<int>((clientRect.bottom - clientRect.top) * windowScale) + clientRect.top;
RECT windowRect = clientRect;
AdjustWindowRectEx(&windowRect, windowStyle, false, windowStyleEx);
SetWindowPos(m_MainWindowHandle, nullptr,
windowRect.left, windowRect.top,
windowRect.right - windowRect.left,
windowRect.bottom - windowRect.top,
SWP_NOZORDER | SWP_NOACTIVATE);
SetWindowScale(1.0f / windowScale);
SetFramebufferScale(windowScale);
return true;
}
@ -236,7 +285,30 @@ void PlatformWin32::SetRenderer(Renderer* renderer)
void PlatformWin32::NewFrame()
{
auto& io = ImGui::GetIO();
auto& ctx = *ImGui::GetCurrentContext();
ImGui_ImplWin32_NewFrame();
auto inputEventCountAfterUpdate = ctx.InputEventsQueue.Size;
auto windowScale = GetWindowScale();
for (auto& event : ctx.InputEventsQueue)
{
if (event.EventId <= m_LastEventId)
continue;
m_LastEventId = event.EventId;
if (event.Type == ImGuiInputEventType_MousePos)
{
if (event.MousePos.PosX > -FLT_MAX && event.MousePos.PosY > -FLT_MAX)
{
event.MousePos.PosX *= windowScale;
event.MousePos.PosY *= windowScale;
}
}
}
if (m_WasMinimized)
{
@ -256,12 +328,6 @@ void PlatformWin32::Quit()
PostQuitMessage(0);
}
void PlatformWin32::SetDpiScale(float dpiScale)
{
SetWindowScale(dpiScale);
SetFramebufferScale(dpiScale);
}
LRESULT PlatformWin32::WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
@ -299,8 +365,21 @@ LRESULT PlatformWin32::WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam
break;
case WM_DPICHANGED:
SetDpiScale(ImGui_ImplWin32_GetDpiScaleForHwnd(hWnd));
{
RECT* const prcNewWindow = (RECT*)lParam;
SetWindowPos(hWnd,
NULL,
prcNewWindow ->left,
prcNewWindow ->top,
prcNewWindow->right - prcNewWindow->left,
prcNewWindow->bottom - prcNewWindow->top,
SWP_NOZORDER | SWP_NOACTIVATE);
const auto windowScale = ImGui_ImplWin32_GetDpiScaleForHwnd(hWnd);
SetWindowScale(1.0f / windowScale);
SetFramebufferScale(windowScale);
return 0;
}
case WM_DESTROY:
PostQuitMessage(0);

View file

@ -23,6 +23,9 @@ struct Renderer
virtual void Resize(int width, int height) = 0;
virtual void InvalidateResources() = 0;
virtual void UpdateResources() = 0;
virtual ImTextureID CreateTexture(const void* data, int width, int height) = 0;
virtual void DestroyTexture(ImTextureID texture) = 0;
virtual int GetTextureWidth(ImTextureID texture) = 0;

View file

@ -19,6 +19,14 @@
struct RendererDX11 final
: Renderer
{
struct Texture
{
ID3D11ShaderResourceView* View = nullptr;
int Width = 0;
int Height = 0;
ImVector<unsigned char> Data;
};
bool Create(Platform& platform) override;
void Destroy() override;
void NewFrame() override;
@ -26,6 +34,8 @@ struct RendererDX11 final
void Clear(const ImVec4& color) override;
void Present() override;
void Resize(int width, int height) override;
void InvalidateResources() override;
void UpdateResources() override;
ImTextureID CreateTexture(const void* data, int width, int height) override;
void DestroyTexture(ImTextureID texture) override;
@ -38,11 +48,16 @@ struct RendererDX11 final
void CreateRenderTarget();
void CleanupRenderTarget();
auto FindTexture(ImTextureID texture) -> Texture*;
bool UploadTexture(Texture* texture);
void ReleaseTexture(Texture* texture);
Platform* m_Platform = nullptr;
ID3D11Device* m_device = nullptr;
ID3D11DeviceContext* m_deviceContext = nullptr;
IDXGISwapChain* m_swapChain = nullptr;
ID3D11RenderTargetView* m_mainRenderTargetView = nullptr;
ImVector<Texture*> m_textures;
};
std::unique_ptr<Renderer> CreateRenderer()
@ -103,12 +118,21 @@ void RendererDX11::Present()
void RendererDX11::Resize(int width, int height)
{
ImGui_ImplDX11_InvalidateDeviceObjects();
CleanupRenderTarget();
m_swapChain->ResizeBuffers(0, (UINT)width, (UINT)height, DXGI_FORMAT_UNKNOWN, 0);
CreateRenderTarget();
}
void RendererDX11::InvalidateResources()
{
ImGui_ImplDX11_InvalidateDeviceObjects();
}
void RendererDX11::UpdateResources()
{
ImGui_ImplDX11_CreateDeviceObjects();
}
HRESULT RendererDX11::CreateDeviceD3D(HWND hWnd)
{
// Setup swap chain
@ -156,12 +180,15 @@ void RendererDX11::CreateRenderTarget()
m_swapChain->GetDesc(&sd);
// Create the render target
ID3D11Texture2D* pBackBuffer;
ID3D11Texture2D* pBackBuffer = nullptr;
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;
m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
if (pBackBuffer == nullptr)
return;
m_device->CreateRenderTargetView(pBackBuffer, &render_target_view_desc, &m_mainRenderTargetView);
m_deviceContext->OMSetRenderTargets(1, &m_mainRenderTargetView, nullptr);
pBackBuffer->Release();
@ -174,22 +201,120 @@ void RendererDX11::CleanupRenderTarget()
ImTextureID RendererDX11::CreateTexture(const void* data, int width, int height)
{
return ImGui_CreateTexture(data, width, height);
auto texture = IM_NEW(Texture);
texture->Width = width;
texture->Height = height;
texture->Data.resize(width * height * 4);
memcpy(texture->Data.Data, data, texture->Data.Size);
if (!UploadTexture(texture))
{
IM_DELETE(texture);
return nullptr;
}
m_textures.push_back(texture);
return static_cast<ImTextureID>(texture->View);
}
void RendererDX11::DestroyTexture(ImTextureID texture)
{
return ImGui_DestroyTexture(texture);
auto textureObject = FindTexture(texture);
if (!textureObject)
return;
m_textures.find_erase_unsorted(textureObject);
ReleaseTexture(textureObject);
IM_DELETE(textureObject);
}
int RendererDX11::GetTextureWidth(ImTextureID texture)
{
return ImGui_GetTextureWidth(texture);
if (auto textureObject = FindTexture(texture))
return textureObject->Width;
else
return 0;
}
int RendererDX11::GetTextureHeight(ImTextureID texture)
{
return ImGui_GetTextureHeight(texture);
if (auto textureObject = FindTexture(texture))
return textureObject->Height;
else
return 0;
}
auto RendererDX11::FindTexture(ImTextureID texture) -> Texture*
{
if (!texture)
return nullptr;
auto textureView = static_cast<decltype(Texture::View)>(texture);
for (auto& t : m_textures)
{
if (t->View == textureView)
return t;
}
return nullptr;
}
bool RendererDX11::UploadTexture(Texture* texture)
{
if (!m_device || !texture)
return false;
if (texture->View)
return true;
D3D11_TEXTURE2D_DESC desc = {};
desc.Width = texture->Width;
desc.Height = texture->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;
D3D11_SUBRESOURCE_DATA subResource = {};
subResource.pSysMem = texture->Data.Data;
subResource.SysMemPitch = desc.Width * 4;
subResource.SysMemSlicePitch = 0;
ID3D11Texture2D *pTexture = nullptr;
m_device->CreateTexture2D(&desc, &subResource, &pTexture);
if (!pTexture)
return false;
// Create texture view
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = desc.MipLevels;
srvDesc.Texture2D.MostDetailedMip = 0;
m_device->CreateShaderResourceView(pTexture, &srvDesc, &texture->View);
pTexture->Release();
return true;
}
void RendererDX11::ReleaseTexture(Texture* texture)
{
if (texture && texture->View)
{
texture->View->Release();
texture->View = nullptr;
}
}
# endif // RENDERER(IMGUI_DX11)

View file

@ -32,8 +32,10 @@ using namespace gl;
# include <glbinding/glbinding.h>// Initialize with glbinding::initialize()
# include <glbinding/gl/gl.h>
using namespace gl;
# else
# elif defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
# include IMGUI_IMPL_OPENGL_LOADER_CUSTOM
# else
# include "imgui_impl_opengl3_loader.h"
# endif
struct ImTexture
@ -53,6 +55,8 @@ struct RendererOpenGL3 final
void Clear(const ImVec4& color) override;
void Present() override;
void Resize(int width, int height) override;
void InvalidateResources() override;
void UpdateResources() override;
ImVector<ImTexture>::iterator FindTexture(ImTextureID texture);
ImTextureID CreateTexture(const void* data, int width, int height) override;
@ -145,6 +149,16 @@ void RendererOpenGL3::Resize(int width, int height)
glViewport(0, 0, width, height);
}
void RendererOpenGL3::InvalidateResources()
{
ImGui_ImplOpenGL3_DestroyFontsTexture();
}
void RendererOpenGL3::UpdateResources()
{
ImGui_ImplOpenGL3_CreateFontsTexture();
}
ImTextureID RendererOpenGL3::CreateTexture(const void* data, int width, int height)
{
m_Textures.resize(m_Textures.size() + 1);

View file

@ -153,8 +153,8 @@ struct Example:
// visual feedback by changing link thickness and color.
}
}
ed::EndCreate(); // Wraps up object creation action handling.
}
ed::EndCreate(); // Wraps up object creation action handling.
// Handle deletion action
@ -181,9 +181,8 @@ struct Example:
// You may reject link deletion by calling:
// ed::RejectDeletedItem();
}
ed::EndDelete(); // Wrap up deletion action
}
ed::EndDelete(); // Wrap up deletion action
// End of interaction with editor.

View file

@ -878,7 +878,7 @@ struct Example:
for (int i = 0; i < linkCount; ++i) ImGui::Text("Link (%p)", selectedLinks[i].AsPointer());
ImGui::Unindent();
if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Z)))
if (ImGui::IsKeyPressed(ImGuiKey_Z))
for (auto& link : m_Links)
ed::Flow(link.ID);
@ -1108,11 +1108,7 @@ struct Example:
ed::PushStyleVar(ed::StyleVar_PinArrowSize, 10.0f);
ed::PushStyleVar(ed::StyleVar_PinArrowWidth, 10.0f);
#if IMGUI_VERSION_NUM > 18101
ed::PushStyleVar(ed::StyleVar_PinCorners, ImDrawFlags_RoundCornersBottom);
#else
ed::PushStyleVar(ed::StyleVar_PinCorners, 12);
#endif
ed::BeginPin(pin.ID, ed::PinKind::Input);
ed::PinPivotRect(inputsRect.GetTL(), inputsRect.GetBR());
ed::PinRect(inputsRect.GetTL(), inputsRect.GetBR());
@ -1154,11 +1150,7 @@ struct Example:
ImGui::Spring(1, 0);
outputsRect = ImGui_GetItemRect();
#if IMGUI_VERSION_NUM > 18101
ed::PushStyleVar(ed::StyleVar_PinCorners, ImDrawFlags_RoundCornersTop);
#else
ed::PushStyleVar(ed::StyleVar_PinCorners, 3);
#endif
ed::BeginPin(pin.ID, ed::PinKind::Output);
ed::PinPivotRect(outputsRect.GetTL(), outputsRect.GetBR());
ed::PinRect(outputsRect.GetTL(), outputsRect.GetBR());
@ -1193,13 +1185,8 @@ struct Example:
// drawList->PathStroke(col, true, thickness);
//};
#if IMGUI_VERSION_NUM > 18101
const auto topRoundCornersFlags = ImDrawFlags_RoundCornersTop;
const auto bottomRoundCornersFlags = ImDrawFlags_RoundCornersBottom;
#else
const auto topRoundCornersFlags = 1 | 2;
const auto bottomRoundCornersFlags = 4 | 8;
#endif
drawList->AddRectFilled(inputsRect.GetTL() + ImVec2(0, 1), inputsRect.GetBR(),
IM_COL32((int)(255 * pinBackground.x), (int)(255 * pinBackground.y), (int)(255 * pinBackground.z), inputAlpha), 4.0f, bottomRoundCornersFlags);
@ -1263,11 +1250,7 @@ struct Example:
inputsRect.Min.y -= padding;
inputsRect.Max.y -= padding;
#if IMGUI_VERSION_NUM > 18101
const auto allRoundCornersFlags = ImDrawFlags_RoundCornersAll;
#else
const auto allRoundCornersFlags = 15;
#endif
//ed::PushStyleVar(ed::StyleVar_PinArrowSize, 10.0f);
//ed::PushStyleVar(ed::StyleVar_PinArrowWidth, 10.0f);
ed::PushStyleVar(ed::StyleVar_PinCorners, allRoundCornersFlags);
@ -1324,13 +1307,8 @@ struct Example:
outputsRect.Min.y += padding;
outputsRect.Max.y += padding;
#if IMGUI_VERSION_NUM > 18101
const auto allRoundCornersFlags = ImDrawFlags_RoundCornersAll;
const auto topRoundCornersFlags = ImDrawFlags_RoundCornersTop;
#else
const auto allRoundCornersFlags = 15;
const auto topRoundCornersFlags = 3;
#endif
ed::PushStyleVar(ed::StyleVar_PinCorners, topRoundCornersFlags);
ed::BeginPin(pin.ID, ed::PinKind::Output);
@ -1543,12 +1521,12 @@ struct Example:
ed::Resume();
}
}
ed::EndCreate();
}
else
newLinkPin = nullptr;
ed::EndCreate();
if (ed::BeginDelete())
{
ed::NodeId nodeId = 0;
@ -1572,8 +1550,9 @@ struct Example:
m_Links.erase(id);
}
}
ed::EndDelete();
}
ed::EndDelete();
}
ImGui::SetCursorScreenPos(cursorTopLeft);

View file

@ -66,11 +66,7 @@ void util::BlueprintNodeBuilder::End()
HeaderMin - ImVec2(8 - halfBorderWidth, 4 - halfBorderWidth),
HeaderMax + ImVec2(8 - halfBorderWidth, 0),
ImVec2(0.0f, 0.0f), uv,
#if IMGUI_VERSION_NUM > 18101
headerColor, GetStyle().NodeRounding, ImDrawFlags_RoundCornersTop);
#else
headerColor, GetStyle().NodeRounding, 1 | 2);
#endif
if (ContentMin.y > HeaderMax.y)
{

View file

@ -112,11 +112,7 @@ void ax::Drawing::DrawIcon(ImDrawList* drawList, const ImVec2& a, const ImVec2&
const auto p0 = rect_center - ImVec2(r, r);
const auto p1 = rect_center + ImVec2(r, r);
#if IMGUI_VERSION_NUM > 18101
drawList->AddRectFilled(p0, p1, color, 0, ImDrawFlags_RoundCornersAll);
#else
drawList->AddRectFilled(p0, p1, color, 0, 15);
#endif
}
else
{
@ -126,18 +122,10 @@ void ax::Drawing::DrawIcon(ImDrawList* drawList, const ImVec2& a, const ImVec2&
if (innerColor & 0xFF000000)
{
#if IMGUI_VERSION_NUM > 18101
drawList->AddRectFilled(p0, p1, innerColor, 0, ImDrawFlags_RoundCornersAll);
#else
drawList->AddRectFilled(p0, p1, innerColor, 0, 15);
#endif
}
#if IMGUI_VERSION_NUM > 18101
drawList->AddRect(p0, p1, color, 0, ImDrawFlags_RoundCornersAll, 2.0f * outline_scale);
#else
drawList->AddRect(p0, p1, color, 0, 15, 2.0f * outline_scale);
#endif
}
}
@ -180,11 +168,7 @@ void ax::Drawing::DrawIcon(ImDrawList* drawList, const ImVec2& a, const ImVec2&
const auto p0 = rect_center - ImVec2(r, r);
const auto p1 = rect_center + ImVec2(r, r);
#if IMGUI_VERSION_NUM > 18101
drawList->AddRectFilled(p0, p1, color, cr, ImDrawFlags_RoundCornersAll);
#else
drawList->AddRectFilled(p0, p1, color, cr, 15);
#endif
}
else
{
@ -195,18 +179,10 @@ void ax::Drawing::DrawIcon(ImDrawList* drawList, const ImVec2& a, const ImVec2&
if (innerColor & 0xFF000000)
{
#if IMGUI_VERSION_NUM > 18101
drawList->AddRectFilled(p0, p1, innerColor, cr, ImDrawFlags_RoundCornersAll);
#else
drawList->AddRectFilled(p0, p1, innerColor, cr, 15);
#endif
}
#if IMGUI_VERSION_NUM > 18101
drawList->AddRect(p0, p1, color, cr, ImDrawFlags_RoundCornersAll, 2.0f * outline_scale);
#else
drawList->AddRect(p0, p1, color, cr, 15, 2.0f * outline_scale);
#endif
}
}
else if (type == IconType::Diamond)

View file

@ -188,7 +188,27 @@ struct Example:
canvas.SetView(drawStartPoint + ImGui::GetMouseDragDelta(1, 0.0f) * viewScale, viewScale);
}
else if (isDragging)
{
isDragging = false;
}
else if (!isDragging && ImGui::IsItemHovered() && io.MouseWheel)
{
auto mousePos = io.MousePos;
// apply new view scale
auto oldView = canvas.View();
auto newViewScale = viewScale * powf(1.1f, io.MouseWheel);
canvas.SetView(viewOrigin, newViewScale);
auto newView = canvas.View();
// calculate origin offset to keep mouse position fixed
auto screenPosition = canvas.FromLocal(mousePos, oldView);
auto canvasPosition = canvas.ToLocal(screenPosition, newView);
auto originOffset = (canvasPosition - mousePos) * newViewScale;
// apply new view
canvas.SetView(viewOrigin + originOffset, newViewScale);
}
viewRect = canvas.ViewRect();

View file

@ -0,0 +1,37 @@
if (TARGET glfw)
return()
endif()
include(FetchContent)
FetchContent_Declare(
glfw
GIT_REPOSITORY https://github.com/glfw/glfw
)
FetchContent_GetProperties(glfw)
if(NOT glfw_POPULATED)
FetchContent_Populate(glfw)
set(GLFW_BUILD_EXAMPLES OFF CACHE INTERNAL "Build the GLFW example programs")
set(GLFW_BUILD_TESTS OFF CACHE INTERNAL "Build the GLFW test programs")
set(GLFW_BUILD_DOCS OFF CACHE INTERNAL "Build the GLFW documentation")
set(GLFW_INSTALL OFF CACHE INTERNAL "Generate installation target")
add_subdirectory(${glfw_SOURCE_DIR} ${glfw_BINARY_DIR})
endif()
FetchContent_MakeAvailable(glfw)
set_target_properties(
glfw
update_mappings
PROPERTIES
FOLDER "external"
)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
glfw
DEFAULT_MSG
)

View file

@ -0,0 +1,83 @@
if (NOT TARGET imgui)
include(FetchContent)
FetchContent_Declare(
imgui
#GIT_REPOSITORY https://github.com/ocornut/imgui.git
#GIT_TAG 12a3c77c2f4671813c2a09197234d5672f8ab5f3
GIT_REPOSITORY https://github.com/thedmd/imgui.git
GIT_TAG layouts
)
FetchContent_MakeAvailable(imgui)
file(GLOB SOURCES CONFIGURE_DEPENDS "${imgui_SOURCE_DIR}/*.cpp" "${imgui_SOURCE_DIR}/*.h")
source_group(TREE ${imgui_SOURCE_DIR} FILES ${SOURCES})
set(imgui_natvis_path "${imgui_SOURCE_DIR}/misc/debuggers/imgui.natvis")
add_library(imgui STATIC ${SOURCES} ${imgui_natvis_path})
target_include_directories(imgui PUBLIC
${imgui_SOURCE_DIR}
)
target_compile_definitions(imgui PUBLIC
IMGUI_DISABLE_OBSOLETE_FUNCTIONS
IMGUI_DISABLE_OBSOLETE_KEYIO
)
set_target_properties(
imgui
PROPERTIES
FOLDER "external"
)
endif()
foreach(component ${imgui_FIND_COMPONENTS})
if (TARGET imgui_${component})
continue()
endif()
file(GLOB COMPONENT_SOURCES CONFIGURE_DEPENDS "${imgui_SOURCE_DIR}/backends/imgui_impl_${component}*")
source_group(TREE ${imgui_SOURCE_DIR}/backends FILES ${COMPONENT_SOURCES})
add_library(imgui_${component} STATIC ${COMPONENT_SOURCES})
target_include_directories(imgui_${component} PUBLIC
${imgui_SOURCE_DIR}/backends
)
target_link_libraries(imgui_${component} PUBLIC imgui)
if (component MATCHES "dx11")
target_link_libraries(imgui_${component} PUBLIC d3d11)
elseif (component MATCHES "opengl*")
find_package(OpenGL REQUIRED COMPONENTS OpenGL)
target_link_libraries(imgui_${component} PUBLIC OpenGL::GL)
elseif(component STREQUAL "glfw")
find_package(glfw REQUIRED)
target_link_libraries(imgui_${component} PUBLIC glfw)
endif()
add_library(imgui::${component} ALIAS imgui_${component})
set_target_properties(
imgui_${component}
PROPERTIES
FOLDER "external"
)
endforeach()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
imgui
DEFAULT_MSG
)

View file

@ -12,6 +12,7 @@ find_package(imgui REQUIRED)
set(_imgui_node_editor_Sources
${IMGUI_NODE_EDITOR_ROOT_DIR}/crude_json.cpp
${IMGUI_NODE_EDITOR_ROOT_DIR}/crude_json.h
${IMGUI_NODE_EDITOR_ROOT_DIR}/misc/crude_json.natvis
${IMGUI_NODE_EDITOR_ROOT_DIR}/imgui_bezier_math.h
${IMGUI_NODE_EDITOR_ROOT_DIR}/imgui_bezier_math.inl
${IMGUI_NODE_EDITOR_ROOT_DIR}/imgui_canvas.cpp
@ -44,6 +45,5 @@ include(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(
imgui_node_editor
REQUIRED_VARS
IMGUI_NODE_EDITOR_ROOT_DIR
DEFAULT_MSG
)

View file

@ -0,0 +1,60 @@
if (NOT TARGET stb)
include(FetchContent)
FetchContent_Declare(
stb
GIT_REPOSITORY https://github.com/nothings/stb.git
)
FetchContent_MakeAvailable(stb)
add_library(stb INTERFACE)
set_target_properties(
stb
PROPERTIES
FOLDER "external"
)
endif()
foreach(component ${stb_FIND_COMPONENTS})
if (TARGET stb_${component})
continue()
endif()
set(HEADER "${stb_SOURCE_DIR}/stb_${component}.h")
set(SOURCE "${stb_BINARY_DIR}/stb_${component}_generated.c")
string(TOUPPER ${component} componentUppercase)
file(GENERATE
OUTPUT "${SOURCE}"
CONTENT "#define STB_${componentUppercase}_IMPLEMENTATION\n#include \"${HEADER}\""
)
source_group("" FILES "${HEADER}" "${SOURCE}")
add_library(stb_${component} STATIC "${SOURCE}" "${HEADER}")
target_include_directories(stb_${component} PUBLIC
${stb_SOURCE_DIR}
)
add_library(stb::${component} ALIAS stb_${component})
set_target_properties(
stb_${component}
PROPERTIES
FOLDER "external"
)
endforeach()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
stb
DEFAULT_MSG
)

View file

@ -128,11 +128,19 @@ struct Example:
// Arrow buttons with Repeater
static int counter = 0;
float spacing = ImGui::GetStyle().ItemInnerSpacing.x;
# if IMGUI_VERSION_NUM >= 19094
ImGui::PushItemFlag(ImGuiItemFlags_ButtonRepeat, true);
# else
ImGui::PushButtonRepeat(true);
# endif
if (ImGui::ArrowButton("##left", ImGuiDir_Left)) { counter--; }
ImGui::SameLine(0.0f, spacing);
if (ImGui::ArrowButton("##right", ImGuiDir_Right)) { counter++; }
# if IMGUI_VERSION_NUM >= 19094
ImGui::PopItemFlag();
# else
ImGui::PopButtonRepeat();
# endif
ImGui::SameLine();
ImGui::Text("%d", counter);
@ -384,8 +392,8 @@ struct Example:
}
}
}
ed::EndCreate();
}
ed::EndCreate();
// Handle deletion action ---------------------------------------------------------------------------
if (ed::BeginDelete())
@ -405,8 +413,8 @@ struct Example:
}
}
}
ed::EndDelete();
}
ed::EndDelete();
ed::End();
ed::SetCurrentEditor(nullptr);

View file

@ -1,74 +0,0 @@
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) Microsoft Corporation. All Rights Reserved.
//
// File: d3dx11.h
// Content: D3DX11 utility library
//
//////////////////////////////////////////////////////////////////////////////
#ifdef __D3DX11_INTERNAL__
#error Incorrect D3DX11 header used
#endif
#ifndef __D3DX11_H__
#define __D3DX11_H__
// Defines
#include <limits.h>
#include <float.h>
#ifdef ALLOW_THROWING_NEW
#include <new>
#endif
#define D3DX11_DEFAULT ((UINT) -1)
#define D3DX11_FROM_FILE ((UINT) -3)
#define DXGI_FORMAT_FROM_FILE ((DXGI_FORMAT) -3)
#ifndef D3DX11INLINE
#ifdef _MSC_VER
#if (_MSC_VER >= 1200)
#define D3DX11INLINE __forceinline
#else
#define D3DX11INLINE __inline
#endif
#else
#ifdef __cplusplus
#define D3DX11INLINE inline
#else
#define D3DX11INLINE
#endif
#endif
#endif
// Includes
#include "d3d11.h"
#include "d3dx11.h"
#include "d3dx11core.h"
#include "d3dx11tex.h"
#include "d3dx11async.h"
// Errors
#define _FACDD 0x876
#define MAKE_DDHRESULT( code ) MAKE_HRESULT( 1, _FACDD, code )
enum _D3DX11_ERR {
D3DX11_ERR_CANNOT_MODIFY_INDEX_BUFFER = MAKE_DDHRESULT(2900),
D3DX11_ERR_INVALID_MESH = MAKE_DDHRESULT(2901),
D3DX11_ERR_CANNOT_ATTR_SORT = MAKE_DDHRESULT(2902),
D3DX11_ERR_SKINNING_NOT_SUPPORTED = MAKE_DDHRESULT(2903),
D3DX11_ERR_TOO_MANY_INFLUENCES = MAKE_DDHRESULT(2904),
D3DX11_ERR_INVALID_DATA = MAKE_DDHRESULT(2905),
D3DX11_ERR_LOADED_MESH_HAS_NO_DATA = MAKE_DDHRESULT(2906),
D3DX11_ERR_DUPLICATE_NAMED_FRAGMENT = MAKE_DDHRESULT(2907),
D3DX11_ERR_CANNOT_REMOVE_LAST_ITEM = MAKE_DDHRESULT(2908),
};
#endif //__D3DX11_H__

View file

@ -1,164 +0,0 @@
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// File: D3DX11Async.h
// Content: D3DX11 Asynchronous Shader loaders / compilers
//
//////////////////////////////////////////////////////////////////////////////
#ifndef __D3DX11ASYNC_H__
#define __D3DX11ASYNC_H__
#include "d3dx11.h"
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
//----------------------------------------------------------------------------
// D3DX11Compile:
// ------------------
// Compiles an effect or shader.
//
// Parameters:
// pSrcFile
// Source file name.
// hSrcModule
// Module handle. if NULL, current module will be used.
// pSrcResource
// Resource name in module.
// pSrcData
// Pointer to source code.
// SrcDataLen
// Size of source code, in bytes.
// pDefines
// Optional NULL-terminated array of preprocessor macro definitions.
// pInclude
// Optional interface pointer to use for handling #include directives.
// If this parameter is NULL, #includes will be honored when compiling
// from file, and will error when compiling from resource or memory.
// pFunctionName
// Name of the entrypoint function where execution should begin.
// pProfile
// Instruction set to be used when generating code. Currently supported
// profiles are "vs_1_1", "vs_2_0", "vs_2_a", "vs_2_sw", "vs_3_0",
// "vs_3_sw", "vs_4_0", "vs_4_1",
// "ps_2_0", "ps_2_a", "ps_2_b", "ps_2_sw", "ps_3_0",
// "ps_3_sw", "ps_4_0", "ps_4_1",
// "gs_4_0", "gs_4_1",
// "tx_1_0",
// "fx_4_0", "fx_4_1"
// Note that this entrypoint does not compile fx_2_0 targets, for that
// you need to use the D3DX9 function.
// Flags1
// See D3D10_SHADER_xxx flags.
// Flags2
// See D3D10_EFFECT_xxx flags.
// ppShader
// Returns a buffer containing the created shader. This buffer contains
// the compiled shader code, as well as any embedded debug and symbol
// table info. (See D3D10GetShaderConstantTable)
// ppErrorMsgs
// Returns a buffer containing a listing of errors and warnings that were
// encountered during the compile. If you are running in a debugger,
// these are the same messages you will see in your debug output.
// pHResult
// Pointer to a memory location to receive the return value upon completion.
// Maybe NULL if not needed.
// If pPump != NULL, pHResult must be a valid memory location until the
// the asynchronous execution completes.
//----------------------------------------------------------------------------
HRESULT WINAPI D3DX11CompileFromFileA(LPCSTR pSrcFile,CONST D3D10_SHADER_MACRO* pDefines, LPD3D10INCLUDE pInclude,
LPCSTR pFunctionName, LPCSTR pProfile, UINT Flags1, UINT Flags2, ID3DX11ThreadPump* pPump, ID3D10Blob** ppShader, ID3D10Blob** ppErrorMsgs, HRESULT* pHResult);
HRESULT WINAPI D3DX11CompileFromFileW(LPCWSTR pSrcFile, CONST D3D10_SHADER_MACRO* pDefines, LPD3D10INCLUDE pInclude,
LPCSTR pFunctionName, LPCSTR pProfile, UINT Flags1, UINT Flags2, ID3DX11ThreadPump* pPump, ID3D10Blob** ppShader, ID3D10Blob** ppErrorMsgs, HRESULT* pHResult);
#ifdef UNICODE
#define D3DX11CompileFromFile D3DX11CompileFromFileW
#else
#define D3DX11CompileFromFile D3DX11CompileFromFileA
#endif
HRESULT WINAPI D3DX11CompileFromResourceA(HMODULE hSrcModule, LPCSTR pSrcResource, LPCSTR pSrcFileName, CONST D3D10_SHADER_MACRO* pDefines,
LPD3D10INCLUDE pInclude, LPCSTR pFunctionName, LPCSTR pProfile, UINT Flags1, UINT Flags2, ID3DX11ThreadPump* pPump, ID3D10Blob** ppShader, ID3D10Blob** ppErrorMsgs, HRESULT* pHResult);
HRESULT WINAPI D3DX11CompileFromResourceW(HMODULE hSrcModule, LPCWSTR pSrcResource, LPCWSTR pSrcFileName, CONST D3D10_SHADER_MACRO* pDefines,
LPD3D10INCLUDE pInclude, LPCSTR pFunctionName, LPCSTR pProfile, UINT Flags1, UINT Flags2, ID3DX11ThreadPump* pPump, ID3D10Blob** ppShader, ID3D10Blob** ppErrorMsgs, HRESULT* pHResult);
#ifdef UNICODE
#define D3DX11CompileFromResource D3DX11CompileFromResourceW
#else
#define D3DX11CompileFromResource D3DX11CompileFromResourceA
#endif
HRESULT WINAPI D3DX11CompileFromMemory(LPCSTR pSrcData, SIZE_T SrcDataLen, LPCSTR pFileName, CONST D3D10_SHADER_MACRO* pDefines, LPD3D10INCLUDE pInclude,
LPCSTR pFunctionName, LPCSTR pProfile, UINT Flags1, UINT Flags2, ID3DX11ThreadPump* pPump, ID3D10Blob** ppShader, ID3D10Blob** ppErrorMsgs, HRESULT* pHResult);
HRESULT WINAPI D3DX11PreprocessShaderFromFileA(LPCSTR pFileName, CONST D3D10_SHADER_MACRO* pDefines,
LPD3D10INCLUDE pInclude, ID3DX11ThreadPump *pPump, ID3D10Blob** ppShaderText, ID3D10Blob** ppErrorMsgs, HRESULT* pHResult);
HRESULT WINAPI D3DX11PreprocessShaderFromFileW(LPCWSTR pFileName, CONST D3D10_SHADER_MACRO* pDefines,
LPD3D10INCLUDE pInclude, ID3DX11ThreadPump *pPump, ID3D10Blob** ppShaderText, ID3D10Blob** ppErrorMsgs, HRESULT* pHResult);
HRESULT WINAPI D3DX11PreprocessShaderFromMemory(LPCSTR pSrcData, SIZE_T SrcDataSize, LPCSTR pFileName, CONST D3D10_SHADER_MACRO* pDefines,
LPD3D10INCLUDE pInclude, ID3DX11ThreadPump *pPump, ID3D10Blob** ppShaderText, ID3D10Blob** ppErrorMsgs, HRESULT* pHResult);
HRESULT WINAPI D3DX11PreprocessShaderFromResourceA(HMODULE hModule, LPCSTR pResourceName, LPCSTR pSrcFileName, CONST D3D10_SHADER_MACRO* pDefines,
LPD3D10INCLUDE pInclude, ID3DX11ThreadPump *pPump, ID3D10Blob** ppShaderText, ID3D10Blob** ppErrorMsgs, HRESULT* pHResult);
HRESULT WINAPI D3DX11PreprocessShaderFromResourceW(HMODULE hModule, LPCWSTR pResourceName, LPCWSTR pSrcFileName, CONST D3D10_SHADER_MACRO* pDefines,
LPD3D10INCLUDE pInclude, ID3DX11ThreadPump *pPump, ID3D10Blob** ppShaderText, ID3D10Blob** ppErrorMsgs, HRESULT* pHResult);
#ifdef UNICODE
#define D3DX11PreprocessShaderFromFile D3DX11PreprocessShaderFromFileW
#define D3DX11PreprocessShaderFromResource D3DX11PreprocessShaderFromResourceW
#else
#define D3DX11PreprocessShaderFromFile D3DX11PreprocessShaderFromFileA
#define D3DX11PreprocessShaderFromResource D3DX11PreprocessShaderFromResourceA
#endif
//----------------------------------------------------------------------------
// Async processors
//----------------------------------------------------------------------------
HRESULT WINAPI D3DX11CreateAsyncCompilerProcessor(LPCSTR pFileName, CONST D3D10_SHADER_MACRO* pDefines, LPD3D10INCLUDE pInclude,
LPCSTR pFunctionName, LPCSTR pProfile, UINT Flags1, UINT Flags2,
ID3D10Blob **ppCompiledShader, ID3D10Blob **ppErrorBuffer, ID3DX11DataProcessor **ppProcessor);
HRESULT WINAPI D3DX11CreateAsyncShaderPreprocessProcessor(LPCSTR pFileName, CONST D3D10_SHADER_MACRO* pDefines, LPD3D10INCLUDE pInclude,
ID3D10Blob** ppShaderText, ID3D10Blob **ppErrorBuffer, ID3DX11DataProcessor **ppProcessor);
//----------------------------------------------------------------------------
// D3DX11 Asynchronous texture I/O (advanced mode)
//----------------------------------------------------------------------------
HRESULT WINAPI D3DX11CreateAsyncFileLoaderW(LPCWSTR pFileName, ID3DX11DataLoader **ppDataLoader);
HRESULT WINAPI D3DX11CreateAsyncFileLoaderA(LPCSTR pFileName, ID3DX11DataLoader **ppDataLoader);
HRESULT WINAPI D3DX11CreateAsyncMemoryLoader(LPCVOID pData, SIZE_T cbData, ID3DX11DataLoader **ppDataLoader);
HRESULT WINAPI D3DX11CreateAsyncResourceLoaderW(HMODULE hSrcModule, LPCWSTR pSrcResource, ID3DX11DataLoader **ppDataLoader);
HRESULT WINAPI D3DX11CreateAsyncResourceLoaderA(HMODULE hSrcModule, LPCSTR pSrcResource, ID3DX11DataLoader **ppDataLoader);
#ifdef UNICODE
#define D3DX11CreateAsyncFileLoader D3DX11CreateAsyncFileLoaderW
#define D3DX11CreateAsyncResourceLoader D3DX11CreateAsyncResourceLoaderW
#else
#define D3DX11CreateAsyncFileLoader D3DX11CreateAsyncFileLoaderA
#define D3DX11CreateAsyncResourceLoader D3DX11CreateAsyncResourceLoaderA
#endif
HRESULT WINAPI D3DX11CreateAsyncTextureProcessor(ID3D11Device *pDevice, D3DX11_IMAGE_LOAD_INFO *pLoadInfo, ID3DX11DataProcessor **ppDataProcessor);
HRESULT WINAPI D3DX11CreateAsyncTextureInfoProcessor(D3DX11_IMAGE_INFO *pImageInfo, ID3DX11DataProcessor **ppDataProcessor);
HRESULT WINAPI D3DX11CreateAsyncShaderResourceViewProcessor(ID3D11Device *pDevice, D3DX11_IMAGE_LOAD_INFO *pLoadInfo, ID3DX11DataProcessor **ppDataProcessor);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif //__D3DX11ASYNC_H__

View file

@ -1,128 +0,0 @@
///////////////////////////////////////////////////////////////////////////
//
// Copyright (C) Microsoft Corporation. All Rights Reserved.
//
// File: d3dx11core.h
// Content: D3DX11 core types and functions
//
///////////////////////////////////////////////////////////////////////////
#include "d3dx11.h"
#ifndef __D3DX11CORE_H__
#define __D3DX11CORE_H__
// Current name of the DLL shipped in the same SDK as this header.
#define D3DX11_DLL_W L"d3dx11_43.dll"
#define D3DX11_DLL_A "d3dx11_43.dll"
#ifdef UNICODE
#define D3DX11_DLL D3DX11_DLL_W
#else
#define D3DX11_DLL D3DX11_DLL_A
#endif
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
///////////////////////////////////////////////////////////////////////////
// D3DX11_SDK_VERSION:
// -----------------
// This identifier is passed to D3DX11CheckVersion in order to ensure that an
// application was built against the correct header files and lib files.
// This number is incremented whenever a header (or other) change would
// require applications to be rebuilt. If the version doesn't match,
// D3DX11CreateVersion will return FALSE. (The number itself has no meaning.)
///////////////////////////////////////////////////////////////////////////
#define D3DX11_SDK_VERSION 43
#ifdef D3D_DIAG_DLL
BOOL WINAPI D3DX11DebugMute(BOOL Mute);
#endif
HRESULT WINAPI D3DX11CheckVersion(UINT D3DSdkVersion, UINT D3DX11SdkVersion);
#ifdef __cplusplus
}
#endif //__cplusplus
//////////////////////////////////////////////////////////////////////////////
// ID3DX11ThreadPump:
//////////////////////////////////////////////////////////////////////////////
#undef INTERFACE
#define INTERFACE ID3DX11DataLoader
DECLARE_INTERFACE(ID3DX11DataLoader)
{
STDMETHOD(Load)(THIS) PURE;
STDMETHOD(Decompress)(THIS_ void **ppData, SIZE_T *pcBytes) PURE;
STDMETHOD(Destroy)(THIS) PURE;
};
#undef INTERFACE
#define INTERFACE ID3DX11DataProcessor
DECLARE_INTERFACE(ID3DX11DataProcessor)
{
STDMETHOD(Process)(THIS_ void *pData, SIZE_T cBytes) PURE;
STDMETHOD(CreateDeviceObject)(THIS_ void **ppDataObject) PURE;
STDMETHOD(Destroy)(THIS) PURE;
};
// {C93FECFA-6967-478a-ABBC-402D90621FCB}
DEFINE_GUID(IID_ID3DX11ThreadPump,
0xc93fecfa, 0x6967, 0x478a, 0xab, 0xbc, 0x40, 0x2d, 0x90, 0x62, 0x1f, 0xcb);
#undef INTERFACE
#define INTERFACE ID3DX11ThreadPump
DECLARE_INTERFACE_(ID3DX11ThreadPump, IUnknown)
{
// IUnknown
STDMETHOD(QueryInterface)(THIS_ REFIID iid, LPVOID *ppv) PURE;
STDMETHOD_(ULONG, AddRef)(THIS) PURE;
STDMETHOD_(ULONG, Release)(THIS) PURE;
// ID3DX11ThreadPump
STDMETHOD(AddWorkItem)(THIS_ ID3DX11DataLoader *pDataLoader, ID3DX11DataProcessor *pDataProcessor, HRESULT *pHResult, void **ppDeviceObject) PURE;
STDMETHOD_(UINT, GetWorkItemCount)(THIS) PURE;
STDMETHOD(WaitForAllItems)(THIS) PURE;
STDMETHOD(ProcessDeviceWorkItems)(THIS_ UINT iWorkItemCount);
STDMETHOD(PurgeAllItems)(THIS) PURE;
STDMETHOD(GetQueueStatus)(THIS_ UINT *pIoQueue, UINT *pProcessQueue, UINT *pDeviceQueue) PURE;
};
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
HRESULT WINAPI D3DX11CreateThreadPump(UINT cIoThreads, UINT cProcThreads, ID3DX11ThreadPump **ppThreadPump);
HRESULT WINAPI D3DX11UnsetAllDeviceObjects(ID3D11DeviceContext *pContext);
#ifdef __cplusplus
}
#endif //__cplusplus
///////////////////////////////////////////////////////////////////////////
#define _FACD3D 0x876
#define MAKE_D3DHRESULT( code ) MAKE_HRESULT( 1, _FACD3D, code )
#define MAKE_D3DSTATUS( code ) MAKE_HRESULT( 0, _FACD3D, code )
#define D3DERR_INVALIDCALL MAKE_D3DHRESULT(2156)
#define D3DERR_WASSTILLDRAWING MAKE_D3DHRESULT(540)
#endif //__D3DX11CORE_H__

View file

@ -1,772 +0,0 @@
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) Microsoft Corporation. All Rights Reserved.
//
// File: d3dx11tex.h
// Content: D3DX11 texturing APIs
//
//////////////////////////////////////////////////////////////////////////////
#include "d3dx11.h"
#ifndef __D3DX11TEX_H__
#define __D3DX11TEX_H__
//----------------------------------------------------------------------------
// D3DX11_FILTER flags:
// ------------------
//
// A valid filter must contain one of these values:
//
// D3DX11_FILTER_NONE
// No scaling or filtering will take place. Pixels outside the bounds
// of the source image are assumed to be transparent black.
// D3DX11_FILTER_POINT
// Each destination pixel is computed by sampling the nearest pixel
// from the source image.
// D3DX11_FILTER_LINEAR
// Each destination pixel is computed by linearly interpolating between
// the nearest pixels in the source image. This filter works best
// when the scale on each axis is less than 2.
// D3DX11_FILTER_TRIANGLE
// Every pixel in the source image contributes equally to the
// destination image. This is the slowest of all the filters.
// D3DX11_FILTER_BOX
// Each pixel is computed by averaging a 2x2(x2) box pixels from
// the source image. Only works when the dimensions of the
// destination are half those of the source. (as with mip maps)
//
// And can be OR'd with any of these optional flags:
//
// D3DX11_FILTER_MIRROR_U
// Indicates that pixels off the edge of the texture on the U-axis
// should be mirrored, not wraped.
// D3DX11_FILTER_MIRROR_V
// Indicates that pixels off the edge of the texture on the V-axis
// should be mirrored, not wraped.
// D3DX11_FILTER_MIRROR_W
// Indicates that pixels off the edge of the texture on the W-axis
// should be mirrored, not wraped.
// D3DX11_FILTER_MIRROR
// Same as specifying D3DX11_FILTER_MIRROR_U | D3DX11_FILTER_MIRROR_V |
// D3DX11_FILTER_MIRROR_V
// D3DX11_FILTER_DITHER
// Dithers the resulting image using a 4x4 order dither pattern.
// D3DX11_FILTER_SRGB_IN
// Denotes that the input data is in sRGB (gamma 2.2) colorspace.
// D3DX11_FILTER_SRGB_OUT
// Denotes that the output data is in sRGB (gamma 2.2) colorspace.
// D3DX11_FILTER_SRGB
// Same as specifying D3DX11_FILTER_SRGB_IN | D3DX11_FILTER_SRGB_OUT
//
//----------------------------------------------------------------------------
typedef enum D3DX11_FILTER_FLAG
{
D3DX11_FILTER_NONE = (1 << 0),
D3DX11_FILTER_POINT = (2 << 0),
D3DX11_FILTER_LINEAR = (3 << 0),
D3DX11_FILTER_TRIANGLE = (4 << 0),
D3DX11_FILTER_BOX = (5 << 0),
D3DX11_FILTER_MIRROR_U = (1 << 16),
D3DX11_FILTER_MIRROR_V = (2 << 16),
D3DX11_FILTER_MIRROR_W = (4 << 16),
D3DX11_FILTER_MIRROR = (7 << 16),
D3DX11_FILTER_DITHER = (1 << 19),
D3DX11_FILTER_DITHER_DIFFUSION= (2 << 19),
D3DX11_FILTER_SRGB_IN = (1 << 21),
D3DX11_FILTER_SRGB_OUT = (2 << 21),
D3DX11_FILTER_SRGB = (3 << 21),
} D3DX11_FILTER_FLAG;
//----------------------------------------------------------------------------
// D3DX11_NORMALMAP flags:
// ---------------------
// These flags are used to control how D3DX11ComputeNormalMap generates normal
// maps. Any number of these flags may be OR'd together in any combination.
//
// D3DX11_NORMALMAP_MIRROR_U
// Indicates that pixels off the edge of the texture on the U-axis
// should be mirrored, not wraped.
// D3DX11_NORMALMAP_MIRROR_V
// Indicates that pixels off the edge of the texture on the V-axis
// should be mirrored, not wraped.
// D3DX11_NORMALMAP_MIRROR
// Same as specifying D3DX11_NORMALMAP_MIRROR_U | D3DX11_NORMALMAP_MIRROR_V
// D3DX11_NORMALMAP_INVERTSIGN
// Inverts the direction of each normal
// D3DX11_NORMALMAP_COMPUTE_OCCLUSION
// Compute the per pixel Occlusion term and encodes it into the alpha.
// An Alpha of 1 means that the pixel is not obscured in anyway, and
// an alpha of 0 would mean that the pixel is completly obscured.
//
//----------------------------------------------------------------------------
typedef enum D3DX11_NORMALMAP_FLAG
{
D3DX11_NORMALMAP_MIRROR_U = (1 << 16),
D3DX11_NORMALMAP_MIRROR_V = (2 << 16),
D3DX11_NORMALMAP_MIRROR = (3 << 16),
D3DX11_NORMALMAP_INVERTSIGN = (8 << 16),
D3DX11_NORMALMAP_COMPUTE_OCCLUSION = (16 << 16),
} D3DX11_NORMALMAP_FLAG;
//----------------------------------------------------------------------------
// D3DX11_CHANNEL flags:
// -------------------
// These flags are used by functions which operate on or more channels
// in a texture.
//
// D3DX11_CHANNEL_RED
// Indicates the red channel should be used
// D3DX11_CHANNEL_BLUE
// Indicates the blue channel should be used
// D3DX11_CHANNEL_GREEN
// Indicates the green channel should be used
// D3DX11_CHANNEL_ALPHA
// Indicates the alpha channel should be used
// D3DX11_CHANNEL_LUMINANCE
// Indicates the luminaces of the red green and blue channels should be
// used.
//
//----------------------------------------------------------------------------
typedef enum D3DX11_CHANNEL_FLAG
{
D3DX11_CHANNEL_RED = (1 << 0),
D3DX11_CHANNEL_BLUE = (1 << 1),
D3DX11_CHANNEL_GREEN = (1 << 2),
D3DX11_CHANNEL_ALPHA = (1 << 3),
D3DX11_CHANNEL_LUMINANCE = (1 << 4),
} D3DX11_CHANNEL_FLAG;
//----------------------------------------------------------------------------
// D3DX11_IMAGE_FILE_FORMAT:
// ---------------------
// This enum is used to describe supported image file formats.
//
//----------------------------------------------------------------------------
typedef enum D3DX11_IMAGE_FILE_FORMAT
{
D3DX11_IFF_BMP = 0,
D3DX11_IFF_JPG = 1,
D3DX11_IFF_PNG = 3,
D3DX11_IFF_DDS = 4,
D3DX11_IFF_TIFF = 10,
D3DX11_IFF_GIF = 11,
D3DX11_IFF_WMP = 12,
D3DX11_IFF_FORCE_DWORD = 0x7fffffff
} D3DX11_IMAGE_FILE_FORMAT;
//----------------------------------------------------------------------------
// D3DX11_SAVE_TEXTURE_FLAG:
// ---------------------
// This enum is used to support texture saving options.
//
//----------------------------------------------------------------------------
typedef enum D3DX11_SAVE_TEXTURE_FLAG
{
D3DX11_STF_USEINPUTBLOB = 0x0001,
} D3DX11_SAVE_TEXTURE_FLAG;
//----------------------------------------------------------------------------
// D3DX11_IMAGE_INFO:
// ---------------
// This structure is used to return a rough description of what the
// the original contents of an image file looked like.
//
// Width
// Width of original image in pixels
// Height
// Height of original image in pixels
// Depth
// Depth of original image in pixels
// ArraySize
// Array size in textures
// MipLevels
// Number of mip levels in original image
// MiscFlags
// Miscellaneous flags
// Format
// D3D format which most closely describes the data in original image
// ResourceDimension
// D3D11_RESOURCE_DIMENSION representing the dimension of texture stored in the file.
// D3D11_RESOURCE_DIMENSION_TEXTURE1D, 2D, 3D
// ImageFileFormat
// D3DX11_IMAGE_FILE_FORMAT representing the format of the image file.
//----------------------------------------------------------------------------
typedef struct D3DX11_IMAGE_INFO
{
UINT Width;
UINT Height;
UINT Depth;
UINT ArraySize;
UINT MipLevels;
UINT MiscFlags;
DXGI_FORMAT Format;
D3D11_RESOURCE_DIMENSION ResourceDimension;
D3DX11_IMAGE_FILE_FORMAT ImageFileFormat;
} D3DX11_IMAGE_INFO;
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
//////////////////////////////////////////////////////////////////////////////
// Image File APIs ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------
// D3DX11_IMAGE_LOAD_INFO:
// ---------------
// This structure can be optionally passed in to texture loader APIs to
// control how textures get loaded. Pass in D3DX11_DEFAULT for any of these
// to have D3DX automatically pick defaults based on the source file.
//
// Width
// Rescale texture to Width texels wide
// Height
// Rescale texture to Height texels high
// Depth
// Rescale texture to Depth texels deep
// FirstMipLevel
// First mip level to load
// MipLevels
// Number of mip levels to load after the first level
// Usage
// D3D11_USAGE flag for the new texture
// BindFlags
// D3D11 Bind flags for the new texture
// CpuAccessFlags
// D3D11 CPU Access flags for the new texture
// MiscFlags
// Reserved. Must be 0
// Format
// Resample texture to the specified format
// Filter
// Filter the texture using the specified filter (only when resampling)
// MipFilter
// Filter the texture mip levels using the specified filter (only if
// generating mips)
// pSrcInfo
// (optional) pointer to a D3DX11_IMAGE_INFO structure that will get
// populated with source image information
//----------------------------------------------------------------------------
typedef struct D3DX11_IMAGE_LOAD_INFO
{
UINT Width;
UINT Height;
UINT Depth;
UINT FirstMipLevel;
UINT MipLevels;
D3D11_USAGE Usage;
UINT BindFlags;
UINT CpuAccessFlags;
UINT MiscFlags;
DXGI_FORMAT Format;
UINT Filter;
UINT MipFilter;
D3DX11_IMAGE_INFO* pSrcInfo;
#ifdef __cplusplus
D3DX11_IMAGE_LOAD_INFO()
{
Width = D3DX11_DEFAULT;
Height = D3DX11_DEFAULT;
Depth = D3DX11_DEFAULT;
FirstMipLevel = D3DX11_DEFAULT;
MipLevels = D3DX11_DEFAULT;
Usage = (D3D11_USAGE) D3DX11_DEFAULT;
BindFlags = D3DX11_DEFAULT;
CpuAccessFlags = D3DX11_DEFAULT;
MiscFlags = D3DX11_DEFAULT;
Format = DXGI_FORMAT_FROM_FILE;
Filter = D3DX11_DEFAULT;
MipFilter = D3DX11_DEFAULT;
pSrcInfo = NULL;
}
#endif
} D3DX11_IMAGE_LOAD_INFO;
//-------------------------------------------------------------------------------
// GetImageInfoFromFile/Resource/Memory:
// ------------------------------
// Fills in a D3DX11_IMAGE_INFO struct with information about an image file.
//
// Parameters:
// pSrcFile
// File name of the source image.
// pSrcModule
// Module where resource is located, or NULL for module associated
// with image the os used to create the current process.
// pSrcResource
// Resource name.
// pSrcData
// Pointer to file in memory.
// SrcDataSize
// Size in bytes of file in memory.
// pPump
// Optional pointer to a thread pump object to use.
// pSrcInfo
// Pointer to a D3DX11_IMAGE_INFO structure to be filled in with the
// description of the data in the source image file.
// pHResult
// Pointer to a memory location to receive the return value upon completion.
// Maybe NULL if not needed.
// If pPump != NULL, pHResult must be a valid memory location until the
// the asynchronous execution completes.
//-------------------------------------------------------------------------------
HRESULT WINAPI
D3DX11GetImageInfoFromFileA(
LPCSTR pSrcFile,
ID3DX11ThreadPump* pPump,
D3DX11_IMAGE_INFO* pSrcInfo,
HRESULT* pHResult);
HRESULT WINAPI
D3DX11GetImageInfoFromFileW(
LPCWSTR pSrcFile,
ID3DX11ThreadPump* pPump,
D3DX11_IMAGE_INFO* pSrcInfo,
HRESULT* pHResult);
#ifdef UNICODE
#define D3DX11GetImageInfoFromFile D3DX11GetImageInfoFromFileW
#else
#define D3DX11GetImageInfoFromFile D3DX11GetImageInfoFromFileA
#endif
HRESULT WINAPI
D3DX11GetImageInfoFromResourceA(
HMODULE hSrcModule,
LPCSTR pSrcResource,
ID3DX11ThreadPump* pPump,
D3DX11_IMAGE_INFO* pSrcInfo,
HRESULT* pHResult);
HRESULT WINAPI
D3DX11GetImageInfoFromResourceW(
HMODULE hSrcModule,
LPCWSTR pSrcResource,
ID3DX11ThreadPump* pPump,
D3DX11_IMAGE_INFO* pSrcInfo,
HRESULT* pHResult);
#ifdef UNICODE
#define D3DX11GetImageInfoFromResource D3DX11GetImageInfoFromResourceW
#else
#define D3DX11GetImageInfoFromResource D3DX11GetImageInfoFromResourceA
#endif
HRESULT WINAPI
D3DX11GetImageInfoFromMemory(
LPCVOID pSrcData,
SIZE_T SrcDataSize,
ID3DX11ThreadPump* pPump,
D3DX11_IMAGE_INFO* pSrcInfo,
HRESULT* pHResult);
//////////////////////////////////////////////////////////////////////////////
// Create/Save Texture APIs //////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------
// D3DX11CreateTextureFromFile/Resource/Memory:
// D3DX11CreateShaderResourceViewFromFile/Resource/Memory:
// -----------------------------------
// Create a texture object from a file or resource.
//
// Parameters:
//
// pDevice
// The D3D device with which the texture is going to be used.
// pSrcFile
// File name.
// hSrcModule
// Module handle. if NULL, current module will be used.
// pSrcResource
// Resource name in module
// pvSrcData
// Pointer to file in memory.
// SrcDataSize
// Size in bytes of file in memory.
// pLoadInfo
// Optional pointer to a D3DX11_IMAGE_LOAD_INFO structure that
// contains additional loader parameters.
// pPump
// Optional pointer to a thread pump object to use.
// ppTexture
// [out] Created texture object.
// ppShaderResourceView
// [out] Shader resource view object created.
// pHResult
// Pointer to a memory location to receive the return value upon completion.
// Maybe NULL if not needed.
// If pPump != NULL, pHResult must be a valid memory location until the
// the asynchronous execution completes.
//
//----------------------------------------------------------------------------
// FromFile
HRESULT WINAPI
D3DX11CreateShaderResourceViewFromFileA(
ID3D11Device* pDevice,
LPCSTR pSrcFile,
D3DX11_IMAGE_LOAD_INFO *pLoadInfo,
ID3DX11ThreadPump* pPump,
ID3D11ShaderResourceView** ppShaderResourceView,
HRESULT* pHResult);
HRESULT WINAPI
D3DX11CreateShaderResourceViewFromFileW(
ID3D11Device* pDevice,
LPCWSTR pSrcFile,
D3DX11_IMAGE_LOAD_INFO *pLoadInfo,
ID3DX11ThreadPump* pPump,
ID3D11ShaderResourceView** ppShaderResourceView,
HRESULT* pHResult);
#ifdef UNICODE
#define D3DX11CreateShaderResourceViewFromFile D3DX11CreateShaderResourceViewFromFileW
#else
#define D3DX11CreateShaderResourceViewFromFile D3DX11CreateShaderResourceViewFromFileA
#endif
HRESULT WINAPI
D3DX11CreateTextureFromFileA(
ID3D11Device* pDevice,
LPCSTR pSrcFile,
D3DX11_IMAGE_LOAD_INFO *pLoadInfo,
ID3DX11ThreadPump* pPump,
ID3D11Resource** ppTexture,
HRESULT* pHResult);
HRESULT WINAPI
D3DX11CreateTextureFromFileW(
ID3D11Device* pDevice,
LPCWSTR pSrcFile,
D3DX11_IMAGE_LOAD_INFO *pLoadInfo,
ID3DX11ThreadPump* pPump,
ID3D11Resource** ppTexture,
HRESULT* pHResult);
#ifdef UNICODE
#define D3DX11CreateTextureFromFile D3DX11CreateTextureFromFileW
#else
#define D3DX11CreateTextureFromFile D3DX11CreateTextureFromFileA
#endif
// FromResource (resources in dll/exes)
HRESULT WINAPI
D3DX11CreateShaderResourceViewFromResourceA(
ID3D11Device* pDevice,
HMODULE hSrcModule,
LPCSTR pSrcResource,
D3DX11_IMAGE_LOAD_INFO* pLoadInfo,
ID3DX11ThreadPump* pPump,
ID3D11ShaderResourceView** ppShaderResourceView,
HRESULT* pHResult);
HRESULT WINAPI
D3DX11CreateShaderResourceViewFromResourceW(
ID3D11Device* pDevice,
HMODULE hSrcModule,
LPCWSTR pSrcResource,
D3DX11_IMAGE_LOAD_INFO* pLoadInfo,
ID3DX11ThreadPump* pPump,
ID3D11ShaderResourceView** ppShaderResourceView,
HRESULT* pHResult);
#ifdef UNICODE
#define D3DX11CreateShaderResourceViewFromResource D3DX11CreateShaderResourceViewFromResourceW
#else
#define D3DX11CreateShaderResourceViewFromResource D3DX11CreateShaderResourceViewFromResourceA
#endif
HRESULT WINAPI
D3DX11CreateTextureFromResourceA(
ID3D11Device* pDevice,
HMODULE hSrcModule,
LPCSTR pSrcResource,
D3DX11_IMAGE_LOAD_INFO *pLoadInfo,
ID3DX11ThreadPump* pPump,
ID3D11Resource** ppTexture,
HRESULT* pHResult);
HRESULT WINAPI
D3DX11CreateTextureFromResourceW(
ID3D11Device* pDevice,
HMODULE hSrcModule,
LPCWSTR pSrcResource,
D3DX11_IMAGE_LOAD_INFO* pLoadInfo,
ID3DX11ThreadPump* pPump,
ID3D11Resource** ppTexture,
HRESULT* pHResult);
#ifdef UNICODE
#define D3DX11CreateTextureFromResource D3DX11CreateTextureFromResourceW
#else
#define D3DX11CreateTextureFromResource D3DX11CreateTextureFromResourceA
#endif
// FromFileInMemory
HRESULT WINAPI
D3DX11CreateShaderResourceViewFromMemory(
ID3D11Device* pDevice,
LPCVOID pSrcData,
SIZE_T SrcDataSize,
D3DX11_IMAGE_LOAD_INFO* pLoadInfo,
ID3DX11ThreadPump* pPump,
ID3D11ShaderResourceView** ppShaderResourceView,
HRESULT* pHResult);
HRESULT WINAPI
D3DX11CreateTextureFromMemory(
ID3D11Device* pDevice,
LPCVOID pSrcData,
SIZE_T SrcDataSize,
D3DX11_IMAGE_LOAD_INFO* pLoadInfo,
ID3DX11ThreadPump* pPump,
ID3D11Resource** ppTexture,
HRESULT* pHResult);
//////////////////////////////////////////////////////////////////////////////
// Misc Texture APIs /////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------
// D3DX11_TEXTURE_LOAD_INFO:
// ------------------------
//
//----------------------------------------------------------------------------
typedef struct _D3DX11_TEXTURE_LOAD_INFO
{
D3D11_BOX *pSrcBox;
D3D11_BOX *pDstBox;
UINT SrcFirstMip;
UINT DstFirstMip;
UINT NumMips;
UINT SrcFirstElement;
UINT DstFirstElement;
UINT NumElements;
UINT Filter;
UINT MipFilter;
#ifdef __cplusplus
_D3DX11_TEXTURE_LOAD_INFO()
{
pSrcBox = NULL;
pDstBox = NULL;
SrcFirstMip = 0;
DstFirstMip = 0;
NumMips = D3DX11_DEFAULT;
SrcFirstElement = 0;
DstFirstElement = 0;
NumElements = D3DX11_DEFAULT;
Filter = D3DX11_DEFAULT;
MipFilter = D3DX11_DEFAULT;
}
#endif
} D3DX11_TEXTURE_LOAD_INFO;
//----------------------------------------------------------------------------
// D3DX11LoadTextureFromTexture:
// ----------------------------
// Load a texture from a texture.
//
// Parameters:
//
//----------------------------------------------------------------------------
HRESULT WINAPI
D3DX11LoadTextureFromTexture(
ID3D11DeviceContext *pContext,
ID3D11Resource *pSrcTexture,
D3DX11_TEXTURE_LOAD_INFO *pLoadInfo,
ID3D11Resource *pDstTexture);
//----------------------------------------------------------------------------
// D3DX11FilterTexture:
// ------------------
// Filters mipmaps levels of a texture.
//
// Parameters:
// pBaseTexture
// The texture object to be filtered
// SrcLevel
// The level whose image is used to generate the subsequent levels.
// MipFilter
// D3DX11_FILTER flags controlling how each miplevel is filtered.
// Or D3DX11_DEFAULT for D3DX11_FILTER_BOX,
//
//----------------------------------------------------------------------------
HRESULT WINAPI
D3DX11FilterTexture(
ID3D11DeviceContext *pContext,
ID3D11Resource *pTexture,
UINT SrcLevel,
UINT MipFilter);
//----------------------------------------------------------------------------
// D3DX11SaveTextureToFile:
// ----------------------
// Save a texture to a file.
//
// Parameters:
// pDestFile
// File name of the destination file
// DestFormat
// D3DX11_IMAGE_FILE_FORMAT specifying file format to use when saving.
// pSrcTexture
// Source texture, containing the image to be saved
//
//----------------------------------------------------------------------------
HRESULT WINAPI
D3DX11SaveTextureToFileA(
ID3D11DeviceContext *pContext,
ID3D11Resource *pSrcTexture,
D3DX11_IMAGE_FILE_FORMAT DestFormat,
LPCSTR pDestFile);
HRESULT WINAPI
D3DX11SaveTextureToFileW(
ID3D11DeviceContext *pContext,
ID3D11Resource *pSrcTexture,
D3DX11_IMAGE_FILE_FORMAT DestFormat,
LPCWSTR pDestFile);
#ifdef UNICODE
#define D3DX11SaveTextureToFile D3DX11SaveTextureToFileW
#else
#define D3DX11SaveTextureToFile D3DX11SaveTextureToFileA
#endif
//----------------------------------------------------------------------------
// D3DX11SaveTextureToMemory:
// ----------------------
// Save a texture to a blob.
//
// Parameters:
// pSrcTexture
// Source texture, containing the image to be saved
// DestFormat
// D3DX11_IMAGE_FILE_FORMAT specifying file format to use when saving.
// ppDestBuf
// address of a d3dxbuffer pointer to return the image data
// Flags
// optional flags
//----------------------------------------------------------------------------
HRESULT WINAPI
D3DX11SaveTextureToMemory(
ID3D11DeviceContext *pContext,
ID3D11Resource* pSrcTexture,
D3DX11_IMAGE_FILE_FORMAT DestFormat,
ID3D10Blob** ppDestBuf,
UINT Flags);
//----------------------------------------------------------------------------
// D3DX11ComputeNormalMap:
// ---------------------
// Converts a height map into a normal map. The (x,y,z) components of each
// normal are mapped to the (r,g,b) channels of the output texture.
//
// Parameters
// pSrcTexture
// Pointer to the source heightmap texture
// Flags
// D3DX11_NORMALMAP flags
// Channel
// D3DX11_CHANNEL specifying source of height information
// Amplitude
// The constant value which the height information is multiplied by.
// pDestTexture
// Pointer to the destination texture
//---------------------------------------------------------------------------
HRESULT WINAPI
D3DX11ComputeNormalMap(
ID3D11DeviceContext *pContext,
ID3D11Texture2D *pSrcTexture,
UINT Flags,
UINT Channel,
FLOAT Amplitude,
ID3D11Texture2D *pDestTexture);
//----------------------------------------------------------------------------
// D3DX11SHProjectCubeMap:
// ----------------------
// Projects a function represented in a cube map into spherical harmonics.
//
// Parameters:
// Order
// Order of the SH evaluation, generates Order^2 coefs, degree is Order-1
// pCubeMap
// CubeMap that is going to be projected into spherical harmonics
// pROut
// Output SH vector for Red.
// pGOut
// Output SH vector for Green
// pBOut
// Output SH vector for Blue
//
//---------------------------------------------------------------------------
HRESULT WINAPI
D3DX11SHProjectCubeMap(
ID3D11DeviceContext *pContext,
__in_range(2,6) UINT Order,
ID3D11Texture2D *pCubeMap,
__out_ecount(Order*Order) FLOAT *pROut,
__out_ecount_opt(Order*Order) FLOAT *pGOut,
__out_ecount_opt(Order*Order) FLOAT *pBOut);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif //__D3DX11TEX_H__

View file

@ -1,76 +0,0 @@
//--------------------------------------------------------------------------------------
// File: DXErr.h
//
// DirectX Error Library
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
// This version only supports UNICODE.
#pragma once
#include <windows.h>
#include <sal.h>
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------------------------
// DXGetErrorString
//--------------------------------------------------------------------------------------
const WCHAR* WINAPI DXGetErrorStringW( _In_ HRESULT hr );
#define DXGetErrorString DXGetErrorStringW
//--------------------------------------------------------------------------------------
// DXGetErrorDescription has to be modified to return a copy in a buffer rather than
// the original static string.
//--------------------------------------------------------------------------------------
void WINAPI DXGetErrorDescriptionW( _In_ HRESULT hr, _Out_cap_(count) WCHAR* desc, _In_ size_t count );
#define DXGetErrorDescription DXGetErrorDescriptionW
//--------------------------------------------------------------------------------------
// DXTrace
//
// Desc: Outputs a formatted error message to the debug stream
//
// Args: WCHAR* strFile The current file, typically passed in using the
// __FILEW__ macro.
// DWORD dwLine The current line number, typically passed in using the
// __LINE__ macro.
// HRESULT hr An HRESULT that will be traced to the debug stream.
// CHAR* strMsg A string that will be traced to the debug stream (may be NULL)
// BOOL bPopMsgBox If TRUE, then a message box will popup also containing the passed info.
//
// Return: The hr that was passed in.
//--------------------------------------------------------------------------------------
HRESULT WINAPI DXTraceW( _In_z_ const WCHAR* strFile, _In_ DWORD dwLine, _In_ HRESULT hr, _In_opt_ const WCHAR* strMsg, _In_ bool bPopMsgBox );
#define DXTrace DXTraceW
//--------------------------------------------------------------------------------------
//
// Helper macros
//
//--------------------------------------------------------------------------------------
#if defined(DEBUG) || defined(_DEBUG)
#define DXTRACE_MSG(str) DXTrace( __FILEW__, (DWORD)__LINE__, 0, str, false )
#define DXTRACE_ERR(str,hr) DXTrace( __FILEW__, (DWORD)__LINE__, hr, str, false )
#define DXTRACE_ERR_MSGBOX(str,hr) DXTrace( __FILEW__, (DWORD)__LINE__, hr, str, true )
#else
#define DXTRACE_MSG(str) (0L)
#define DXTRACE_ERR(str,hr) (hr)
#define DXTRACE_ERR_MSGBOX(str,hr) (hr)
#endif
#ifdef __cplusplus
}
#endif //__cplusplus

File diff suppressed because it is too large Load diff

View file

@ -1,12 +0,0 @@
project(ScopeGuard)
add_library(ScopeGuard INTERFACE)
set(_ScopeGuard_Sources
${CMAKE_CURRENT_SOURCE_DIR}/ScopeGuard.h
)
target_include_directories(ScopeGuard INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})
target_sources(ScopeGuard INTERFACE ${_ScopeGuard_Sources})
source_group("ThirdParty\\ScopeGuard" FILES ${_ScopeGuard_Sources})

View file

@ -1,42 +0,0 @@
# pragma once
# include <utility>
# define AX_CONCATENATE_IMPL(s1, s2) s1##s2
# define AX_CONCATENATE(s1, s2) AX_CONCATENATE_IMPL(s1, s2)
# ifdef __COUNTER__
# define AX_ANONYMOUS_VARIABLE(str) AX_CONCATENATE(str, __COUNTER__)
# else
# define AX_ANONYMOUS_VARIABLE(str) AX_CONCATENATE(str, __LINE__)
# endif
namespace ax {
namespace scopeguard_detail {
enum class ScopeGuardOnExit {};
template <typename F>
class ScopeGuard
{
F f_;
bool active_;
public:
ScopeGuard() = delete;
ScopeGuard(const ScopeGuard&) = delete;
ScopeGuard& operator=(const ScopeGuard&) = delete;
ScopeGuard(ScopeGuard&& rhs): f_(std::move(rhs.f_)), active_(rhs.active_) { rhs.dismiss(); }
ScopeGuard(F f): f_(std::move(f)), active_(true) {}
~ScopeGuard() { if (active_) f_(); }
void dismiss() { active_ = false; }
};
template <typename F>
inline ScopeGuard<F> operator+(ScopeGuardOnExit, F&& f)
{
return ScopeGuard<F>(std::forward<F>(f));
}
} // namespace scopeguard_detail
} // namespace ax
# define AX_SCOPE_EXIT \
auto AX_ANONYMOUS_VARIABLE(AX_SCOPE_EXIT_STATE) \
= ::ax::scopeguard_detail::ScopeGuardOnExit() + [&]()

View file

@ -1,19 +0,0 @@
set(_gl3w_Sources
Include/GL/gl3w.h
Include/GL/glcorearb.h
Source/gl3w.c
)
source_group("" FILES ${_gl3w_Sources})
add_library(gl3w STATIC ${_gl3w_Sources})
target_include_directories(gl3w PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/Include)
if (UNIX AND (NOT APPLE))
# Linux: GL is required to pull glXGetProcAddress
target_link_libraries(gl3w PRIVATE GL dl)
endif()
set_property(TARGET gl3w PROPERTY FOLDER "external")

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,28 +0,0 @@
project(imgui VERSION 1.76)
set(_imgui_Sources
imconfig.h
imgui.cpp
imgui.h
imgui.natvis
imgui_demo.cpp
imgui_draw.cpp
imgui_internal.h
imgui_widgets.cpp
imgui_tables.cpp
imstb_rectpack.h
imstb_textedit.h
imstb_truetype.h
LICENSE.txt
)
add_library(${PROJECT_NAME} STATIC ${_imgui_Sources})
target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
#target_compile_definitions(${PROJECT_NAME} PUBLIC "ImDrawIdx=unsigned int")
target_compile_definitions(${PROJECT_NAME} PUBLIC IMGUI_DISABLE_OBSOLETE_FUNCTIONS)
source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${_imgui_Sources})
set_property(TARGET ${PROJECT_NAME} PROPERTY FOLDER "external")

View file

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2014-2020 Omar Cornut
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,122 +0,0 @@
//-----------------------------------------------------------------------------
// COMPILE-TIME OPTIONS FOR DEAR IMGUI
// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure.
// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions.
//-----------------------------------------------------------------------------
// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it)
// B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template.
//-----------------------------------------------------------------------------
// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp
// files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures.
// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts.
// Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using.
//-----------------------------------------------------------------------------
#pragma once
//---- Define assertion handler. Defaults to calling assert().
// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement.
//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
//#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts
//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows
// Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
// DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()
// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details.
//#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport )
//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names.
//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
//---- Disable all of Dear ImGui or don't implement standard windows.
// It is very strongly recommended to NOT disable the demo windows during development. Please read comments in imgui_demo.cpp.
//#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty.
//#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty. Not recommended.
//#define IMGUI_DISABLE_METRICS_WINDOW // Disable metrics/debugger window: ShowMetricsWindow() will be empty.
//---- Don't implement some functions to reduce linkage requirements.
//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a)
//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] Don't implement default IME handler. Won't use and link with ImmGetContext/ImmSetCompositionWindow. (imm32.lib/.a)
//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, ime).
//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default).
//#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf)
//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself.
//#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies)
//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function.
//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().
//#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available
//---- Include imgui_user.h at the end of imgui.h as a convenience
//#define IMGUI_INCLUDE_IMGUI_USER_H
//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another)
//#define IMGUI_USE_BGRA_PACKED_COLOR
//---- Use 32-bit for ImWchar (default is 16-bit) to support unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...)
//#define IMGUI_USE_WCHAR32
//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version
// By default the embedded implementations are declared static and not available outside of Dear ImGui sources files.
//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h"
//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h"
//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
//---- Use stb_printf's faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined)
// Requires 'stb_sprintf.h' to be available in the include path. Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by STB sprintf.
// #define IMGUI_USE_STB_SPRINTF
//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui)
// Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided).
// On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'.
//#define IMGUI_ENABLE_FREETYPE
//---- Use stb_truetype to build and rasterize the font atlas (default)
// The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend.
//#define IMGUI_ENABLE_STB_TRUETYPE
//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4.
// This will be inlined as part of ImVec2 and ImVec4 class declarations.
/*
#define IM_VEC2_CLASS_EXTRA \
ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \
operator MyVec2() const { return MyVec2(x,y); }
#define IM_VEC4_CLASS_EXTRA \
ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \
operator MyVec4() const { return MyVec4(x,y,z,w); }
*/
//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices.
// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices).
// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer.
// Read about ImGuiBackendFlags_RendererHasVtxOffset for details.
//#define ImDrawIdx unsigned int
//---- Override ImDrawCallback signature (will need to modify renderer backends accordingly)
//struct ImDrawList;
//struct ImDrawCmd;
//typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data);
//#define ImDrawCallback MyImDrawCallback
//---- Debug Tools: Macro to break in Debugger
// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.)
//#define IM_DEBUG_BREAK IM_ASSERT(0)
//#define IM_DEBUG_BREAK __debugbreak()
//---- Debug Tools: Have the Item Picker break in the ItemAdd() function instead of ItemHoverable(),
// (which comes earlier in the code, will catch a few extra items, allow picking items other than Hovered one.)
// This adds a small runtime cost which is why it is not enabled by default.
//#define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
//---- Debug Tools: Enable slower asserts
//#define IMGUI_DEBUG_PARANOID
//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files.
/*
namespace ImGui
{
void MyFunction(const char* name, const MyMatrix44& v);
}
*/

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,47 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- natvis file for Visual Studio debugger (you can include this in a project file, or install in visual studio folder) -->
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
<Type Name="ImVector&lt;*&gt;">
<DisplayString>{{Size={Size} Capacity={Capacity}}}</DisplayString>
<Expand>
<ArrayItems>
<Size>Size</Size>
<ValuePointer>Data</ValuePointer>
</ArrayItems>
</Expand>
</Type>
<Type Name="ImVec2">
<DisplayString>{{x={x,g} y={y,g}}}</DisplayString>
</Type>
<Type Name="ImVec4">
<DisplayString>{{x={x,g} y={y,g} z={z,g} w={w,g}}}</DisplayString>
</Type>
<Type Name="ImRect">
<DisplayString>{{Min=({Min.x,g} {Min.y,g}) Max=({Max.x,g} {Max.y,g}) Size=({Max.x-Min.x,g} {Max.y-Min.y,g})}}</DisplayString>
<Expand>
<Item Name="Min">Min</Item>
<Item Name="Max">Max</Item>
<Item Name="[Width]">Max.x - Min.x</Item>
<Item Name="[Height]">Max.y - Min.y</Item>
</Expand>
</Type>
<Type Name="ImGuiWindow">
<DisplayString>{{Name {Name,s} Active {(Active||WasActive)?1:0,d} Child {(Flags &amp; 0x01000000)?1:0,d} Popup {(Flags &amp; 0x04000000)?1:0,d} Hidden {(Hidden)?1:0,d}}</DisplayString>
</Type>
<Type Name="ImGuiDockNode">
<DisplayString>{{ID {ID,x} Pos=({Pos.x,g} {Pos.y,g}) Size=({Size.x,g} {Size.y,g}) Parent {(ParentNode==0)?0:ParentNode->ID,x} Childs {(ChildNodes[0] != 0)+(ChildNodes[1] != 0)} Windows {Windows.Size} }</DisplayString>
</Type>
<Type Name="ImDrawChannel">
<DisplayString>{{ Cmd={_CmdBuffer.Size} Idx={_IdxBuffer.Size} }}</DisplayString>
</Type>
</AutoVisualizer>

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,639 +0,0 @@
// [DEAR IMGUI]
// This is a slightly modified version of stb_rect_pack.h 1.00.
// Those changes would need to be pushed into nothings/stb:
// - Added STBRP__CDECL
// Grep for [DEAR IMGUI] to find the changes.
// stb_rect_pack.h - v1.00 - 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.
// Can override those by defining STBRP_SORT and STBRP_ASSERT.
//
// 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.
//
// Credits
//
// Library
// Sean Barrett
// Minor features
// Martins Mozeiko
// github:IntellectualKitty
//
// Bugfixes / warning fixes
// Jeremy Jaussaud
// Fabian Giesen
//
// Version history:
//
// 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles
// 0.99 (2019-02-07) warning fixes
// 0.11 (2017-03-03) return packing success/fail result
// 0.10 (2016-10-25) remove cast-away-const to avoid warnings
// 0.09 (2016-08-27) fix compiler warnings
// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
// 0.05: added STBRP_ASSERT to allow replacing assert
// 0.04: fixed minor bug in STBRP_LARGE_RECTS support
// 0.01: initial release
//
// LICENSE
//
// See end of file for license information.
//////////////////////////////////////////////////////////////////////////////
//
// 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 int 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.
//
// The function returns 1 if all of the rectangles were successfully
// packed and 0 otherwise.
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
#ifndef STBRP_SORT
#include <stdlib.h>
#define STBRP_SORT qsort
#endif
#ifndef STBRP_ASSERT
#include <assert.h>
#define STBRP_ASSERT assert
#endif
// [DEAR IMGUI] Added STBRP__CDECL
#ifdef _MSC_VER
#define STBRP__NOTUSED(v) (void)(v)
#define STBRP__CDECL __cdecl
#else
#define STBRP__NOTUSED(v) (void)sizeof(v)
#define STBRP__CDECL
#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)
{
stbrp_node *node = first;
int x1 = x0 + width;
int min_y, visited_width, waste_area;
STBRP__NOTUSED(c);
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);
// if it can't possibly fit, bail immediately
if (width > c->width || height > c->height) {
fr.prev_link = NULL;
fr.x = fr.y = 0;
return fr;
}
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);
{
int count=0;
cur = context->active_head;
while (cur) {
cur = cur->next;
++count;
}
cur = context->free_head;
while (cur) {
cur = cur->next;
++count;
}
STBRP_ASSERT(count == context->num_nodes+2);
}
#endif
return res;
}
// [DEAR IMGUI] Added STBRP__CDECL
static int STBRP__CDECL rect_height_compare(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const 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);
}
// [DEAR IMGUI] Added STBRP__CDECL
static int STBRP__CDECL rect_original_order(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const 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 int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
{
int i, all_rects_packed = 1;
// we use the 'was_packed' field internally to allow sorting/unsorting
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = i;
}
// sort according to heuristic
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
for (i=0; i < num_rects; ++i) {
if (rects[i].w == 0 || rects[i].h == 0) {
rects[i].x = rects[i].y = 0; // empty rect needs no space
} else {
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
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
// set was_packed flags and all_rects_packed status
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
if (!rects[i].was_packed)
all_rects_packed = 0;
}
// return the all_rects_packed status
return all_rects_packed;
}
#endif
/*
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Sean Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
*/

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,12 +0,0 @@
project(stb_image)
add_library(stb_image INTERFACE)
set(_stb_image_Sources
${CMAKE_CURRENT_SOURCE_DIR}/stb_image.h
)
target_include_directories(stb_image INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})
target_sources(stb_image INTERFACE ${_stb_image_Sources})
source_group("ThirdParty\\stb_image" FILES ${_stb_image_Sources})

File diff suppressed because it is too large Load diff

View file

@ -27,6 +27,11 @@
static constexpr bool value = (sizeof(yes_type) == sizeof(test<mixin>(0))); \
}
// Special sentinel value. This needs to be unique, so allow it to be overridden in the user's ImGui config
# ifndef ImDrawCallback_ImCanvas
# define ImDrawCallback_ImCanvas (ImDrawCallback)(-2)
# endif
namespace ImCanvasDetails {
DECLARE_HAS_MEMBER(HasFringeScale, _FringeScale);
@ -68,12 +73,6 @@ struct VtxCurrentOffsetRef
}
};
static void SentinelDrawCallback(const ImDrawList* parent_list, const ImDrawCmd* cmd)
{
// This is a sentinel draw callback, it's only purpose is to mark draw list command.
IM_ASSERT(false && "This draw callback should never be called.");
}
} // namespace ImCanvasDetails
// Returns a reference to _FringeScale extension to ImDrawList
@ -109,13 +108,8 @@ bool ImGuiEx::Canvas::Begin(ImGuiID id, const ImVec2& size)
UpdateViewTransformPosition();
# if IMGUI_VERSION_NUM > 18415
if (ImGui::IsClippedEx(m_WidgetRect, id))
return false;
# else
if (ImGui::IsClippedEx(m_WidgetRect, id, false))
return false;
# endif
// Save current channel, so we can assert when user
// call canvas API with different one.
@ -376,13 +370,8 @@ void ImGuiEx::Canvas::SaveViewportState()
m_WindowPosBackup = window->Pos;
m_ViewportPosBackup = viewport->Pos;
m_ViewportSizeBackup = viewport->Size;
# if IMGUI_VERSION_NUM > 18002
m_ViewportWorkPosBackup = viewport->WorkPos;
m_ViewportWorkSizeBackup = viewport->WorkSize;
# else
m_ViewportWorkOffsetMinBackup = viewport->WorkOffsetMin;
m_ViewportWorkOffsetMaxBackup = viewport->WorkOffsetMax;
# endif
# endif
}
@ -395,13 +384,8 @@ void ImGuiEx::Canvas::RestoreViewportState()
window->Pos = m_WindowPosBackup;
viewport->Pos = m_ViewportPosBackup;
viewport->Size = m_ViewportSizeBackup;
# if IMGUI_VERSION_NUM > 18002
viewport->WorkPos = m_ViewportWorkPosBackup;
viewport->WorkSize = m_ViewportWorkSizeBackup;
# else
viewport->WorkOffsetMin = m_ViewportWorkOffsetMinBackup;
viewport->WorkOffsetMax = m_ViewportWorkOffsetMaxBackup;
# endif
# endif
}
@ -421,6 +405,15 @@ void ImGuiEx::Canvas::EnterLocalSpace()
auto clipped_clip_rect = m_DrawList->_ClipRectStack.back();
ImGui::PopClipRect();
# if IMGUI_EX_CANVAS_DEFERED()
m_Ranges.resize(m_Ranges.Size + 1);
m_CurrentRange = &m_Ranges.back();
m_CurrentRange->BeginComandIndex = ImMax(m_DrawList->CmdBuffer.Size, 0);
m_CurrentRange->BeginVertexIndex = m_DrawList->_VtxCurrentIdx + ImVtxOffsetRef(m_DrawList);
# endif
m_DrawListCommadBufferSize = ImMax(m_DrawList->CmdBuffer.Size, 0);
m_DrawListStartVertexIndex = m_DrawList->_VtxCurrentIdx + ImVtxOffsetRef(m_DrawList);
// Make sure we do not share draw command with anyone. We don't want to mess
// with someones clip rectangle.
@ -435,16 +428,9 @@ void ImGuiEx::Canvas::EnterLocalSpace()
//
// More investigation is needed. To get to the bottom of this.
if ((!m_DrawList->CmdBuffer.empty() && m_DrawList->CmdBuffer.back().ElemCount > 0) || m_DrawList->_Splitter._Count > 1)
m_DrawList->AddCallback(&ImCanvasDetails::SentinelDrawCallback, nullptr);
m_DrawList->AddCallback(ImDrawCallback_ImCanvas, nullptr);
# if IMGUI_EX_CANVAS_DEFERED()
m_Ranges.resize(m_Ranges.Size + 1);
m_CurrentRange = &m_Ranges.back();
m_CurrentRange->BeginComandIndex = ImMax(m_DrawList->CmdBuffer.Size - 1, 0);
m_CurrentRange->BeginVertexIndex = m_DrawList->_VtxCurrentIdx + ImVtxOffsetRef(m_DrawList);
# endif
m_DrawListCommadBufferSize = ImMax(m_DrawList->CmdBuffer.Size - 1, 0);
m_DrawListStartVertexIndex = m_DrawList->_VtxCurrentIdx + ImVtxOffsetRef(m_DrawList);
m_DrawListFirstCommandIndex = ImMax(m_DrawList->CmdBuffer.Size - 1, 0);
# if defined(IMGUI_HAS_VIEWPORT)
auto window = ImGui::GetCurrentWindow();
@ -462,13 +448,8 @@ void ImGuiEx::Canvas::EnterLocalSpace()
viewport->Pos = viewport_min;
viewport->Size = viewport_max - viewport_min;
# if IMGUI_VERSION_NUM > 18002
viewport->WorkPos = m_ViewportWorkPosBackup * m_View.InvScale;
viewport->WorkSize = m_ViewportWorkSizeBackup * m_View.InvScale;
# else
viewport->WorkOffsetMin = m_ViewportWorkOffsetMinBackup * m_View.InvScale;
viewport->WorkOffsetMax = m_ViewportWorkOffsetMaxBackup * m_View.InvScale;
# endif
# endif
// Clip rectangle in parent canvas space and move it to local space.
@ -524,7 +505,7 @@ void ImGuiEx::Canvas::LeaveLocalSpace()
}
// Move clip rectangles to screen space.
for (int i = m_DrawListCommadBufferSize; i < m_DrawList->CmdBuffer.size(); ++i)
for (int i = m_DrawListFirstCommandIndex; i < m_DrawList->CmdBuffer.size(); ++i)
{
auto& command = m_DrawList->CmdBuffer[i];
command.ClipRect.x = command.ClipRect.x * m_View.Scale + m_ViewTransformPosition.x;
@ -543,7 +524,7 @@ void ImGuiEx::Canvas::LeaveLocalSpace()
}
// Move clip rectangles to screen space.
for (int i = m_DrawListCommadBufferSize; i < m_DrawList->CmdBuffer.size(); ++i)
for (int i = m_DrawListFirstCommandIndex; i < m_DrawList->CmdBuffer.size(); ++i)
{
auto& command = m_DrawList->CmdBuffer[i];
command.ClipRect.x = command.ClipRect.x + m_ViewTransformPosition.x;
@ -554,8 +535,13 @@ void ImGuiEx::Canvas::LeaveLocalSpace()
}
// Remove sentinel draw command if present
if (m_DrawListCommadBufferSize > 0 && m_DrawList->CmdBuffer.size() >= m_DrawListCommadBufferSize && m_DrawList->CmdBuffer[m_DrawListCommadBufferSize - 1].UserCallback == &ImCanvasDetails::SentinelDrawCallback)
m_DrawList->CmdBuffer.erase(m_DrawList->CmdBuffer.Data + m_DrawListCommadBufferSize - 1);
if (m_DrawListCommadBufferSize > 0)
{
if (m_DrawList->CmdBuffer.size() > m_DrawListCommadBufferSize && m_DrawList->CmdBuffer[m_DrawListCommadBufferSize].UserCallback == ImDrawCallback_ImCanvas)
m_DrawList->CmdBuffer.erase(m_DrawList->CmdBuffer.Data + m_DrawListCommadBufferSize);
else if (m_DrawList->CmdBuffer.size() >= m_DrawListCommadBufferSize && m_DrawList->CmdBuffer[m_DrawListCommadBufferSize - 1].UserCallback == ImDrawCallback_ImCanvas)
m_DrawList->CmdBuffer.erase(m_DrawList->CmdBuffer.Data + m_DrawListCommadBufferSize - 1);
}
auto& fringeScale = ImFringeScaleRef(m_DrawList);
fringeScale = m_LastFringeScale;

View file

@ -236,6 +236,7 @@ private:
Range* m_CurrentRange = nullptr;
# endif
int m_DrawListFirstCommandIndex = 0;
int m_DrawListCommadBufferSize = 0;
int m_DrawListStartVertexIndex = 0;
@ -257,13 +258,8 @@ private:
ImVec2 m_WindowPosBackup;
ImVec2 m_ViewportPosBackup;
ImVec2 m_ViewportSizeBackup;
# if IMGUI_VERSION_NUM > 18002
ImVec2 m_ViewportWorkPosBackup;
ImVec2 m_ViewportWorkSizeBackup;
# else
ImVec2 m_ViewportWorkOffsetMinBackup;
ImVec2 m_ViewportWorkOffsetMaxBackup;
# endif
# endif
};

View file

@ -30,8 +30,10 @@ struct ImLine
//------------------------------------------------------------------------------
# if IMGUI_VERSION_NUM < 19002
inline bool operator==(const ImVec2& lhs, const ImVec2& rhs);
inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs);
# endif
inline ImVec2 operator*(const float lhs, const ImVec2& rhs);
# if IMGUI_VERSION_NUM < 18955
inline ImVec2 operator-(const ImVec2& lhs);

View file

@ -19,6 +19,7 @@
//------------------------------------------------------------------------------
# if IMGUI_VERSION_NUM < 19002
inline bool operator==(const ImVec2& lhs, const ImVec2& rhs)
{
return lhs.x == rhs.x && lhs.y == rhs.y;
@ -28,6 +29,7 @@ inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs)
{
return lhs.x != rhs.x || lhs.y != rhs.y;
}
# endif
inline ImVec2 operator*(const float lhs, const ImVec2& rhs)
{

View file

@ -40,46 +40,10 @@ namespace ax {
namespace NodeEditor {
namespace Detail {
# if !defined(IMGUI_VERSION_NUM) || (IMGUI_VERSION_NUM < 18822)
# define DECLARE_KEY_TESTER(Key) \
DECLARE_HAS_NESTED(Key, Key) \
struct KeyTester_ ## Key \
{ \
template <typename T> \
static int Get(typename std::enable_if<has_nested_ ## Key<ImGuiKey_>::value, T>::type*) \
{ \
return ImGui::GetKeyIndex(T::Key); \
} \
\
template <typename T> \
static int Get(typename std::enable_if<!has_nested_ ## Key<ImGuiKey_>::value, T>::type*) \
{ \
return -1; \
} \
}
DECLARE_KEY_TESTER(ImGuiKey_F);
DECLARE_KEY_TESTER(ImGuiKey_D);
static inline int GetKeyIndexForF()
{
return KeyTester_ImGuiKey_F::Get<ImGuiKey_>(nullptr);
}
static inline int GetKeyIndexForD()
{
return KeyTester_ImGuiKey_D::Get<ImGuiKey_>(nullptr);
}
# else
static inline ImGuiKey GetKeyIndexForF()
{
return ImGuiKey_F;
}
static inline ImGuiKey GetKeyIndexForD()
{
return ImGuiKey_D;
}
# if !defined(IMGUI_VERSION_NUM)
# error IMGUI_VERSION_NUM is not defined, please update Dear ImGui copy to at least 1.89 (August 2022)
# elif IMGUI_VERSION_NUM < 18900
# error Please update Dear ImGui copy to at least 1.89 (August 2022)
# endif
} // namespace Detail
@ -129,11 +93,7 @@ static const float c_SelectionFadeOutDuration = 0.15f; // seconds
static const auto c_MaxMoveOverEdgeSpeed = 10.0f;
static const auto c_MaxMoveOverEdgeDistance = 300.0f;
#if IMGUI_VERSION_NUM > 18101
static const auto c_AllRoundCornersFlags = ImDrawFlags_RoundCornersAll;
#else
static const auto c_AllRoundCornersFlags = 15;
#endif
//------------------------------------------------------------------------------
@ -1965,7 +1925,8 @@ void ed::EditorContext::Suspend(SuspendFlags flags)
IM_ASSERT(m_DrawList != nullptr && "Suspend was called outiside of Begin/End.");
auto lastChannel = m_DrawList->_Splitter._Current;
m_DrawList->ChannelsSetCurrent(m_ExternalChannel);
m_Canvas.Suspend();
if (m_IsCanvasVisible)
m_Canvas.Suspend();
m_DrawList->ChannelsSetCurrent(lastChannel);
if ((flags & SuspendFlags::KeepSplitter) != SuspendFlags::KeepSplitter)
ImDrawList_SwapSplitter(m_DrawList, m_Splitter);
@ -1978,7 +1939,8 @@ void ed::EditorContext::Resume(SuspendFlags flags)
ImDrawList_SwapSplitter(m_DrawList, m_Splitter);
auto lastChannel = m_DrawList->_Splitter._Current;
m_DrawList->ChannelsSetCurrent(m_ExternalChannel);
m_Canvas.Resume();
if (m_IsCanvasVisible)
m_Canvas.Resume();
m_DrawList->ChannelsSetCurrent(lastChannel);
}
@ -2563,7 +2525,7 @@ ed::Control ed::EditorContext::BuildControl(bool allowOffscreen)
# if IMGUI_VERSION_NUM >= 18836
if (m_IsHoveredWithoutOverlapp)
ImGui::SetItemKeyOwner(ImGuiKey_MouseWheelY);
# elif IMGUI_VERSION_NUM >= 17909
# else
if (m_IsHoveredWithoutOverlapp)
ImGui::SetItemUsingMouseWheel();
# endif
@ -3331,7 +3293,7 @@ ed::EditorAction::AcceptResult ed::NavigateAction::Accept(const Control& control
auto& io = ImGui::GetIO();
if (Editor->CanAcceptUserInput() && ImGui::IsKeyPressed(GetKeyIndexForF()) && Editor->AreShortcutsEnabled())
if (Editor->CanAcceptUserInput() && ImGui::IsKeyPressed(ImGuiKey_F) && Editor->AreShortcutsEnabled())
{
const auto zoomMode = io.KeyShift ? NavigateAction::ZoomMode::WithMargin : NavigateAction::ZoomMode::None;
@ -3447,8 +3409,7 @@ bool ed::NavigateAction::HandleZoom(const Control& control)
m_Animation.Finish();
auto mousePos = io.MousePos;
auto steps = (int)io.MouseWheel;
auto newZoom = MatchZoom(steps, m_ZoomLevels[steps < 0 ? 0 : m_ZoomLevelCount - 1]);
auto newZoom = GetNextZoom(io.MouseWheel);
auto oldView = GetView();
m_Zoom = newZoom;
@ -3624,6 +3585,32 @@ ImRect ed::NavigateAction::GetViewRect() const
return m_Canvas.CalcViewRect(GetView());
}
float ed::NavigateAction::GetNextZoom(float steps)
{
if (this->Editor->GetConfig().EnableSmoothZoom)
{
return MatchSmoothZoom(steps);
}
else
{
auto fixedSteps = (int)steps;
return MatchZoom(fixedSteps, m_ZoomLevels[fixedSteps < 0 ? 0 : m_ZoomLevelCount - 1]);
}
}
float ed::NavigateAction::MatchSmoothZoom(float steps)
{
const auto power = Editor->GetConfig().SmoothZoomPower;
const auto newZoom = m_Zoom * powf(power, steps);
if (newZoom < m_ZoomLevels[0])
return m_ZoomLevels[0];
else if (newZoom > m_ZoomLevels[m_ZoomLevelCount - 1])
return m_ZoomLevels[m_ZoomLevelCount - 1];
else
return newZoom;
}
float ed::NavigateAction::MatchZoom(int steps, float fallbackZoom)
{
auto currentZoomIndex = MatchZoomIndex(steps);
@ -4364,15 +4351,15 @@ ed::EditorAction::AcceptResult ed::ShortcutAction::Accept(const Control& control
Action candidateAction = None;
auto& io = ImGui::GetIO();
if (io.KeyCtrl && !io.KeyShift && !io.KeyAlt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_X)))
if (io.KeyCtrl && !io.KeyShift && !io.KeyAlt && ImGui::IsKeyPressed(ImGuiKey_X))
candidateAction = Cut;
if (io.KeyCtrl && !io.KeyShift && !io.KeyAlt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
if (io.KeyCtrl && !io.KeyShift && !io.KeyAlt && ImGui::IsKeyPressed(ImGuiKey_C))
candidateAction = Copy;
if (io.KeyCtrl && !io.KeyShift && !io.KeyAlt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_V)))
if (io.KeyCtrl && !io.KeyShift && !io.KeyAlt && ImGui::IsKeyPressed(ImGuiKey_V))
candidateAction = Paste;
if (io.KeyCtrl && !io.KeyShift && !io.KeyAlt && ImGui::IsKeyPressed(GetKeyIndexForD()))
if (io.KeyCtrl && !io.KeyShift && !io.KeyAlt && ImGui::IsKeyPressed(ImGuiKey_D))
candidateAction = Duplicate;
if (!io.KeyCtrl && !io.KeyShift && !io.KeyAlt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Space)))
if (!io.KeyCtrl && !io.KeyShift && !io.KeyAlt && ImGui::IsKeyPressed(ImGuiKey_Space))
candidateAction = CreateNode;
if (candidateAction != None)
@ -4709,15 +4696,15 @@ bool ed::CreateItemAction::Begin()
{
IM_ASSERT(false == m_InActive);
if (m_NextStage == None)
return false;
m_InActive = true;
m_CurrentStage = m_NextStage;
m_UserAction = Unknown;
m_LinkColor = IM_COL32_WHITE;
m_LinkThickness = 1.0f;
if (m_CurrentStage == None)
return false;
m_LastChannel = Editor->GetDrawList()->_Splitter._Current;
return true;
@ -4725,7 +4712,7 @@ bool ed::CreateItemAction::Begin()
void ed::CreateItemAction::End()
{
IM_ASSERT(m_InActive);
IM_ASSERT(m_InActive && "Please call End() only when Begin() was successful");
if (m_IsInGlobalSpace)
{
@ -4926,7 +4913,7 @@ ed::EditorAction::AcceptResult ed::DeleteItemsAction::Accept(const Control& cont
return False;
auto& io = ImGui::GetIO();
if (Editor->CanAcceptUserInput() && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Delete)) && Editor->AreShortcutsEnabled())
if (Editor->CanAcceptUserInput() && ImGui::IsKeyPressed(ImGuiKey_Delete) && Editor->AreShortcutsEnabled())
{
auto& selection = Editor->GetSelectedObjects();
if (!selection.empty())

View file

@ -21,8 +21,8 @@
//------------------------------------------------------------------------------
# define IMGUI_NODE_EDITOR_VERSION "0.9.2"
# define IMGUI_NODE_EDITOR_VERSION_NUM 000902
# define IMGUI_NODE_EDITOR_VERSION "0.10.0"
# define IMGUI_NODE_EDITOR_VERSION_NUM 001000
//------------------------------------------------------------------------------
@ -105,6 +105,8 @@ struct Config
int SelectButtonIndex; // Mouse button index select action will react to (0-left, 1-right, 2-middle)
int NavigateButtonIndex; // Mouse button index navigate action will react to (0-left, 1-right, 2-middle)
int ContextMenuButtonIndex; // Mouse button index context menu action will react to (0-left, 1-right, 2-middle)
bool EnableSmoothZoom;
float SmoothZoomPower;
Config()
: SettingsFile("NodeEditor.json")
@ -121,6 +123,12 @@ struct Config
, SelectButtonIndex(0)
, NavigateButtonIndex(1)
, ContextMenuButtonIndex(1)
, EnableSmoothZoom(true)
# ifdef __APPLE__
, SmoothZoomPower(1.1f)
# else
, SmoothZoomPower(1.3f)
# endif
{
}
};
@ -237,11 +245,7 @@ struct Style
PivotAlignment = ImVec2(0.5f, 0.5f);
PivotSize = ImVec2(0.0f, 0.0f);
PivotScale = ImVec2(1, 1);
#if IMGUI_VERSION_NUM > 18101
PinCorners = ImDrawFlags_RoundCornersAll;
#else
PinCorners = ImDrawCornerFlags_All;
#endif
PinRadius = 0.0f;
PinArrowSize = 0.0f;
PinArrowWidth = 0.0f;
@ -519,4 +523,4 @@ struct PinId final: Details::SafePointerType<PinId>
//------------------------------------------------------------------------------
# endif // __IMGUI_NODE_EDITOR_H__
# endif // __IMGUI_NODE_EDITOR_H__

View file

@ -886,6 +886,8 @@ private:
void NavigateTo(const ImRect& target, float duration = -1.0f, NavigationReason reason = NavigationReason::Unknown);
float GetNextZoom(float steps);
float MatchSmoothZoom(float steps);
float MatchZoom(int steps, float fallbackZoom);
int MatchZoomIndex(int direction);

View file

@ -1,17 +0,0 @@
if (TARGET ScopeGuard)
return()
endif()
set(_ScopeGuard_SourceDir ${IMGUI_NODE_EDITOR_ROOT_DIR}/external/ScopeGuard)
set(_ScopeGuard_BinaryDir ${CMAKE_BINARY_DIR}/external/ScopeGuard)
add_subdirectory(${_ScopeGuard_SourceDir} ${_ScopeGuard_BinaryDir})
include(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(
ScopeGuard
REQUIRED_VARS
_ScopeGuard_SourceDir
)

View file

@ -1,17 +0,0 @@
if (TARGET gl3w)
return()
endif()
set(_gl3w_SourceDir ${IMGUI_NODE_EDITOR_ROOT_DIR}/external/gl3w)
set(_gl3w_BinaryDir ${CMAKE_BINARY_DIR}/external/gl3w)
add_subdirectory(${_gl3w_SourceDir} ${_gl3w_BinaryDir})
include(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(
gl3w
REQUIRED_VARS
_gl3w_SourceDir
)

View file

@ -1,17 +0,0 @@
if (TARGET imgui)
return()
endif()
set(_imgui_SourceDir ${IMGUI_NODE_EDITOR_ROOT_DIR}/external/imgui)
set(_imgui_BinaryDir ${CMAKE_BINARY_DIR}/external/imgui)
add_subdirectory(${_imgui_SourceDir} ${_imgui_BinaryDir})
include(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(
imgui
REQUIRED_VARS
_imgui_SourceDir
)

View file

@ -1,17 +0,0 @@
if (TARGET stb_image)
return()
endif()
set(_stb_image_SourceDir ${IMGUI_NODE_EDITOR_ROOT_DIR}/external/stb_image)
set(_stb_image_BinaryDir ${CMAKE_BINARY_DIR}/external/stb_image)
add_subdirectory(${_stb_image_SourceDir} ${_stb_image_BinaryDir})
include(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(
stb_image
REQUIRED_VARS
_stb_image_SourceDir
)

View file

@ -2,16 +2,35 @@
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
<Type Name="crude_json::value">
<DisplayString Condition="m_Type == 1">{m_Type,en} {*(crude_json::object*)&amp;m_Storage,view(simple)}</DisplayString>
<DisplayString Condition="m_Type == 2">{m_Type,en} {*(crude_json::array*)&amp;m_Storage,view(simple)}</DisplayString>
<DisplayString Condition="m_Type == 3">{*(crude_json::string*)&amp;m_Storage,view(simple)}</DisplayString>
<DisplayString Condition="m_Type == 4">{*(crude_json::boolean*)&amp;m_Storage}</DisplayString>
<DisplayString Condition="m_Type == 5">{*(crude_json::number*)&amp;m_Storage,g}</DisplayString>
<Intrinsic Name="data" Expression="(void*)m_Storage.data" />
<Intrinsic Name="object_ptr" Expression="(crude_json::object*)m_Storage.data" />
<Intrinsic Name="array_ptr" Expression="(crude_json::array*)m_Storage.data" />
<Intrinsic Name="string_ptr" Expression="(crude_json::string*)m_Storage.data" />
<Intrinsic Name="boolean_ptr" Expression="(crude_json::boolean*)m_Storage.data" />
<Intrinsic Name="number_ptr" Expression="(crude_json::number*)m_Storage.data" />
<DisplayString Condition="m_Type == crude_json::type_t::null">null</DisplayString>
<DisplayString Condition="m_Type == crude_json::type_t::object">{*object_ptr()} : object</DisplayString>
<DisplayString Condition="m_Type == crude_json::type_t::array">{*array_ptr()} : array</DisplayString>
<DisplayString Condition="m_Type == crude_json::type_t::string">{*string_ptr()} : string</DisplayString>
<DisplayString Condition="m_Type == crude_json::type_t::boolean">{*boolean_ptr()} : boolean</DisplayString>
<DisplayString Condition="m_Type == crude_json::type_t::number">{*number_ptr(),g} : number</DisplayString>
<DisplayString Condition="m_Type == crude_json::type_t::discarded">discarded</DisplayString>
<DisplayString>{m_Type,en}</DisplayString>
<StringView Condition="m_Type == 3">*(crude_json::string*)&amp;m_Storage</StringView>
<StringView Condition="m_Type == crude_json::type_t::string">*(crude_json::string*)data()</StringView>
<Expand>
<ExpandedItem Condition="m_Type == 1">*(crude_json::object*)&amp;m_Storage,view(simple)</ExpandedItem>
<ExpandedItem Condition="m_Type == 2">*(crude_json::array*)&amp;m_Storage,view(simple)</ExpandedItem>
<ExpandedItem Condition="m_Type == crude_json::type_t::object">*(crude_json::object*)data(),view(simple)</ExpandedItem>
<ExpandedItem Condition="m_Type == crude_json::type_t::array">*(crude_json::array*)data(),view(simple)</ExpandedItem>
<Item Name="[value]" Condition="m_Type == crude_json::type_t::string">*string_ptr(),view(simple)</Item>
<Item Name="[value]" Condition="m_Type == crude_json::type_t::boolean">*boolean_ptr()</Item>
<Item Name="[value]" Condition="m_Type == crude_json::type_t::number">*number_ptr()</Item>
</Expand>
</Type>
<Type Name="std::pair&lt;*, crude_json::value&gt;" IncludeView="MapHelper" Priority="High">
<DisplayString>{second}</DisplayString>
<Expand HideRawView="true">
<ExpandedItem>second</ExpandedItem>
</Expand>
</Type>

View file

@ -30,35 +30,4 @@
</Expand>
</Type>
<Type Name="std::pair&lt;*, crude_json::value&gt;" IncludeView="MapHelper" Priority="High">
<DisplayString>{second}</DisplayString>
<Expand HideRawView="true">
<ExpandedItem>second</ExpandedItem>
</Expand>
</Type>
<Type Name="crude_json::value">
<Intrinsic Name="object_ptr" Expression="(crude_json::object*)&amp;m_Storage" />
<Intrinsic Name="array_ptr" Expression="(crude_json::array*)&amp;m_Storage" />
<Intrinsic Name="string_ptr" Expression="(crude_json::string*)&amp;m_Storage" />
<Intrinsic Name="boolean_ptr" Expression="(crude_json::boolean*)&amp;m_Storage" />
<Intrinsic Name="number_ptr" Expression="(crude_json::number*)&amp;m_Storage" />
<DisplayString Condition="m_Type == crude_json::type_t::null">null</DisplayString>
<DisplayString Condition="m_Type == crude_json::type_t::object">{*object_ptr()} : object</DisplayString>
<DisplayString Condition="m_Type == crude_json::type_t::array">{*array_ptr()} : array</DisplayString>
<DisplayString Condition="m_Type == crude_json::type_t::string">{*string_ptr()} : string</DisplayString>
<DisplayString Condition="m_Type == crude_json::type_t::boolean">{*boolean_ptr()} : boolean</DisplayString>
<DisplayString Condition="m_Type == crude_json::type_t::number">{*number_ptr(),g} : number</DisplayString>
<DisplayString Condition="m_Type == crude_json::type_t::discarded">discarded</DisplayString>
<Expand HideRawView="true">
<!--<Synthetic Name="[type]"><DisplayString>{m_Type,en}</DisplayString></Synthetic>-->
<ExpandedItem Condition="m_Type == crude_json::type_t::object">*object_ptr(),view(simple)</ExpandedItem>
<ExpandedItem Condition="m_Type == crude_json::type_t::array">*array_ptr(),view(simple)</ExpandedItem>
<Item Name="[value]" Condition="m_Type == crude_json::type_t::string">*string_ptr(),view(simple)</Item>
<Item Name="[value]" Condition="m_Type == crude_json::type_t::boolean">*boolean_ptr()</Item>
<Item Name="[value]" Condition="m_Type == crude_json::type_t::number">*number_ptr()</Item>
</Expand>
</Type>
</AutoVisualizer>

View file

@ -2,12 +2,80 @@
#include "IconsMaterialDesignIcons.h"
#include <fstream>
#include <memory>
#include <sstream>
#include <iostream>
#include <string>
#include "imgui.h"
void CodeEditor::TextViewDraw()
{
ImGui::BeginChild("TextView", ImVec2(0, 0), true, ImGuiWindowFlags_HorizontalScrollbar);
static ImGuiTableFlags flags1 = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_RowBg | ImGuiTableFlags_ContextMenuInBody;
static ImU32 cell_bg_color = ImGui::GetColorU32(ImVec4(0.3f, 0.3f, 0.7f, 0.65f));
if (ImGui::BeginTable("AssemblyCode", 3, flags1))
{
int i = 0;
std::string line;
std::istringstream is(m_text);
while (std::getline(is, line))
{
ImGui::TableNextRow();
ImGui::PushID(static_cast<int>(i)); // Identifiant unique pour chaque ligne
ImGui::TableNextColumn();
// Colonne des breakpoints
if (ImGui::Selectable("", m_breakpoints.contains(i), 0, ImVec2(20, 20))) {
if (m_breakpoints.contains(i))
{
m_breakpoints.erase(i);
}
else
{
m_breakpoints.insert(i);
}
}
if (m_breakpoints.contains(i)) {
ImU32 cell_bg_color = ImGui::GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 0.85f));
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, cell_bg_color);
}
ImGui::TableNextColumn();
if (m_highlights.count(i) > 0)
{
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, cell_bg_color);
}
// Colonne des numéros de ligne
ImGui::Text("%d", static_cast<int>(i + 1));
ImGui::TableNextColumn();
if (m_highlights.count(i) > 0)
{
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, cell_bg_color);
}
ImGui::TextUnformatted(line.c_str());
ImGui::PopID();
i++;
}
ImGui::EndTable();
}
ImGui::EndChild();
}
CodeEditor::CodeEditor(IStoryManager &project)
: WindowBase("Code editor")
, m_storyManager(project)
{
mEditor.SetReadOnly(false);
// mEditor.SetReadOnly(false);
SetFlags(ImGuiWindowFlags_MenuBar);
}
@ -27,24 +95,39 @@ void CodeEditor::Initialize()
void CodeEditor::ClearErrors()
{
m_markers.clear();
// m_markers.clear();
}
void CodeEditor::AddError(int line, const std::string &text)
{
m_markers.insert(std::make_pair(line, text));
mEditor.SetErrorMarkers(m_markers);
// m_markers.insert(std::make_pair(line, text));
// mEditor.SetErrorMarkers(m_markers);
}
void CodeEditor::SetScript(const std::string &txt)
{
mEditor.SetText(txt);
m_text = txt;
m_text = R"(
fdsfds
fds
ffffffffffffffffffffff
ff
fd
feeeee
21234f
e
fdsfs
)";
HighlightLine(2);
}
std::string CodeEditor::GetScript() const
{
return mEditor.GetText();
// return mEditor.GetText();
return "";
}
@ -53,7 +136,7 @@ void CodeEditor::Draw()
WindowBase::BeginDraw();
auto cpos = mEditor.GetCursorPosition();
// auto cpos = mEditor.GetCursorPosition();
ImGui::SetWindowSize(ImVec2(800, 600), ImGuiCond_FirstUseEver);
if (ImGui::BeginMenuBar())
@ -62,18 +145,18 @@ void CodeEditor::Draw()
{
if (ImGui::MenuItem("Save"))
{
auto textToSave = mEditor.GetText();
// auto textToSave = mEditor.GetText();
/// save text....
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Edit"))
{
bool ro = mEditor.IsReadOnly();
if (ImGui::MenuItem("Read-only mode", nullptr, &ro))
mEditor.SetReadOnly(ro);
// bool ro = mEditor.IsReadOnly();
// if (ImGui::MenuItem("Read-only mode", nullptr, &ro))
// mEditor.SetReadOnly(ro);
ImGui::Separator();
/*
if (ImGui::MenuItem("Undo", "ALT-Backspace", nullptr, !ro && mEditor.CanUndo()))
mEditor.Undo();
if (ImGui::MenuItem("Redo", "Ctrl-Y", nullptr, !ro && mEditor.CanRedo()))
@ -89,15 +172,16 @@ void CodeEditor::Draw()
mEditor.Delete();
if (ImGui::MenuItem("Paste", "Ctrl-V", nullptr, !ro && ImGui::GetClipboardText() != nullptr))
mEditor.Paste();
*/
ImGui::Separator();
if (ImGui::MenuItem("Select all", nullptr, nullptr))
mEditor.SetSelection(TextEditor::Coordinates(), TextEditor::Coordinates(mEditor.GetTotalLines(), 0));
// if (ImGui::MenuItem("Select all", nullptr, nullptr))
// mEditor.SetSelection(TextEditor::Coordinates(), TextEditor::Coordinates(mEditor.GetTotalLines(), 0));
ImGui::EndMenu();
}
/*
if (ImGui::BeginMenu("View"))
{
if (ImGui::MenuItem("Dark palette"))
@ -108,15 +192,17 @@ void CodeEditor::Draw()
mEditor.SetPalette(TextEditor::GetRetroBluePalette());
ImGui::EndMenu();
}
*/
ImGui::EndMenuBar();
}
ImGui::Text("%6d/%-6d %6d lines | %s | %s ", cpos.mLine + 1, cpos.mColumn + 1, mEditor.GetTotalLines(),
mEditor.IsOverwrite() ? "Ovr" : "Ins",
mEditor.CanUndo() ? "*" : " ");
// ImGui::Text("%6d/%-6d %6d lines | %s | %s ", cpos.mLine + 1, cpos.mColumn + 1, mEditor.GetTotalLines(),
// mEditor.IsOverwrite() ? "Ovr" : "Ins",
// mEditor.CanUndo() ? "*" : " ");
ImGui::SameLine();
if (ImGui::SmallButton("Toggle breakpoint")) {
/*
if (m_breakPoints.contains(cpos.mLine + 1))
{
m_breakPoints.erase(cpos.mLine + 1);
@ -128,6 +214,7 @@ void CodeEditor::Draw()
mEditor.SetBreakpoints(m_breakPoints);
m_storyManager.ToggleBreakpoint(cpos.mLine + 1);
*/
}
ImGui::SameLine();
if (ImGui::SmallButton(ICON_MDI_SKIP_NEXT "##step_instruction")) {
@ -139,6 +226,8 @@ void CodeEditor::Draw()
m_storyManager.Run();
}
mEditor.Render("TextEditor");
TextViewDraw();
// mEditor.Render("TextEditor");
WindowBase::EndDraw();
}

View file

@ -1,8 +1,9 @@
#pragma once
#include "TextEditor.h"
#include "window_base.h"
#include "i_story_manager.h"
#include <unordered_set>
class CodeEditor : public WindowBase
{
@ -20,12 +21,19 @@ public:
void HighlightLine(int line)
{
mEditor.SetExecutionMarker(line);
// mEditor.SetExecutionMarker(line);
m_highlights[line] = ImVec4(0.5f, 0.5f, 1.0f, 0.5f);
}
private:
IStoryManager &m_storyManager;
TextEditor mEditor;
TextEditor::Breakpoints m_breakPoints;
TextEditor::ErrorMarkers m_markers;
std::string m_text;
std::unordered_set<int> m_breakpoints;
std::map<int, ImVec4> m_highlights;
// TextEditor mEditor;
// TextEditor::Breakpoints m_breakPoints;
// TextEditor::ErrorMarkers m_markers;
void TextViewDraw();
};

View file

@ -37,7 +37,7 @@ void EmulatorWindow::Draw()
if (m_image.Valid())
{
ImGui::Image(m_image.texture, ImVec2(320, 240));
ImGui::Image(reinterpret_cast<ImTextureID>(m_image.texture), ImVec2(320, 240));
}
else
{

View file

@ -65,7 +65,7 @@ bool LoadTextureFromFile(const char* filename, Gui::Image &img)
/* Use the tonemap operator to convert to SDR output */
const char *tonemap = NULL;
SDL_SetStringProperty(SDL_GetSurfaceProperties(surface), SDL_PROP_SURFACE_TONEMAP_OPERATOR_STRING, tonemap);
temp = SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_RGBA32);
temp = SDL_ConvertSurface(surface, SDL_PIXELFORMAT_RGBA32);
SDL_DestroySurface(surface);
if (!temp) {
SDL_Log("Couldn't convert surface: %s\n", SDL_GetError());
@ -79,8 +79,11 @@ bool LoadTextureFromFile(const char* filename, Gui::Image &img)
return false;
}
SDL_QueryTexture(static_cast<SDL_Texture*>(img.texture), NULL, NULL, &img.w, &img.h);
float w, h = 0;
SDL_GetTextureSize(static_cast<SDL_Texture*>(img.texture), &w, &h);
img.w = (int)w;
img.h = (int)h;
return true;
}
@ -116,7 +119,7 @@ bool Gui::Initialize()
// if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
// Setup SDL3
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0)
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_AUDIO) < 0)
{
printf("Error: SDL_Init(): %s\n", SDL_GetError());
return false;
@ -141,7 +144,7 @@ bool Gui::Initialize()
}*/
// Enable native IME.
SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");
// SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");
// Create window with SDL_Renderer graphics context
SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN);
@ -157,7 +160,7 @@ bool Gui::Initialize()
printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError());
return false;
}
renderer = SDL_CreateRenderer(window, nullptr, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED);
renderer = SDL_CreateRenderer(window, nullptr);
if (renderer == nullptr)
{
SDL_Log("Error: SDL_CreateRenderer(): %s\n", SDL_GetError());
@ -289,7 +292,7 @@ void Gui::EndFrame()
ImGui::Render();
ImGui_ImplSDLRenderer3_RenderDrawData(ImGui::GetDrawData()); // SDL3
ImGui_ImplSDLRenderer3_RenderDrawData(ImGui::GetDrawData(), renderer); // SDL3
// ImGui_ImplSDLRenderer2_RenderDrawData(ImGui::GetDrawData()); // SDL2
SDL_RenderPresent(renderer);

View file

@ -454,7 +454,7 @@ float MainWindow::DrawMainMenuBar()
ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Platform");
ImGui::Text("%s", SDL_GetPlatform());
ImGui::Text("CPU cores: %d", SDL_GetCPUCount());
ImGui::Text("CPU cores: %d", SDL_GetNumLogicalCPUCores());
ImGui::Text("RAM: %.2f GB", SDL_GetSystemRAM() / 1024.0f);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::Separator();
@ -831,7 +831,7 @@ void MainWindow::CloseProject()
m_nodeEditorWindow.Disable();
m_emulatorWindow.Disable();
m_codeEditorWindow.Disable();
// m_codeEditorWindow.Disable();
m_resourcesWindow.Disable();
m_PropertiesWindow.Disable();
m_cpuWindow.Disable();
@ -897,7 +897,7 @@ void MainWindow::Loop()
size.x -= 60;
vp->WorkPos = pos;
vp->WorkSize = size;
ImGui::DockSpaceOverViewport(vp);
ImGui::DockSpaceOverViewport(0, vp);
float height = DrawMainMenuBar();
// DrawStatusBar();

View file

@ -45,7 +45,7 @@ void MediaNodeWidget::Draw()
if (m_image.Valid())
{
ImGui::Image(m_image.texture, ImVec2(320, 240));
ImGui::Image(reinterpret_cast<ImTextureID>(m_image.texture), ImVec2(320, 240));
}
else
{

View file

@ -269,8 +269,10 @@ void NodeEditorWindow::Draw()
// visual feedback by changing link thickness and color.
}
}
ed::EndCreate(); // Wraps up object creation action handling.
}
ed::EndCreate(); // Wraps up object creation action handling.
// Handle deletion action

View file

@ -34,7 +34,7 @@ include(FetchContent)
FetchContent_Declare(
sdl3
GIT_REPOSITORY https://github.com/libsdl-org/SDL.git
GIT_TAG prerelease-3.1.0
GIT_TAG 78cc5c173404488d80751af226d1eaf67033bcc4 # === prerelease-3.1.0
GIT_SHALLOW TRUE
GIT_PROGRESS TRUE
)