file_path
stringlengths 21
224
| content
stringlengths 0
80.8M
|
---|---|
NVIDIA-Omniverse/PhysX/flow/external/imgui/imstb_truetype.h | // [DEAR IMGUI]
// This is a slightly modified version of stb_truetype.h 1.20.
// Mostly fixing for compiler and static analyzer warnings.
// Grep for [DEAR IMGUI] to find the changes.
// stb_truetype.h - v1.20 - public domain
// authored from 2009-2016 by Sean Barrett / RAD Game Tools
//
// This library processes TrueType files:
// parse files
// extract glyph metrics
// extract glyph shapes
// render glyphs to one-channel bitmaps with antialiasing (box filter)
// render glyphs to one-channel SDF bitmaps (signed-distance field/function)
//
// Todo:
// non-MS cmaps
// crashproof on bad data
// hinting? (no longer patented)
// cleartype-style AA?
// optimize: use simple memory allocator for intermediates
// optimize: build edge-list directly from curves
// optimize: rasterize directly from curves?
//
// ADDITIONAL CONTRIBUTORS
//
// Mikko Mononen: compound shape support, more cmap formats
// Tor Andersson: kerning, subpixel rendering
// Dougall Johnson: OpenType / Type 2 font handling
// Daniel Ribeiro Maciel: basic GPOS-based kerning
//
// Misc other:
// Ryan Gordon
// Simon Glass
// github:IntellectualKitty
// Imanol Celaya
// Daniel Ribeiro Maciel
//
// Bug/warning reports/fixes:
// "Zer" on mollyrocket Fabian "ryg" Giesen
// Cass Everitt Martins Mozeiko
// stoiko (Haemimont Games) Cap Petschulat
// Brian Hook Omar Cornut
// Walter van Niftrik github:aloucks
// David Gow Peter LaValle
// David Given Sergey Popov
// Ivan-Assen Ivanov Giumo X. Clanjor
// Anthony Pesch Higor Euripedes
// Johan Duparc Thomas Fields
// Hou Qiming Derek Vinyard
// Rob Loach Cort Stratton
// Kenney Phillis Jr. github:oyvindjam
// Brian Costabile github:vassvik
//
// VERSION HISTORY
//
// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics()
// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod
// 1.18 (2018-01-29) add missing function
// 1.17 (2017-07-23) make more arguments const; doc fix
// 1.16 (2017-07-12) SDF support
// 1.15 (2017-03-03) make more arguments const
// 1.14 (2017-01-16) num-fonts-in-TTC function
// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts
// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
// 1.11 (2016-04-02) fix unused-variable warning
// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef
// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly
// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
// variant PackFontRanges to pack and render in separate phases;
// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
// fixed an assert() bug in the new rasterizer
// replace assert() with STBTT_assert() in new rasterizer
//
// Full history can be found at the end of this file.
//
// LICENSE
//
// See end of file for license information.
//
// USAGE
//
// Include this file in whatever places need to refer to it. In ONE C/C++
// file, write:
// #define STB_TRUETYPE_IMPLEMENTATION
// before the #include of this file. This expands out the actual
// implementation into that C/C++ file.
//
// To make the implementation private to the file that generates the implementation,
// #define STBTT_STATIC
//
// Simple 3D API (don't ship this, but it's fine for tools and quick start)
// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture
// stbtt_GetBakedQuad() -- compute quad to draw for a given char
//
// Improved 3D API (more shippable):
// #include "stb_rect_pack.h" -- optional, but you really want it
// stbtt_PackBegin()
// stbtt_PackSetOversampling() -- for improved quality on small fonts
// stbtt_PackFontRanges() -- pack and renders
// stbtt_PackEnd()
// stbtt_GetPackedQuad()
//
// "Load" a font file from a memory buffer (you have to keep the buffer loaded)
// stbtt_InitFont()
// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections
// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections
//
// Render a unicode codepoint to a bitmap
// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap
// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide
// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be
//
// Character advance/positioning
// stbtt_GetCodepointHMetrics()
// stbtt_GetFontVMetrics()
// stbtt_GetFontVMetricsOS2()
// stbtt_GetCodepointKernAdvance()
//
// Starting with version 1.06, the rasterizer was replaced with a new,
// faster and generally-more-precise rasterizer. The new rasterizer more
// accurately measures pixel coverage for anti-aliasing, except in the case
// where multiple shapes overlap, in which case it overestimates the AA pixel
// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If
// this turns out to be a problem, you can re-enable the old rasterizer with
// #define STBTT_RASTERIZER_VERSION 1
// which will incur about a 15% speed hit.
//
// ADDITIONAL DOCUMENTATION
//
// Immediately after this block comment are a series of sample programs.
//
// After the sample programs is the "header file" section. This section
// includes documentation for each API function.
//
// Some important concepts to understand to use this library:
//
// Codepoint
// Characters are defined by unicode codepoints, e.g. 65 is
// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is
// the hiragana for "ma".
//
// Glyph
// A visual character shape (every codepoint is rendered as
// some glyph)
//
// Glyph index
// A font-specific integer ID representing a glyph
//
// Baseline
// Glyph shapes are defined relative to a baseline, which is the
// bottom of uppercase characters. Characters extend both above
// and below the baseline.
//
// Current Point
// As you draw text to the screen, you keep track of a "current point"
// which is the origin of each character. The current point's vertical
// position is the baseline. Even "baked fonts" use this model.
//
// Vertical Font Metrics
// The vertical qualities of the font, used to vertically position
// and space the characters. See docs for stbtt_GetFontVMetrics.
//
// Font Size in Pixels or Points
// The preferred interface for specifying font sizes in stb_truetype
// is to specify how tall the font's vertical extent should be in pixels.
// If that sounds good enough, skip the next paragraph.
//
// Most font APIs instead use "points", which are a common typographic
// measurement for describing font size, defined as 72 points per inch.
// stb_truetype provides a point API for compatibility. However, true
// "per inch" conventions don't make much sense on computer displays
// since different monitors have different number of pixels per
// inch. For example, Windows traditionally uses a convention that
// there are 96 pixels per inch, thus making 'inch' measurements have
// nothing to do with inches, and thus effectively defining a point to
// be 1.333 pixels. Additionally, the TrueType font data provides
// an explicit scale factor to scale a given font's glyphs to points,
// but the author has observed that this scale factor is often wrong
// for non-commercial fonts, thus making fonts scaled in points
// according to the TrueType spec incoherently sized in practice.
//
// DETAILED USAGE:
//
// Scale:
// Select how high you want the font to be, in points or pixels.
// Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute
// a scale factor SF that will be used by all other functions.
//
// Baseline:
// You need to select a y-coordinate that is the baseline of where
// your text will appear. Call GetFontBoundingBox to get the baseline-relative
// bounding box for all characters. SF*-y0 will be the distance in pixels
// that the worst-case character could extend above the baseline, so if
// you want the top edge of characters to appear at the top of the
// screen where y=0, then you would set the baseline to SF*-y0.
//
// Current point:
// Set the current point where the first character will appear. The
// first character could extend left of the current point; this is font
// dependent. You can either choose a current point that is the leftmost
// point and hope, or add some padding, or check the bounding box or
// left-side-bearing of the first character to be displayed and set
// the current point based on that.
//
// Displaying a character:
// Compute the bounding box of the character. It will contain signed values
// relative to <current_point, baseline>. I.e. if it returns x0,y0,x1,y1,
// then the character should be displayed in the rectangle from
// <current_point+SF*x0, baseline+SF*y0> to <current_point+SF*x1,baseline+SF*y1).
//
// Advancing for the next character:
// Call GlyphHMetrics, and compute 'current_point += SF * advance'.
//
//
// ADVANCED USAGE
//
// Quality:
//
// - Use the functions with Subpixel at the end to allow your characters
// to have subpixel positioning. Since the font is anti-aliased, not
// hinted, this is very import for quality. (This is not possible with
// baked fonts.)
//
// - Kerning is now supported, and if you're supporting subpixel rendering
// then kerning is worth using to give your text a polished look.
//
// Performance:
//
// - Convert Unicode codepoints to glyph indexes and operate on the glyphs;
// if you don't do this, stb_truetype is forced to do the conversion on
// every call.
//
// - There are a lot of memory allocations. We should modify it to take
// a temp buffer and allocate from the temp buffer (without freeing),
// should help performance a lot.
//
// NOTES
//
// The system uses the raw data found in the .ttf file without changing it
// and without building auxiliary data structures. This is a bit inefficient
// on little-endian systems (the data is big-endian), but assuming you're
// caching the bitmaps or glyph shapes this shouldn't be a big deal.
//
// It appears to be very hard to programmatically determine what font a
// given file is in a general way. I provide an API for this, but I don't
// recommend it.
//
//
// SOURCE STATISTICS (based on v0.6c, 2050 LOC)
//
// Documentation & header file 520 LOC \___ 660 LOC documentation
// Sample code 140 LOC /
// Truetype parsing 620 LOC ---- 620 LOC TrueType
// Software rasterization 240 LOC \.
// Curve tessellation 120 LOC \__ 550 LOC Bitmap creation
// Bitmap management 100 LOC /
// Baked bitmap interface 70 LOC /
// Font name matching & access 150 LOC ---- 150
// C runtime library abstraction 60 LOC ---- 60
//
//
// PERFORMANCE MEASUREMENTS FOR 1.06:
//
// 32-bit 64-bit
// Previous release: 8.83 s 7.68 s
// Pool allocations: 7.72 s 6.34 s
// Inline sort : 6.54 s 5.65 s
// New rasterizer : 5.63 s 5.00 s
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
////
//// SAMPLE PROGRAMS
////
//
// Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless
//
#if 0
#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
#include "stb_truetype.h"
unsigned char ttf_buffer[1<<20];
unsigned char temp_bitmap[512*512];
stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
GLuint ftex;
void my_stbtt_initfont(void)
{
fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!
// can free ttf_buffer at this point
glGenTextures(1, &ftex);
glBindTexture(GL_TEXTURE_2D, ftex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
// can free temp_bitmap at this point
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
void my_stbtt_print(float x, float y, char *text)
{
// assume orthographic projection with units = screen pixels, origin at top left
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, ftex);
glBegin(GL_QUADS);
while (*text) {
if (*text >= 32 && *text < 128) {
stbtt_aligned_quad q;
stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9
glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0);
glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0);
glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1);
glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1);
}
++text;
}
glEnd();
}
#endif
//
//
//////////////////////////////////////////////////////////////////////////////
//
// Complete program (this compiles): get a single bitmap, print as ASCII art
//
#if 0
#include <stdio.h>
#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
#include "stb_truetype.h"
char ttf_buffer[1<<25];
int main(int argc, char **argv)
{
stbtt_fontinfo font;
unsigned char *bitmap;
int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);
fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));
bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);
for (j=0; j < h; ++j) {
for (i=0; i < w; ++i)
putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);
putchar('\n');
}
return 0;
}
#endif
//
// Output:
//
// .ii.
// @@@@@@.
// V@Mio@@o
// :i. V@V
// :oM@@M
// :@@@MM@M
// @@o o@M
// :@@. M@M
// @@@o@@@@
// :M@@V:@@.
//
//////////////////////////////////////////////////////////////////////////////
//
// Complete program: print "Hello World!" banner, with bugs
//
#if 0
char buffer[24<<20];
unsigned char screen[20][79];
int main(int arg, char **argv)
{
stbtt_fontinfo font;
int i,j,ascent,baseline,ch=0;
float scale, xpos=2; // leave a little padding in case the character extends left
char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness
fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
stbtt_InitFont(&font, buffer, 0);
scale = stbtt_ScaleForPixelHeight(&font, 15);
stbtt_GetFontVMetrics(&font, &ascent,0,0);
baseline = (int) (ascent*scale);
while (text[ch]) {
int advance,lsb,x0,y0,x1,y1;
float x_shift = xpos - (float) floor(xpos);
stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);
// note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
// because this API is really for baking character bitmaps into textures. if you want to render
// a sequence of characters, you really need to render each bitmap to a temp buffer, then
// "alpha blend" that into the working buffer
xpos += (advance * scale);
if (text[ch+1])
xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);
++ch;
}
for (j=0; j < 20; ++j) {
for (i=0; i < 78; ++i)
putchar(" .:ioVM@"[screen[j][i]>>5]);
putchar('\n');
}
return 0;
}
#endif
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
////
//// INTEGRATION WITH YOUR CODEBASE
////
//// The following sections allow you to supply alternate definitions
//// of C library functions used by stb_truetype, e.g. if you don't
//// link with the C runtime library.
#ifdef STB_TRUETYPE_IMPLEMENTATION
// #define your own (u)stbtt_int8/16/32 before including to override this
#ifndef stbtt_uint8
typedef unsigned char stbtt_uint8;
typedef signed char stbtt_int8;
typedef unsigned short stbtt_uint16;
typedef signed short stbtt_int16;
typedef unsigned int stbtt_uint32;
typedef signed int stbtt_int32;
#endif
typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];
typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];
// e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
#ifndef STBTT_ifloor
#include <math.h>
#define STBTT_ifloor(x) ((int) floor(x))
#define STBTT_iceil(x) ((int) ceil(x))
#endif
#ifndef STBTT_sqrt
#include <math.h>
#define STBTT_sqrt(x) sqrt(x)
#define STBTT_pow(x,y) pow(x,y)
#endif
#ifndef STBTT_fmod
#include <math.h>
#define STBTT_fmod(x,y) fmod(x,y)
#endif
#ifndef STBTT_cos
#include <math.h>
#define STBTT_cos(x) cos(x)
#define STBTT_acos(x) acos(x)
#endif
#ifndef STBTT_fabs
#include <math.h>
#define STBTT_fabs(x) fabs(x)
#endif
// #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
#ifndef STBTT_malloc
#include <stdlib.h>
#define STBTT_malloc(x,u) ((void)(u),malloc(x))
#define STBTT_free(x,u) ((void)(u),free(x))
#endif
#ifndef STBTT_assert
#include <assert.h>
#define STBTT_assert(x) assert(x)
#endif
#ifndef STBTT_strlen
#include <string.h>
#define STBTT_strlen(x) strlen(x)
#endif
#ifndef STBTT_memcpy
#include <string.h>
#define STBTT_memcpy memcpy
#define STBTT_memset memset
#endif
#endif
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
////
//// INTERFACE
////
////
#ifndef __STB_INCLUDE_STB_TRUETYPE_H__
#define __STB_INCLUDE_STB_TRUETYPE_H__
#ifdef STBTT_STATIC
#define STBTT_DEF static
#else
#define STBTT_DEF extern
#endif
#ifdef __cplusplus
extern "C" {
#endif
// private structure
typedef struct
{
unsigned char *data;
int cursor;
int size;
} stbtt__buf;
//////////////////////////////////////////////////////////////////////////////
//
// TEXTURE BAKING API
//
// If you use this API, you only have to call two functions ever.
//
typedef struct
{
unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
float xoff,yoff,xadvance;
} stbtt_bakedchar;
STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)
float pixel_height, // height of font in pixels
unsigned char *pixels, int pw, int ph, // bitmap to be filled in
int first_char, int num_chars, // characters to bake
stbtt_bakedchar *chardata); // you allocate this, it's num_chars long
// if return is positive, the first unused row of the bitmap
// if return is negative, returns the negative of the number of characters that fit
// if return is 0, no characters fit and no rows were used
// This uses a very crappy packing.
typedef struct
{
float x0,y0,s0,t0; // top-left
float x1,y1,s1,t1; // bottom-right
} stbtt_aligned_quad;
STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above
int char_index, // character to display
float *xpos, float *ypos, // pointers to current position in screen pixel space
stbtt_aligned_quad *q, // output: quad to draw
int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier
// Call GetBakedQuad with char_index = 'character - first_char', and it
// creates the quad you need to draw and advances the current position.
//
// The coordinate system used assumes y increases downwards.
//
// Characters will extend both above and below the current position;
// see discussion of "BASELINE" above.
//
// It's inefficient; you might want to c&p it and optimize it.
STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap);
// Query the font vertical metrics without having to create a font first.
//////////////////////////////////////////////////////////////////////////////
//
// NEW TEXTURE BAKING API
//
// This provides options for packing multiple fonts into one atlas, not
// perfectly but better than nothing.
typedef struct
{
unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
float xoff,yoff,xadvance;
float xoff2,yoff2;
} stbtt_packedchar;
typedef struct stbtt_pack_context stbtt_pack_context;
typedef struct stbtt_fontinfo stbtt_fontinfo;
#ifndef STB_RECT_PACK_VERSION
typedef struct stbrp_rect stbrp_rect;
#endif
STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context);
// Initializes a packing context stored in the passed-in stbtt_pack_context.
// Future calls using this context will pack characters into the bitmap passed
// in here: a 1-channel bitmap that is width * height. stride_in_bytes is
// the distance from one row to the next (or 0 to mean they are packed tightly
// together). "padding" is the amount of padding to leave between each
// character (normally you want '1' for bitmaps you'll use as textures with
// bilinear filtering).
//
// Returns 0 on failure, 1 on success.
STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc);
// Cleans up the packing context and frees all memory.
#define STBTT_POINT_SIZE(x) (-(x))
STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,
int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range);
// Creates character bitmaps from the font_index'th font found in fontdata (use
// font_index=0 if you don't know what that is). It creates num_chars_in_range
// bitmaps for characters with unicode values starting at first_unicode_char_in_range
// and increasing. Data for how to render them is stored in chardata_for_range;
// pass these to stbtt_GetPackedQuad to get back renderable quads.
//
// font_size is the full height of the character from ascender to descender,
// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed
// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE()
// and pass that result as 'font_size':
// ..., 20 , ... // font max minus min y is 20 pixels tall
// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall
typedef struct
{
float font_size;
int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint
int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints
int num_chars;
stbtt_packedchar *chardata_for_range; // output
unsigned char h_oversample, v_oversample; // don't set these, they're used internally
} stbtt_pack_range;
STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);
// Creates character bitmaps from multiple ranges of characters stored in
// ranges. This will usually create a better-packed bitmap than multiple
// calls to stbtt_PackFontRange. Note that you can call this multiple
// times within a single PackBegin/PackEnd.
STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample);
// Oversampling a font increases the quality by allowing higher-quality subpixel
// positioning, and is especially valuable at smaller text sizes.
//
// This function sets the amount of oversampling for all following calls to
// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given
// pack context. The default (no oversampling) is achieved by h_oversample=1
// and v_oversample=1. The total number of pixels required is
// h_oversample*v_oversample larger than the default; for example, 2x2
// oversampling requires 4x the storage of 1x1. For best results, render
// oversampled textures with bilinear filtering. Look at the readme in
// stb/tests/oversample for information about oversampled fonts
//
// To use with PackFontRangesGather etc., you must set it before calls
// call to PackFontRangesGatherRects.
STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip);
// If skip != 0, this tells stb_truetype to skip any codepoints for which
// there is no corresponding glyph. If skip=0, which is the default, then
// codepoints without a glyph recived the font's "missing character" glyph,
// typically an empty box by convention.
STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above
int char_index, // character to display
float *xpos, float *ypos, // pointers to current position in screen pixel space
stbtt_aligned_quad *q, // output: quad to draw
int align_to_integer);
STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects);
STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
// Calling these functions in sequence is roughly equivalent to calling
// stbtt_PackFontRanges(). If you more control over the packing of multiple
// fonts, or if you want to pack custom data into a font texture, take a look
// at the source to of stbtt_PackFontRanges() and create a custom version
// using these functions, e.g. call GatherRects multiple times,
// building up a single array of rects, then call PackRects once,
// then call RenderIntoRects repeatedly. This may result in a
// better packing than calling PackFontRanges multiple times
// (or it may not).
// this is an opaque structure that you shouldn't mess with which holds
// all the context needed from PackBegin to PackEnd.
struct stbtt_pack_context {
void *user_allocator_context;
void *pack_info;
int width;
int height;
int stride_in_bytes;
int padding;
int skip_missing;
unsigned int h_oversample, v_oversample;
unsigned char *pixels;
void *nodes;
};
//////////////////////////////////////////////////////////////////////////////
//
// FONT LOADING
//
//
STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data);
// This function will determine the number of fonts in a font file. TrueType
// collection (.ttc) files may contain multiple fonts, while TrueType font
// (.ttf) files only contain one font. The number of fonts can be used for
// indexing with the previous function where the index is between zero and one
// less than the total fonts. If an error occurs, -1 is returned.
STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);
// Each .ttf/.ttc file may have more than one font. Each font has a sequential
// index number starting from 0. Call this function to get the font offset for
// a given index; it returns -1 if the index is out of range. A regular .ttf
// file will only define one font and it always be at offset 0, so it will
// return '0' for index 0, and -1 for all other indices.
// The following structure is defined publicly so you can declare one on
// the stack or as a global or etc, but you should treat it as opaque.
struct stbtt_fontinfo
{
void * userdata;
unsigned char * data; // pointer to .ttf file
int fontstart; // offset of start of font
int numGlyphs; // number of glyphs, needed for range checking
int loca,head,glyf,hhea,hmtx,kern,gpos; // table locations as offset from start of .ttf
int index_map; // a cmap mapping for our chosen character encoding
int indexToLocFormat; // format needed to map from glyph index to glyph
stbtt__buf cff; // cff font data
stbtt__buf charstrings; // the charstring index
stbtt__buf gsubrs; // global charstring subroutines index
stbtt__buf subrs; // private charstring subroutines index
stbtt__buf fontdicts; // array of font dicts
stbtt__buf fdselect; // map from glyph to fontdict
};
STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);
// Given an offset into the file that defines a font, this function builds
// the necessary cached info for the rest of the system. You must allocate
// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't
// need to do anything special to free it, because the contents are pure
// value data with no additional data structures. Returns 0 on failure.
//////////////////////////////////////////////////////////////////////////////
//
// CHARACTER TO GLYPH-INDEX CONVERSIOn
STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);
// If you're going to perform multiple operations on the same character
// and you want a speed-up, call this function with the character you're
// going to process, then use glyph-based functions instead of the
// codepoint-based functions.
// Returns 0 if the character codepoint is not defined in the font.
//////////////////////////////////////////////////////////////////////////////
//
// CHARACTER PROPERTIES
//
STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);
// computes a scale factor to produce a font whose "height" is 'pixels' tall.
// Height is measured as the distance from the highest ascender to the lowest
// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics
// and computing:
// scale = pixels / (ascent - descent)
// so if you prefer to measure height by the ascent only, use a similar calculation.
STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);
// computes a scale factor to produce a font whose EM size is mapped to
// 'pixels' tall. This is probably what traditional APIs compute, but
// I'm not positive.
STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);
// ascent is the coordinate above the baseline the font extends; descent
// is the coordinate below the baseline the font extends (i.e. it is typically negative)
// lineGap is the spacing between one row's descent and the next row's ascent...
// so you should advance the vertical position by "*ascent - *descent + *lineGap"
// these are expressed in unscaled coordinates, so you must multiply by
// the scale factor for a given size
STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap);
// analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2
// table (specific to MS/Windows TTF files).
//
// Returns 1 on success (table present), 0 on failure.
STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);
// the bounding box around all possible characters
STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);
// leftSideBearing is the offset from the current horizontal position to the left edge of the character
// advanceWidth is the offset from the current horizontal position to the next horizontal position
// these are expressed in unscaled coordinates
STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);
// an additional amount to add to the 'advance' value between ch1 and ch2
STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);
// Gets the bounding box of the visible part of the glyph, in unscaled coordinates
STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);
STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);
STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
// as above, but takes one or more glyph indices for greater efficiency
//////////////////////////////////////////////////////////////////////////////
//
// GLYPH SHAPES (you probably don't need these, but they have to go before
// the bitmaps for C declaration-order reasons)
//
#ifndef STBTT_vmove // you can predefine these to use different values (but why?)
enum {
STBTT_vmove=1,
STBTT_vline,
STBTT_vcurve,
STBTT_vcubic
};
#endif
#ifndef stbtt_vertex // you can predefine this to use different values
// (we share this with other code at RAD)
#define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file
typedef struct
{
stbtt_vertex_type x,y,cx,cy,cx1,cy1;
unsigned char type,padding;
} stbtt_vertex;
#endif
STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);
// returns non-zero if nothing is drawn for this glyph
STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);
STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);
// returns # of vertices and fills *vertices with the pointer to them
// these are expressed in "unscaled" coordinates
//
// The shape is a series of contours. Each one starts with
// a STBTT_moveto, then consists of a series of mixed
// STBTT_lineto and STBTT_curveto segments. A lineto
// draws a line from previous endpoint to its x,y; a curveto
// draws a quadratic bezier from previous endpoint to
// its x,y, using cx,cy as the bezier control point.
STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);
// frees the data allocated above
//////////////////////////////////////////////////////////////////////////////
//
// BITMAP RENDERING
//
STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);
// frees the bitmap allocated below
STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff);
// allocates a large-enough single-channel 8bpp bitmap and renders the
// specified character/glyph at the specified scale into it, with
// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).
// *width & *height are filled out with the width & height of the bitmap,
// which is stored left-to-right, top-to-bottom.
//
// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap
STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff);
// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel
// shift for the character
STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint);
// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap
// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap
// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the
// width and height and positioning info for it first.
STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint);
// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel
// shift for the character
STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint);
// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering
// is performed (see stbtt_PackSetOversampling)
STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
// get the bbox of the bitmap centered around the glyph origin; so the
// bitmap width is ix1-ix0, height is iy1-iy0, and location to place
// the bitmap top left is (leftSideBearing*scale,iy0).
// (Note that the bitmap uses y-increases-down, but the shape uses
// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)
STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);
// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel
// shift for the character
// the following functions are equivalent to the above functions, but operate
// on glyph indices instead of Unicode codepoints (for efficiency)
STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff);
STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff);
STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph);
STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph);
STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph);
STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);
// @TODO: don't expose this structure
typedef struct
{
int w,h,stride;
unsigned char *pixels;
} stbtt__bitmap;
// rasterize a shape with quadratic beziers into a bitmap
STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into
float flatness_in_pixels, // allowable error of curve in pixels
stbtt_vertex *vertices, // array of vertices defining shape
int num_verts, // number of vertices in above array
float scale_x, float scale_y, // scale applied to input vertices
float shift_x, float shift_y, // translation applied to input vertices
int x_off, int y_off, // another translation applied to input
int invert, // if non-zero, vertically flip shape
void *userdata); // context for to STBTT_MALLOC
//////////////////////////////////////////////////////////////////////////////
//
// Signed Distance Function (or Field) rendering
STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata);
// frees the SDF bitmap allocated below
STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);
STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);
// These functions compute a discretized SDF field for a single character, suitable for storing
// in a single-channel texture, sampling with bilinear filtering, and testing against
// larger than some threshold to produce scalable fonts.
// info -- the font
// scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap
// glyph/codepoint -- the character to generate the SDF for
// padding -- extra "pixels" around the character which are filled with the distance to the character (not 0),
// which allows effects like bit outlines
// onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character)
// pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale)
// if positive, > onedge_value is inside; if negative, < onedge_value is inside
// width,height -- output height & width of the SDF bitmap (including padding)
// xoff,yoff -- output origin of the character
// return value -- a 2D array of bytes 0..255, width*height in size
//
// pixel_dist_scale & onedge_value are a scale & bias that allows you to make
// optimal use of the limited 0..255 for your application, trading off precision
// and special effects. SDF values outside the range 0..255 are clamped to 0..255.
//
// Example:
// scale = stbtt_ScaleForPixelHeight(22)
// padding = 5
// onedge_value = 180
// pixel_dist_scale = 180/5.0 = 36.0
//
// This will create an SDF bitmap in which the character is about 22 pixels
// high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled
// shape, sample the SDF at each pixel and fill the pixel if the SDF value
// is greater than or equal to 180/255. (You'll actually want to antialias,
// which is beyond the scope of this example.) Additionally, you can compute
// offset outlines (e.g. to stroke the character border inside & outside,
// or only outside). For example, to fill outside the character up to 3 SDF
// pixels, you would compare against (180-36.0*3)/255 = 72/255. The above
// choice of variables maps a range from 5 pixels outside the shape to
// 2 pixels inside the shape to 0..255; this is intended primarily for apply
// outside effects only (the interior range is needed to allow proper
// antialiasing of the font at *smaller* sizes)
//
// The function computes the SDF analytically at each SDF pixel, not by e.g.
// building a higher-res bitmap and approximating it. In theory the quality
// should be as high as possible for an SDF of this size & representation, but
// unclear if this is true in practice (perhaps building a higher-res bitmap
// and computing from that can allow drop-out prevention).
//
// The algorithm has not been optimized at all, so expect it to be slow
// if computing lots of characters or very large sizes.
//////////////////////////////////////////////////////////////////////////////
//
// Finding the right font...
//
// You should really just solve this offline, keep your own tables
// of what font is what, and don't try to get it out of the .ttf file.
// That's because getting it out of the .ttf file is really hard, because
// the names in the file can appear in many possible encodings, in many
// possible languages, and e.g. if you need a case-insensitive comparison,
// the details of that depend on the encoding & language in a complex way
// (actually underspecified in truetype, but also gigantic).
//
// But you can use the provided functions in two possible ways:
// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on
// unicode-encoded names to try to find the font you want;
// you can run this before calling stbtt_InitFont()
//
// stbtt_GetFontNameString() lets you get any of the various strings
// from the file yourself and do your own comparisons on them.
// You have to have called stbtt_InitFont() first.
STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);
// returns the offset (not index) of the font that matches, or -1 if none
// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".
// if you use any other flag, use a font name like "Arial"; this checks
// the 'macStyle' header field; i don't know if fonts set this consistently
#define STBTT_MACSTYLE_DONTCARE 0
#define STBTT_MACSTYLE_BOLD 1
#define STBTT_MACSTYLE_ITALIC 2
#define STBTT_MACSTYLE_UNDERSCORE 4
#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0
STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);
// returns 1/0 whether the first string interpreted as utf8 is identical to
// the second string interpreted as big-endian utf16... useful for strings from next func
STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);
// returns the string (which may be big-endian double byte, e.g. for unicode)
// and puts the length in bytes in *length.
//
// some of the values for the IDs are below; for more see the truetype spec:
// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html
// http://www.microsoft.com/typography/otspec/name.htm
enum { // platformID
STBTT_PLATFORM_ID_UNICODE =0,
STBTT_PLATFORM_ID_MAC =1,
STBTT_PLATFORM_ID_ISO =2,
STBTT_PLATFORM_ID_MICROSOFT =3
};
enum { // encodingID for STBTT_PLATFORM_ID_UNICODE
STBTT_UNICODE_EID_UNICODE_1_0 =0,
STBTT_UNICODE_EID_UNICODE_1_1 =1,
STBTT_UNICODE_EID_ISO_10646 =2,
STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,
STBTT_UNICODE_EID_UNICODE_2_0_FULL=4
};
enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT
STBTT_MS_EID_SYMBOL =0,
STBTT_MS_EID_UNICODE_BMP =1,
STBTT_MS_EID_SHIFTJIS =2,
STBTT_MS_EID_UNICODE_FULL =10
};
enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes
STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4,
STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5,
STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6,
STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7
};
enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...
// problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs
STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410,
STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411,
STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412,
STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419,
STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409,
STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D
};
enum { // languageID for STBTT_PLATFORM_ID_MAC
STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11,
STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23,
STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32,
STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 ,
STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 ,
STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,
STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19
};
#ifdef __cplusplus
}
#endif
#endif // __STB_INCLUDE_STB_TRUETYPE_H__
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
////
//// IMPLEMENTATION
////
////
#ifdef STB_TRUETYPE_IMPLEMENTATION
#ifndef STBTT_MAX_OVERSAMPLE
#define STBTT_MAX_OVERSAMPLE 8
#endif
#if STBTT_MAX_OVERSAMPLE > 255
#error "STBTT_MAX_OVERSAMPLE cannot be > 255"
#endif
typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1];
#ifndef STBTT_RASTERIZER_VERSION
#define STBTT_RASTERIZER_VERSION 2
#endif
#ifdef _MSC_VER
#define STBTT__NOTUSED(v) (void)(v)
#else
#define STBTT__NOTUSED(v) (void)sizeof(v)
#endif
//////////////////////////////////////////////////////////////////////////
//
// stbtt__buf helpers to parse data from file
//
static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b)
{
if (b->cursor >= b->size)
return 0;
return b->data[b->cursor++];
}
static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b)
{
if (b->cursor >= b->size)
return 0;
return b->data[b->cursor];
}
static void stbtt__buf_seek(stbtt__buf *b, int o)
{
STBTT_assert(!(o > b->size || o < 0));
b->cursor = (o > b->size || o < 0) ? b->size : o;
}
static void stbtt__buf_skip(stbtt__buf *b, int o)
{
stbtt__buf_seek(b, b->cursor + o);
}
static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n)
{
stbtt_uint32 v = 0;
int i;
STBTT_assert(n >= 1 && n <= 4);
for (i = 0; i < n; i++)
v = (v << 8) | stbtt__buf_get8(b);
return v;
}
static stbtt__buf stbtt__new_buf(const void *p, size_t size)
{
stbtt__buf r;
STBTT_assert(size < 0x40000000);
r.data = (stbtt_uint8*) p;
r.size = (int) size;
r.cursor = 0;
return r;
}
#define stbtt__buf_get16(b) stbtt__buf_get((b), 2)
#define stbtt__buf_get32(b) stbtt__buf_get((b), 4)
static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s)
{
stbtt__buf r = stbtt__new_buf(NULL, 0);
if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r;
r.data = b->data + o;
r.size = s;
return r;
}
static stbtt__buf stbtt__cff_get_index(stbtt__buf *b)
{
int count, start, offsize;
start = b->cursor;
count = stbtt__buf_get16(b);
if (count) {
offsize = stbtt__buf_get8(b);
STBTT_assert(offsize >= 1 && offsize <= 4);
stbtt__buf_skip(b, offsize * count);
stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1);
}
return stbtt__buf_range(b, start, b->cursor - start);
}
static stbtt_uint32 stbtt__cff_int(stbtt__buf *b)
{
int b0 = stbtt__buf_get8(b);
if (b0 >= 32 && b0 <= 246) return b0 - 139;
else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108;
else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108;
else if (b0 == 28) return stbtt__buf_get16(b);
else if (b0 == 29) return stbtt__buf_get32(b);
STBTT_assert(0);
return 0;
}
static void stbtt__cff_skip_operand(stbtt__buf *b) {
int v, b0 = stbtt__buf_peek8(b);
STBTT_assert(b0 >= 28);
if (b0 == 30) {
stbtt__buf_skip(b, 1);
while (b->cursor < b->size) {
v = stbtt__buf_get8(b);
if ((v & 0xF) == 0xF || (v >> 4) == 0xF)
break;
}
} else {
stbtt__cff_int(b);
}
}
static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key)
{
stbtt__buf_seek(b, 0);
while (b->cursor < b->size) {
int start = b->cursor, end, op;
while (stbtt__buf_peek8(b) >= 28)
stbtt__cff_skip_operand(b);
end = b->cursor;
op = stbtt__buf_get8(b);
if (op == 12) op = stbtt__buf_get8(b) | 0x100;
if (op == key) return stbtt__buf_range(b, start, end-start);
}
return stbtt__buf_range(b, 0, 0);
}
static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out)
{
int i;
stbtt__buf operands = stbtt__dict_get(b, key);
for (i = 0; i < outcount && operands.cursor < operands.size; i++)
out[i] = stbtt__cff_int(&operands);
}
static int stbtt__cff_index_count(stbtt__buf *b)
{
stbtt__buf_seek(b, 0);
return stbtt__buf_get16(b);
}
static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i)
{
int count, offsize, start, end;
stbtt__buf_seek(&b, 0);
count = stbtt__buf_get16(&b);
offsize = stbtt__buf_get8(&b);
STBTT_assert(i >= 0 && i < count);
STBTT_assert(offsize >= 1 && offsize <= 4);
stbtt__buf_skip(&b, i*offsize);
start = stbtt__buf_get(&b, offsize);
end = stbtt__buf_get(&b, offsize);
return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start);
}
//////////////////////////////////////////////////////////////////////////
//
// accessors to parse data from file
//
// on platforms that don't allow misaligned reads, if we want to allow
// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE
#define ttBYTE(p) (* (stbtt_uint8 *) (p))
#define ttCHAR(p) (* (stbtt_int8 *) (p))
#define ttFixed(p) ttLONG(p)
static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }
static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }
static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))
#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3])
static int stbtt__isfont(stbtt_uint8 *font)
{
// check the version number
if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1
if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this!
if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF
if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0
if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts
return 0;
}
// @OPTIMIZE: binary search
static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)
{
stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);
stbtt_uint32 tabledir = fontstart + 12;
stbtt_int32 i;
for (i=0; i < num_tables; ++i) {
stbtt_uint32 loc = tabledir + 16*i;
if (stbtt_tag(data+loc+0, tag))
return ttULONG(data+loc+8);
}
return 0;
}
static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index)
{
// if it's just a font, there's only one valid index
if (stbtt__isfont(font_collection))
return index == 0 ? 0 : -1;
// check if it's a TTC
if (stbtt_tag(font_collection, "ttcf")) {
// version 1?
if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
stbtt_int32 n = ttLONG(font_collection+8);
if (index >= n)
return -1;
return ttULONG(font_collection+12+index*4);
}
}
return -1;
}
static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection)
{
// if it's just a font, there's only one valid font
if (stbtt__isfont(font_collection))
return 1;
// check if it's a TTC
if (stbtt_tag(font_collection, "ttcf")) {
// version 1?
if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
return ttLONG(font_collection+8);
}
}
return 0;
}
static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict)
{
stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 };
stbtt__buf pdict;
stbtt__dict_get_ints(&fontdict, 18, 2, private_loc);
if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0);
pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]);
stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff);
if (!subrsoff) return stbtt__new_buf(NULL, 0);
stbtt__buf_seek(&cff, private_loc[1]+subrsoff);
return stbtt__cff_get_index(&cff);
}
static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart)
{
stbtt_uint32 cmap, t;
stbtt_int32 i,numTables;
info->data = data;
info->fontstart = fontstart;
info->cff = stbtt__new_buf(NULL, 0);
cmap = stbtt__find_table(data, fontstart, "cmap"); // required
info->loca = stbtt__find_table(data, fontstart, "loca"); // required
info->head = stbtt__find_table(data, fontstart, "head"); // required
info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required
info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required
info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required
info->kern = stbtt__find_table(data, fontstart, "kern"); // not required
info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required
if (!cmap || !info->head || !info->hhea || !info->hmtx)
return 0;
if (info->glyf) {
// required for truetype
if (!info->loca) return 0;
} else {
// initialization for CFF / Type2 fonts (OTF)
stbtt__buf b, topdict, topdictidx;
stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0;
stbtt_uint32 cff;
cff = stbtt__find_table(data, fontstart, "CFF ");
if (!cff) return 0;
info->fontdicts = stbtt__new_buf(NULL, 0);
info->fdselect = stbtt__new_buf(NULL, 0);
// @TODO this should use size from table (not 512MB)
info->cff = stbtt__new_buf(data+cff, 512*1024*1024);
b = info->cff;
// read the header
stbtt__buf_skip(&b, 2);
stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize
// @TODO the name INDEX could list multiple fonts,
// but we just use the first one.
stbtt__cff_get_index(&b); // name INDEX
topdictidx = stbtt__cff_get_index(&b);
topdict = stbtt__cff_index_get(topdictidx, 0);
stbtt__cff_get_index(&b); // string INDEX
info->gsubrs = stbtt__cff_get_index(&b);
stbtt__dict_get_ints(&topdict, 17, 1, &charstrings);
stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype);
stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff);
stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff);
info->subrs = stbtt__get_subrs(b, topdict);
// we only support Type 2 charstrings
if (cstype != 2) return 0;
if (charstrings == 0) return 0;
if (fdarrayoff) {
// looks like a CID font
if (!fdselectoff) return 0;
stbtt__buf_seek(&b, fdarrayoff);
info->fontdicts = stbtt__cff_get_index(&b);
info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff);
}
stbtt__buf_seek(&b, charstrings);
info->charstrings = stbtt__cff_get_index(&b);
}
t = stbtt__find_table(data, fontstart, "maxp");
if (t)
info->numGlyphs = ttUSHORT(data+t+4);
else
info->numGlyphs = 0xffff;
// find a cmap encoding table we understand *now* to avoid searching
// later. (todo: could make this installable)
// the same regardless of glyph.
numTables = ttUSHORT(data + cmap + 2);
info->index_map = 0;
for (i=0; i < numTables; ++i) {
stbtt_uint32 encoding_record = cmap + 4 + 8 * i;
// find an encoding we understand:
switch(ttUSHORT(data+encoding_record)) {
case STBTT_PLATFORM_ID_MICROSOFT:
switch (ttUSHORT(data+encoding_record+2)) {
case STBTT_MS_EID_UNICODE_BMP:
case STBTT_MS_EID_UNICODE_FULL:
// MS/Unicode
info->index_map = cmap + ttULONG(data+encoding_record+4);
break;
}
break;
case STBTT_PLATFORM_ID_UNICODE:
// Mac/iOS has these
// all the encodingIDs are unicode, so we don't bother to check it
info->index_map = cmap + ttULONG(data+encoding_record+4);
break;
}
}
if (info->index_map == 0)
return 0;
info->indexToLocFormat = ttUSHORT(data+info->head + 50);
return 1;
}
STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)
{
stbtt_uint8 *data = info->data;
stbtt_uint32 index_map = info->index_map;
stbtt_uint16 format = ttUSHORT(data + index_map + 0);
if (format == 0) { // apple byte encoding
stbtt_int32 bytes = ttUSHORT(data + index_map + 2);
if (unicode_codepoint < bytes-6)
return ttBYTE(data + index_map + 6 + unicode_codepoint);
return 0;
} else if (format == 6) {
stbtt_uint32 first = ttUSHORT(data + index_map + 6);
stbtt_uint32 count = ttUSHORT(data + index_map + 8);
if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)
return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);
return 0;
} else if (format == 2) {
STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean
return 0;
} else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges
stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;
stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;
stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);
stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;
// do a binary search of the segments
stbtt_uint32 endCount = index_map + 14;
stbtt_uint32 search = endCount;
if (unicode_codepoint > 0xffff)
return 0;
// they lie from endCount .. endCount + segCount
// but searchRange is the nearest power of two, so...
if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))
search += rangeShift*2;
// now decrement to bias correctly to find smallest
search -= 2;
while (entrySelector) {
stbtt_uint16 end;
searchRange >>= 1;
end = ttUSHORT(data + search + searchRange*2);
if (unicode_codepoint > end)
search += searchRange*2;
--entrySelector;
}
search += 2;
{
stbtt_uint16 offset, start;
stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1);
STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item));
start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);
if (unicode_codepoint < start)
return 0;
offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);
if (offset == 0)
return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));
return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);
}
} else if (format == 12 || format == 13) {
stbtt_uint32 ngroups = ttULONG(data+index_map+12);
stbtt_int32 low,high;
low = 0; high = (stbtt_int32)ngroups;
// Binary search the right group.
while (low < high) {
stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high
stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);
stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);
if ((stbtt_uint32) unicode_codepoint < start_char)
high = mid;
else if ((stbtt_uint32) unicode_codepoint > end_char)
low = mid+1;
else {
stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);
if (format == 12)
return start_glyph + unicode_codepoint-start_char;
else // format == 13
return start_glyph;
}
}
return 0; // not found
}
// @TODO
STBTT_assert(0);
return 0;
}
STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)
{
return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);
}
static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)
{
v->type = type;
v->x = (stbtt_int16) x;
v->y = (stbtt_int16) y;
v->cx = (stbtt_int16) cx;
v->cy = (stbtt_int16) cy;
}
static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)
{
int g1,g2;
STBTT_assert(!info->cff.size);
if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range
if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format
if (info->indexToLocFormat == 0) {
g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;
g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;
} else {
g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);
g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);
}
return g1==g2 ? -1 : g1; // if length is 0, return -1
}
static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
{
if (info->cff.size) {
stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1);
} else {
int g = stbtt__GetGlyfOffset(info, glyph_index);
if (g < 0) return 0;
if (x0) *x0 = ttSHORT(info->data + g + 2);
if (y0) *y0 = ttSHORT(info->data + g + 4);
if (x1) *x1 = ttSHORT(info->data + g + 6);
if (y1) *y1 = ttSHORT(info->data + g + 8);
}
return 1;
}
STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)
{
return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);
}
STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)
{
stbtt_int16 numberOfContours;
int g;
if (info->cff.size)
return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0;
g = stbtt__GetGlyfOffset(info, glyph_index);
if (g < 0) return 1;
numberOfContours = ttSHORT(info->data + g);
return numberOfContours == 0;
}
static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,
stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)
{
if (start_off) {
if (was_off)
stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);
stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);
} else {
if (was_off)
stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);
else
stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);
}
return num_vertices;
}
static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
{
stbtt_int16 numberOfContours;
stbtt_uint8 *endPtsOfContours;
stbtt_uint8 *data = info->data;
stbtt_vertex *vertices=0;
int num_vertices=0;
int g = stbtt__GetGlyfOffset(info, glyph_index);
*pvertices = NULL;
if (g < 0) return 0;
numberOfContours = ttSHORT(data + g);
if (numberOfContours > 0) {
stbtt_uint8 flags=0,flagcount;
stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;
stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;
stbtt_uint8 *points;
endPtsOfContours = (data + g + 10);
ins = ttUSHORT(data + g + 10 + numberOfContours * 2);
points = data + g + 10 + numberOfContours * 2 + 2 + ins;
n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);
m = n + 2*numberOfContours; // a loose bound on how many vertices we might need
vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);
if (vertices == 0)
return 0;
next_move = 0;
flagcount=0;
// in first pass, we load uninterpreted data into the allocated array
// above, shifted to the end of the array so we won't overwrite it when
// we create our final data starting from the front
off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated
// first load flags
for (i=0; i < n; ++i) {
if (flagcount == 0) {
flags = *points++;
if (flags & 8)
flagcount = *points++;
} else
--flagcount;
vertices[off+i].type = flags;
}
// now load x coordinates
x=0;
for (i=0; i < n; ++i) {
flags = vertices[off+i].type;
if (flags & 2) {
stbtt_int16 dx = *points++;
x += (flags & 16) ? dx : -dx; // ???
} else {
if (!(flags & 16)) {
x = x + (stbtt_int16) (points[0]*256 + points[1]);
points += 2;
}
}
vertices[off+i].x = (stbtt_int16) x;
}
// now load y coordinates
y=0;
for (i=0; i < n; ++i) {
flags = vertices[off+i].type;
if (flags & 4) {
stbtt_int16 dy = *points++;
y += (flags & 32) ? dy : -dy; // ???
} else {
if (!(flags & 32)) {
y = y + (stbtt_int16) (points[0]*256 + points[1]);
points += 2;
}
}
vertices[off+i].y = (stbtt_int16) y;
}
// now convert them to our format
num_vertices=0;
sx = sy = cx = cy = scx = scy = 0;
for (i=0; i < n; ++i) {
flags = vertices[off+i].type;
x = (stbtt_int16) vertices[off+i].x;
y = (stbtt_int16) vertices[off+i].y;
if (next_move == i) {
if (i != 0)
num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
// now start the new one
start_off = !(flags & 1);
if (start_off) {
// if we start off with an off-curve point, then when we need to find a point on the curve
// where we can start, and we need to save some state for when we wraparound.
scx = x;
scy = y;
if (!(vertices[off+i+1].type & 1)) {
// next point is also a curve point, so interpolate an on-point curve
sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;
sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;
} else {
// otherwise just use the next point as our start point
sx = (stbtt_int32) vertices[off+i+1].x;
sy = (stbtt_int32) vertices[off+i+1].y;
++i; // we're using point i+1 as the starting point, so skip it
}
} else {
sx = x;
sy = y;
}
stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);
was_off = 0;
next_move = 1 + ttUSHORT(endPtsOfContours+j*2);
++j;
} else {
if (!(flags & 1)) { // if it's a curve
if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint
stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);
cx = x;
cy = y;
was_off = 1;
} else {
if (was_off)
stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);
else
stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);
was_off = 0;
}
}
}
num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
} else if (numberOfContours == -1) {
// Compound shapes.
int more = 1;
stbtt_uint8 *comp = data + g + 10;
num_vertices = 0;
vertices = 0;
while (more) {
stbtt_uint16 flags, gidx;
int comp_num_verts = 0, i;
stbtt_vertex *comp_verts = 0, *tmp = 0;
float mtx[6] = {1,0,0,1,0,0}, m, n;
flags = ttSHORT(comp); comp+=2;
gidx = ttSHORT(comp); comp+=2;
if (flags & 2) { // XY values
if (flags & 1) { // shorts
mtx[4] = ttSHORT(comp); comp+=2;
mtx[5] = ttSHORT(comp); comp+=2;
} else {
mtx[4] = ttCHAR(comp); comp+=1;
mtx[5] = ttCHAR(comp); comp+=1;
}
}
else {
// @TODO handle matching point
STBTT_assert(0);
}
if (flags & (1<<3)) { // WE_HAVE_A_SCALE
mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
mtx[1] = mtx[2] = 0;
} else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE
mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
mtx[1] = mtx[2] = 0;
mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
} else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO
mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;
mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;
mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
}
// Find transformation scales.
m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);
n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);
// Get indexed glyph.
comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);
if (comp_num_verts > 0) {
// Transform vertices.
for (i = 0; i < comp_num_verts; ++i) {
stbtt_vertex* v = &comp_verts[i];
stbtt_vertex_type x,y;
x=v->x; y=v->y;
v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
x=v->cx; y=v->cy;
v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
}
// Append vertices.
tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);
if (!tmp) {
if (vertices) STBTT_free(vertices, info->userdata);
if (comp_verts) STBTT_free(comp_verts, info->userdata);
return 0;
}
if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); //-V595
STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));
if (vertices) STBTT_free(vertices, info->userdata);
vertices = tmp;
STBTT_free(comp_verts, info->userdata);
num_vertices += comp_num_verts;
}
// More components ?
more = flags & (1<<5);
}
} else if (numberOfContours < 0) {
// @TODO other compound variations?
STBTT_assert(0);
} else {
// numberOfCounters == 0, do nothing
}
*pvertices = vertices;
return num_vertices;
}
typedef struct
{
int bounds;
int started;
float first_x, first_y;
float x, y;
stbtt_int32 min_x, max_x, min_y, max_y;
stbtt_vertex *pvertices;
int num_vertices;
} stbtt__csctx;
#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0}
static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y)
{
if (x > c->max_x || !c->started) c->max_x = x;
if (y > c->max_y || !c->started) c->max_y = y;
if (x < c->min_x || !c->started) c->min_x = x;
if (y < c->min_y || !c->started) c->min_y = y;
c->started = 1;
}
static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1)
{
if (c->bounds) {
stbtt__track_vertex(c, x, y);
if (type == STBTT_vcubic) {
stbtt__track_vertex(c, cx, cy);
stbtt__track_vertex(c, cx1, cy1);
}
} else {
stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy);
c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1;
c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1;
}
c->num_vertices++;
}
static void stbtt__csctx_close_shape(stbtt__csctx *ctx)
{
if (ctx->first_x != ctx->x || ctx->first_y != ctx->y)
stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0);
}
static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy)
{
stbtt__csctx_close_shape(ctx);
ctx->first_x = ctx->x = ctx->x + dx;
ctx->first_y = ctx->y = ctx->y + dy;
stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
}
static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy)
{
ctx->x += dx;
ctx->y += dy;
stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
}
static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3)
{
float cx1 = ctx->x + dx1;
float cy1 = ctx->y + dy1;
float cx2 = cx1 + dx2;
float cy2 = cy1 + dy2;
ctx->x = cx2 + dx3;
ctx->y = cy2 + dy3;
stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2);
}
static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n)
{
int count = stbtt__cff_index_count(&idx);
int bias = 107;
if (count >= 33900)
bias = 32768;
else if (count >= 1240)
bias = 1131;
n += bias;
if (n < 0 || n >= count)
return stbtt__new_buf(NULL, 0);
return stbtt__cff_index_get(idx, n);
}
static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index)
{
stbtt__buf fdselect = info->fdselect;
int nranges, start, end, v, fmt, fdselector = -1, i;
stbtt__buf_seek(&fdselect, 0);
fmt = stbtt__buf_get8(&fdselect);
if (fmt == 0) {
// untested
stbtt__buf_skip(&fdselect, glyph_index);
fdselector = stbtt__buf_get8(&fdselect);
} else if (fmt == 3) {
nranges = stbtt__buf_get16(&fdselect);
start = stbtt__buf_get16(&fdselect);
for (i = 0; i < nranges; i++) {
v = stbtt__buf_get8(&fdselect);
end = stbtt__buf_get16(&fdselect);
if (glyph_index >= start && glyph_index < end) {
fdselector = v;
break;
}
start = end;
}
}
if (fdselector == -1) stbtt__new_buf(NULL, 0);
return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector));
}
static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c)
{
int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0;
int has_subrs = 0, clear_stack;
float s[48];
stbtt__buf subr_stack[10], subrs = info->subrs, b;
float f;
#define STBTT__CSERR(s) (0)
// this currently ignores the initial width value, which isn't needed if we have hmtx
b = stbtt__cff_index_get(info->charstrings, glyph_index);
while (b.cursor < b.size) {
i = 0;
clear_stack = 1;
b0 = stbtt__buf_get8(&b);
switch (b0) {
// @TODO implement hinting
case 0x13: // hintmask
case 0x14: // cntrmask
if (in_header)
maskbits += (sp / 2); // implicit "vstem"
in_header = 0;
stbtt__buf_skip(&b, (maskbits + 7) / 8);
break;
case 0x01: // hstem
case 0x03: // vstem
case 0x12: // hstemhm
case 0x17: // vstemhm
maskbits += (sp / 2);
break;
case 0x15: // rmoveto
in_header = 0;
if (sp < 2) return STBTT__CSERR("rmoveto stack");
stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]);
break;
case 0x04: // vmoveto
in_header = 0;
if (sp < 1) return STBTT__CSERR("vmoveto stack");
stbtt__csctx_rmove_to(c, 0, s[sp-1]);
break;
case 0x16: // hmoveto
in_header = 0;
if (sp < 1) return STBTT__CSERR("hmoveto stack");
stbtt__csctx_rmove_to(c, s[sp-1], 0);
break;
case 0x05: // rlineto
if (sp < 2) return STBTT__CSERR("rlineto stack");
for (; i + 1 < sp; i += 2)
stbtt__csctx_rline_to(c, s[i], s[i+1]);
break;
// hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical
// starting from a different place.
case 0x07: // vlineto
if (sp < 1) return STBTT__CSERR("vlineto stack");
goto vlineto;
case 0x06: // hlineto
if (sp < 1) return STBTT__CSERR("hlineto stack");
for (;;) {
if (i >= sp) break;
stbtt__csctx_rline_to(c, s[i], 0);
i++;
vlineto:
if (i >= sp) break;
stbtt__csctx_rline_to(c, 0, s[i]);
i++;
}
break;
case 0x1F: // hvcurveto
if (sp < 4) return STBTT__CSERR("hvcurveto stack");
goto hvcurveto;
case 0x1E: // vhcurveto
if (sp < 4) return STBTT__CSERR("vhcurveto stack");
for (;;) {
if (i + 3 >= sp) break;
stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f);
i += 4;
hvcurveto:
if (i + 3 >= sp) break;
stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]);
i += 4;
}
break;
case 0x08: // rrcurveto
if (sp < 6) return STBTT__CSERR("rcurveline stack");
for (; i + 5 < sp; i += 6)
stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
break;
case 0x18: // rcurveline
if (sp < 8) return STBTT__CSERR("rcurveline stack");
for (; i + 5 < sp - 2; i += 6)
stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack");
stbtt__csctx_rline_to(c, s[i], s[i+1]);
break;
case 0x19: // rlinecurve
if (sp < 8) return STBTT__CSERR("rlinecurve stack");
for (; i + 1 < sp - 6; i += 2)
stbtt__csctx_rline_to(c, s[i], s[i+1]);
if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack");
stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
break;
case 0x1A: // vvcurveto
case 0x1B: // hhcurveto
if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack");
f = 0.0;
if (sp & 1) { f = s[i]; i++; }
for (; i + 3 < sp; i += 4) {
if (b0 == 0x1B)
stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0);
else
stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]);
f = 0.0;
}
break;
case 0x0A: // callsubr
if (!has_subrs) {
if (info->fdselect.size)
subrs = stbtt__cid_get_glyph_subrs(info, glyph_index);
has_subrs = 1;
}
// fallthrough
case 0x1D: // callgsubr
if (sp < 1) return STBTT__CSERR("call(g|)subr stack");
v = (int) s[--sp];
if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit");
subr_stack[subr_stack_height++] = b;
b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v);
if (b.size == 0) return STBTT__CSERR("subr not found");
b.cursor = 0;
clear_stack = 0;
break;
case 0x0B: // return
if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr");
b = subr_stack[--subr_stack_height];
clear_stack = 0;
break;
case 0x0E: // endchar
stbtt__csctx_close_shape(c);
return 1;
case 0x0C: { // two-byte escape
float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6;
float dx, dy;
int b1 = stbtt__buf_get8(&b);
switch (b1) {
// @TODO These "flex" implementations ignore the flex-depth and resolution,
// and always draw beziers.
case 0x22: // hflex
if (sp < 7) return STBTT__CSERR("hflex stack");
dx1 = s[0];
dx2 = s[1];
dy2 = s[2];
dx3 = s[3];
dx4 = s[4];
dx5 = s[5];
dx6 = s[6];
stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0);
stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0);
break;
case 0x23: // flex
if (sp < 13) return STBTT__CSERR("flex stack");
dx1 = s[0];
dy1 = s[1];
dx2 = s[2];
dy2 = s[3];
dx3 = s[4];
dy3 = s[5];
dx4 = s[6];
dy4 = s[7];
dx5 = s[8];
dy5 = s[9];
dx6 = s[10];
dy6 = s[11];
//fd is s[12]
stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
break;
case 0x24: // hflex1
if (sp < 9) return STBTT__CSERR("hflex1 stack");
dx1 = s[0];
dy1 = s[1];
dx2 = s[2];
dy2 = s[3];
dx3 = s[4];
dx4 = s[5];
dx5 = s[6];
dy5 = s[7];
dx6 = s[8];
stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0);
stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5));
break;
case 0x25: // flex1
if (sp < 11) return STBTT__CSERR("flex1 stack");
dx1 = s[0];
dy1 = s[1];
dx2 = s[2];
dy2 = s[3];
dx3 = s[4];
dy3 = s[5];
dx4 = s[6];
dy4 = s[7];
dx5 = s[8];
dy5 = s[9];
dx6 = dy6 = s[10];
dx = dx1+dx2+dx3+dx4+dx5;
dy = dy1+dy2+dy3+dy4+dy5;
if (STBTT_fabs(dx) > STBTT_fabs(dy))
dy6 = -dy;
else
dx6 = -dx;
stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
break;
default:
return STBTT__CSERR("unimplemented");
}
} break;
default:
if (b0 != 255 && b0 != 28 && (b0 < 32 || b0 > 254)) //-V560
return STBTT__CSERR("reserved operator");
// push immediate
if (b0 == 255) {
f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000;
} else {
stbtt__buf_skip(&b, -1);
f = (float)(stbtt_int16)stbtt__cff_int(&b);
}
if (sp >= 48) return STBTT__CSERR("push stack overflow");
s[sp++] = f;
clear_stack = 0;
break;
}
if (clear_stack) sp = 0;
}
return STBTT__CSERR("no endchar");
#undef STBTT__CSERR
}
static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
{
// runs the charstring twice, once to count and once to output (to avoid realloc)
stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1);
stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0);
if (stbtt__run_charstring(info, glyph_index, &count_ctx)) {
*pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata);
output_ctx.pvertices = *pvertices;
if (stbtt__run_charstring(info, glyph_index, &output_ctx)) {
STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices);
return output_ctx.num_vertices;
}
}
*pvertices = NULL;
return 0;
}
static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
{
stbtt__csctx c = STBTT__CSCTX_INIT(1);
int r = stbtt__run_charstring(info, glyph_index, &c);
if (x0) *x0 = r ? c.min_x : 0;
if (y0) *y0 = r ? c.min_y : 0;
if (x1) *x1 = r ? c.max_x : 0;
if (y1) *y1 = r ? c.max_y : 0;
return r ? c.num_vertices : 0;
}
STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
{
if (!info->cff.size)
return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices);
else
return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices);
}
STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)
{
stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);
if (glyph_index < numOfLongHorMetrics) {
if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index);
if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);
} else {
if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));
if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));
}
}
static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
{
stbtt_uint8 *data = info->data + info->kern;
stbtt_uint32 needle, straw;
int l, r, m;
// we only look at the first table. it must be 'horizontal' and format 0.
if (!info->kern)
return 0;
if (ttUSHORT(data+2) < 1) // number of tables, need at least 1
return 0;
if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format
return 0;
l = 0;
r = ttUSHORT(data+10) - 1;
needle = glyph1 << 16 | glyph2;
while (l <= r) {
m = (l + r) >> 1;
straw = ttULONG(data+18+(m*6)); // note: unaligned read
if (needle < straw)
r = m - 1;
else if (needle > straw)
l = m + 1;
else
return ttSHORT(data+22+(m*6));
}
return 0;
}
static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph)
{
stbtt_uint16 coverageFormat = ttUSHORT(coverageTable);
switch(coverageFormat) {
case 1: {
stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2);
// Binary search.
stbtt_int32 l=0, r=glyphCount-1, m;
int straw, needle=glyph;
while (l <= r) {
stbtt_uint8 *glyphArray = coverageTable + 4;
stbtt_uint16 glyphID;
m = (l + r) >> 1;
glyphID = ttUSHORT(glyphArray + 2 * m);
straw = glyphID;
if (needle < straw)
r = m - 1;
else if (needle > straw)
l = m + 1;
else {
return m;
}
}
} break;
case 2: {
stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2);
stbtt_uint8 *rangeArray = coverageTable + 4;
// Binary search.
stbtt_int32 l=0, r=rangeCount-1, m;
int strawStart, strawEnd, needle=glyph;
while (l <= r) {
stbtt_uint8 *rangeRecord;
m = (l + r) >> 1;
rangeRecord = rangeArray + 6 * m;
strawStart = ttUSHORT(rangeRecord);
strawEnd = ttUSHORT(rangeRecord + 2);
if (needle < strawStart)
r = m - 1;
else if (needle > strawEnd)
l = m + 1;
else {
stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4);
return startCoverageIndex + glyph - strawStart;
}
}
} break;
default: {
// There are no other cases.
STBTT_assert(0);
} break;
}
return -1;
}
static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph)
{
stbtt_uint16 classDefFormat = ttUSHORT(classDefTable);
switch(classDefFormat)
{
case 1: {
stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2);
stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4);
stbtt_uint8 *classDef1ValueArray = classDefTable + 6;
if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount)
return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID));
// [DEAR IMGUI] Commented to fix static analyzer warning
//classDefTable = classDef1ValueArray + 2 * glyphCount;
} break;
case 2: {
stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2);
stbtt_uint8 *classRangeRecords = classDefTable + 4;
// Binary search.
stbtt_int32 l=0, r=classRangeCount-1, m;
int strawStart, strawEnd, needle=glyph;
while (l <= r) {
stbtt_uint8 *classRangeRecord;
m = (l + r) >> 1;
classRangeRecord = classRangeRecords + 6 * m;
strawStart = ttUSHORT(classRangeRecord);
strawEnd = ttUSHORT(classRangeRecord + 2);
if (needle < strawStart)
r = m - 1;
else if (needle > strawEnd)
l = m + 1;
else
return (stbtt_int32)ttUSHORT(classRangeRecord + 4);
}
// [DEAR IMGUI] Commented to fix static analyzer warning
//classDefTable = classRangeRecords + 6 * classRangeCount;
} break;
default: {
// There are no other cases.
STBTT_assert(0);
} break;
}
return -1;
}
// Define to STBTT_assert(x) if you want to break on unimplemented formats.
#define STBTT_GPOS_TODO_assert(x)
static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
{
stbtt_uint16 lookupListOffset;
stbtt_uint8 *lookupList;
stbtt_uint16 lookupCount;
stbtt_uint8 *data;
stbtt_int32 i;
if (!info->gpos) return 0;
data = info->data + info->gpos;
if (ttUSHORT(data+0) != 1) return 0; // Major version 1
if (ttUSHORT(data+2) != 0) return 0; // Minor version 0
lookupListOffset = ttUSHORT(data+8);
lookupList = data + lookupListOffset;
lookupCount = ttUSHORT(lookupList);
for (i=0; i<lookupCount; ++i) {
stbtt_uint16 lookupOffset = ttUSHORT(lookupList + 2 + 2 * i);
stbtt_uint8 *lookupTable = lookupList + lookupOffset;
stbtt_uint16 lookupType = ttUSHORT(lookupTable);
stbtt_uint16 subTableCount = ttUSHORT(lookupTable + 4);
stbtt_uint8 *subTableOffsets = lookupTable + 6;
switch(lookupType) {
case 2: { // Pair Adjustment Positioning Subtable
stbtt_int32 sti;
for (sti=0; sti<subTableCount; sti++) {
stbtt_uint16 subtableOffset = ttUSHORT(subTableOffsets + 2 * sti);
stbtt_uint8 *table = lookupTable + subtableOffset;
stbtt_uint16 posFormat = ttUSHORT(table);
stbtt_uint16 coverageOffset = ttUSHORT(table + 2);
stbtt_int32 coverageIndex = stbtt__GetCoverageIndex(table + coverageOffset, glyph1);
if (coverageIndex == -1) continue;
switch (posFormat) {
case 1: {
stbtt_int32 l, r, m;
int straw, needle;
stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);
stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);
stbtt_int32 valueRecordPairSizeInBytes = 2;
stbtt_uint16 pairSetCount = ttUSHORT(table + 8);
stbtt_uint16 pairPosOffset = ttUSHORT(table + 10 + 2 * coverageIndex);
stbtt_uint8 *pairValueTable = table + pairPosOffset;
stbtt_uint16 pairValueCount = ttUSHORT(pairValueTable);
stbtt_uint8 *pairValueArray = pairValueTable + 2;
// TODO: Support more formats.
STBTT_GPOS_TODO_assert(valueFormat1 == 4);
if (valueFormat1 != 4) return 0;
STBTT_GPOS_TODO_assert(valueFormat2 == 0);
if (valueFormat2 != 0) return 0;
STBTT_assert(coverageIndex < pairSetCount);
STBTT__NOTUSED(pairSetCount);
needle=glyph2;
r=pairValueCount-1;
l=0;
// Binary search.
while (l <= r) {
stbtt_uint16 secondGlyph;
stbtt_uint8 *pairValue;
m = (l + r) >> 1;
pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m;
secondGlyph = ttUSHORT(pairValue);
straw = secondGlyph;
if (needle < straw)
r = m - 1;
else if (needle > straw)
l = m + 1;
else {
stbtt_int16 xAdvance = ttSHORT(pairValue + 2);
return xAdvance;
}
}
} break;
case 2: {
stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);
stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);
stbtt_uint16 classDef1Offset = ttUSHORT(table + 8);
stbtt_uint16 classDef2Offset = ttUSHORT(table + 10);
int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1);
int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2);
stbtt_uint16 class1Count = ttUSHORT(table + 12);
stbtt_uint16 class2Count = ttUSHORT(table + 14);
STBTT_assert(glyph1class < class1Count);
STBTT_assert(glyph2class < class2Count);
// TODO: Support more formats.
STBTT_GPOS_TODO_assert(valueFormat1 == 4);
if (valueFormat1 != 4) return 0;
STBTT_GPOS_TODO_assert(valueFormat2 == 0);
if (valueFormat2 != 0) return 0;
if (glyph1class >= 0 && glyph1class < class1Count && glyph2class >= 0 && glyph2class < class2Count) {
stbtt_uint8 *class1Records = table + 16;
stbtt_uint8 *class2Records = class1Records + 2 * (glyph1class * class2Count);
stbtt_int16 xAdvance = ttSHORT(class2Records + 2 * glyph2class);
return xAdvance;
}
} break;
default: {
// There are no other cases.
STBTT_assert(0);
break;
};
}
}
break;
};
default:
// TODO: Implement other stuff.
break;
}
}
return 0;
}
STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2)
{
int xAdvance = 0;
if (info->gpos)
xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2);
if (info->kern)
xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2);
return xAdvance;
}
STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)
{
if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs
return 0;
return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));
}
STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)
{
stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);
}
STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)
{
if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4);
if (descent) *descent = ttSHORT(info->data+info->hhea + 6);
if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);
}
STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap)
{
int tab = stbtt__find_table(info->data, info->fontstart, "OS/2");
if (!tab)
return 0;
if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68);
if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70);
if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72);
return 1;
}
STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)
{
*x0 = ttSHORT(info->data + info->head + 36);
*y0 = ttSHORT(info->data + info->head + 38);
*x1 = ttSHORT(info->data + info->head + 40);
*y1 = ttSHORT(info->data + info->head + 42);
}
STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)
{
int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);
return (float) height / fheight;
}
STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)
{
int unitsPerEm = ttUSHORT(info->data + info->head + 18);
return pixels / unitsPerEm;
}
STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)
{
STBTT_free(v, info->userdata);
}
//////////////////////////////////////////////////////////////////////////////
//
// antialiasing software rasterizer
//
STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)
{
int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning
if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) {
// e.g. space character
if (ix0) *ix0 = 0;
if (iy0) *iy0 = 0;
if (ix1) *ix1 = 0;
if (iy1) *iy1 = 0;
} else {
// move to integral bboxes (treating pixels as little squares, what pixels get touched)?
if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x);
if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y);
if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x);
if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y);
}
}
STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
{
stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1);
}
STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)
{
stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1);
}
STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
{
stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1);
}
//////////////////////////////////////////////////////////////////////////////
//
// Rasterizer
typedef struct stbtt__hheap_chunk
{
struct stbtt__hheap_chunk *next;
} stbtt__hheap_chunk;
typedef struct stbtt__hheap
{
struct stbtt__hheap_chunk *head;
void *first_free;
int num_remaining_in_head_chunk;
} stbtt__hheap;
static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata)
{
if (hh->first_free) {
void *p = hh->first_free;
hh->first_free = * (void **) p;
return p;
} else {
if (hh->num_remaining_in_head_chunk == 0) {
int count = (size < 32 ? 2000 : size < 128 ? 800 : 100);
stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata);
if (c == NULL)
return NULL;
c->next = hh->head;
hh->head = c;
hh->num_remaining_in_head_chunk = count;
}
--hh->num_remaining_in_head_chunk;
return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk;
}
}
static void stbtt__hheap_free(stbtt__hheap *hh, void *p)
{
*(void **) p = hh->first_free;
hh->first_free = p;
}
static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata)
{
stbtt__hheap_chunk *c = hh->head;
while (c) {
stbtt__hheap_chunk *n = c->next;
STBTT_free(c, userdata);
c = n;
}
}
typedef struct stbtt__edge {
float x0,y0, x1,y1;
int invert;
} stbtt__edge;
typedef struct stbtt__active_edge
{
struct stbtt__active_edge *next;
#if STBTT_RASTERIZER_VERSION==1
int x,dx;
float ey;
int direction;
#elif STBTT_RASTERIZER_VERSION==2
float fx,fdx,fdy;
float direction;
float sy;
float ey;
#else
#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
#endif
} stbtt__active_edge;
#if STBTT_RASTERIZER_VERSION == 1
#define STBTT_FIXSHIFT 10
#define STBTT_FIX (1 << STBTT_FIXSHIFT)
#define STBTT_FIXMASK (STBTT_FIX-1)
static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
{
stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
STBTT_assert(z != NULL);
if (!z) return z;
// round dx down to avoid overshooting
if (dxdy < 0)
z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy);
else
z->dx = STBTT_ifloor(STBTT_FIX * dxdy);
z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount
z->x -= off_x * STBTT_FIX;
z->ey = e->y1;
z->next = 0;
z->direction = e->invert ? 1 : -1;
return z;
}
#elif STBTT_RASTERIZER_VERSION == 2
static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
{
stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
STBTT_assert(z != NULL);
//STBTT_assert(e->y0 <= start_point);
if (!z) return z;
z->fdx = dxdy;
z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f;
z->fx = e->x0 + dxdy * (start_point - e->y0);
z->fx -= off_x;
z->direction = e->invert ? 1.0f : -1.0f;
z->sy = e->y0;
z->ey = e->y1;
z->next = 0;
return z;
}
#else
#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
#endif
#if STBTT_RASTERIZER_VERSION == 1
// note: this routine clips fills that extend off the edges... ideally this
// wouldn't happen, but it could happen if the truetype glyph bounding boxes
// are wrong, or if the user supplies a too-small bitmap
static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)
{
// non-zero winding fill
int x0=0, w=0;
while (e) {
if (w == 0) {
// if we're currently at zero, we need to record the edge start point
x0 = e->x; w += e->direction;
} else {
int x1 = e->x; w += e->direction;
// if we went to zero, we need to draw
if (w == 0) {
int i = x0 >> STBTT_FIXSHIFT;
int j = x1 >> STBTT_FIXSHIFT;
if (i < len && j >= 0) {
if (i == j) {
// x0,x1 are the same pixel, so compute combined coverage
scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT);
} else {
if (i >= 0) // add antialiasing for x0
scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT);
else
i = -1; // clip
if (j < len) // add antialiasing for x1
scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT);
else
j = len; // clip
for (++i; i < j; ++i) // fill pixels between x0 and x1
scanline[i] = scanline[i] + (stbtt_uint8) max_weight;
}
}
}
}
e = e->next;
}
}
static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
{
stbtt__hheap hh = { 0, 0, 0 };
stbtt__active_edge *active = NULL;
int y,j=0;
int max_weight = (255 / vsubsample); // weight per vertical scanline
int s; // vertical subsample index
unsigned char scanline_data[512], *scanline;
if (result->w > 512)
scanline = (unsigned char *) STBTT_malloc(result->w, userdata);
else
scanline = scanline_data;
y = off_y * vsubsample;
e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;
while (j < result->h) {
STBTT_memset(scanline, 0, result->w);
for (s=0; s < vsubsample; ++s) {
// find center of pixel for this scanline
float scan_y = y + 0.5f;
stbtt__active_edge **step = &active;
// update all active edges;
// remove all active edges that terminate before the center of this scanline
while (*step) {
stbtt__active_edge * z = *step;
if (z->ey <= scan_y) {
*step = z->next; // delete from list
STBTT_assert(z->direction);
z->direction = 0;
stbtt__hheap_free(&hh, z);
} else {
z->x += z->dx; // advance to position for current scanline
step = &((*step)->next); // advance through list
}
}
// resort the list if needed
for(;;) {
int changed=0;
step = &active;
while (*step && (*step)->next) {
if ((*step)->x > (*step)->next->x) {
stbtt__active_edge *t = *step;
stbtt__active_edge *q = t->next;
t->next = q->next;
q->next = t;
*step = q;
changed = 1;
}
step = &(*step)->next;
}
if (!changed) break;
}
// insert all edges that start before the center of this scanline -- omit ones that also end on this scanline
while (e->y0 <= scan_y) {
if (e->y1 > scan_y) {
stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata);
if (z != NULL) {
// find insertion point
if (active == NULL)
active = z;
else if (z->x < active->x) {
// insert at front
z->next = active;
active = z;
} else {
// find thing to insert AFTER
stbtt__active_edge *p = active;
while (p->next && p->next->x < z->x)
p = p->next;
// at this point, p->next->x is NOT < z->x
z->next = p->next;
p->next = z;
}
}
}
++e;
}
// now process all active edges in XOR fashion
if (active)
stbtt__fill_active_edges(scanline, result->w, active, max_weight);
++y;
}
STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);
++j;
}
stbtt__hheap_cleanup(&hh, userdata);
if (scanline != scanline_data)
STBTT_free(scanline, userdata);
}
#elif STBTT_RASTERIZER_VERSION == 2
// the edge passed in here does not cross the vertical line at x or the vertical line at x+1
// (i.e. it has already been clipped to those)
static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1)
{
if (y0 == y1) return;
STBTT_assert(y0 < y1);
STBTT_assert(e->sy <= e->ey);
if (y0 > e->ey) return;
if (y1 < e->sy) return;
if (y0 < e->sy) {
x0 += (x1-x0) * (e->sy - y0) / (y1-y0);
y0 = e->sy;
}
if (y1 > e->ey) {
x1 += (x1-x0) * (e->ey - y1) / (y1-y0);
y1 = e->ey;
}
if (x0 == x)
STBTT_assert(x1 <= x+1);
else if (x0 == x+1)
STBTT_assert(x1 >= x);
else if (x0 <= x)
STBTT_assert(x1 <= x);
else if (x0 >= x+1)
STBTT_assert(x1 >= x+1);
else
STBTT_assert(x1 >= x && x1 <= x+1);
if (x0 <= x && x1 <= x)
scanline[x] += e->direction * (y1-y0);
else if (x0 >= x+1 && x1 >= x+1)
;
else {
STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1);
scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position
}
}
static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top)
{
float y_bottom = y_top+1;
while (e) {
// brute force every pixel
// compute intersection points with top & bottom
STBTT_assert(e->ey >= y_top);
if (e->fdx == 0) {
float x0 = e->fx;
if (x0 < len) {
if (x0 >= 0) {
stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom);
stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom);
} else {
stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom);
}
}
} else {
float x0 = e->fx;
float dx = e->fdx;
float xb = x0 + dx;
float x_top, x_bottom;
float sy0,sy1;
float dy = e->fdy;
STBTT_assert(e->sy <= y_bottom && e->ey >= y_top);
// compute endpoints of line segment clipped to this scanline (if the
// line segment starts on this scanline. x0 is the intersection of the
// line with y_top, but that may be off the line segment.
if (e->sy > y_top) {
x_top = x0 + dx * (e->sy - y_top);
sy0 = e->sy;
} else {
x_top = x0;
sy0 = y_top;
}
if (e->ey < y_bottom) {
x_bottom = x0 + dx * (e->ey - y_top);
sy1 = e->ey;
} else {
x_bottom = xb;
sy1 = y_bottom;
}
if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) {
// from here on, we don't have to range check x values
if ((int) x_top == (int) x_bottom) {
float height;
// simple case, only spans one pixel
int x = (int) x_top;
height = sy1 - sy0;
STBTT_assert(x >= 0 && x < len);
scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2) * height;
scanline_fill[x] += e->direction * height; // everything right of this pixel is filled
} else {
int x,x1,x2;
float y_crossing, step, sign, area;
// covers 2+ pixels
if (x_top > x_bottom) {
// flip scanline vertically; signed area is the same
float t;
sy0 = y_bottom - (sy0 - y_top);
sy1 = y_bottom - (sy1 - y_top);
t = sy0, sy0 = sy1, sy1 = t;
t = x_bottom, x_bottom = x_top, x_top = t;
dx = -dx;
dy = -dy;
t = x0, x0 = xb, xb = t;
// [DEAR IMGUI] Fix static analyzer warning
(void)dx; // [ImGui: fix static analyzer warning]
}
x1 = (int) x_top;
x2 = (int) x_bottom;
// compute intersection with y axis at x1+1
y_crossing = (x1+1 - x0) * dy + y_top;
sign = e->direction;
// area of the rectangle covered from y0..y_crossing
area = sign * (y_crossing-sy0);
// area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing)
scanline[x1] += area * (1-((x_top - x1)+(x1+1-x1))/2);
step = sign * dy;
for (x = x1+1; x < x2; ++x) {
scanline[x] += area + step/2;
area += step;
}
y_crossing += dy * (x2 - (x1+1));
STBTT_assert(STBTT_fabs(area) <= 1.01f);
scanline[x2] += area + sign * (1-((x2-x2)+(x_bottom-x2))/2) * (sy1-y_crossing);
scanline_fill[x2] += sign * (sy1-sy0);
}
} else {
// if edge goes outside of box we're drawing, we require
// clipping logic. since this does not match the intended use
// of this library, we use a different, very slow brute
// force implementation
int x;
for (x=0; x < len; ++x) {
// cases:
//
// there can be up to two intersections with the pixel. any intersection
// with left or right edges can be handled by splitting into two (or three)
// regions. intersections with top & bottom do not necessitate case-wise logic.
//
// the old way of doing this found the intersections with the left & right edges,
// then used some simple logic to produce up to three segments in sorted order
// from top-to-bottom. however, this had a problem: if an x edge was epsilon
// across the x border, then the corresponding y position might not be distinct
// from the other y segment, and it might ignored as an empty segment. to avoid
// that, we need to explicitly produce segments based on x positions.
// rename variables to clearly-defined pairs
float y0 = y_top;
float x1 = (float) (x);
float x2 = (float) (x+1);
float x3 = xb;
float y3 = y_bottom;
// x = e->x + e->dx * (y-y_top)
// (y-y_top) = (x - e->x) / e->dx
// y = (x - e->x) / e->dx + y_top
float y1 = (x - x0) / dx + y_top;
float y2 = (x+1 - x0) / dx + y_top;
if (x0 < x1 && x3 > x2) { // three segments descending down-right
stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2);
stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
} else if (x3 < x1 && x0 > x2) { // three segments descending down-left
stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1);
stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
} else if (x0 < x1 && x3 > x1) { // two segments across x, down-right
stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
} else if (x3 < x1 && x0 > x1) { // two segments across x, down-left
stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
} else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right
stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
} else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left
stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
} else { // one segment
stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3);
}
}
}
}
e = e->next;
}
}
// directly AA rasterize edges w/o supersampling
static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
{
stbtt__hheap hh = { 0, 0, 0 };
stbtt__active_edge *active = NULL;
int y,j=0, i;
float scanline_data[129], *scanline, *scanline2;
STBTT__NOTUSED(vsubsample);
if (result->w > 64)
scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata);
else
scanline = scanline_data;
scanline2 = scanline + result->w;
y = off_y;
e[n].y0 = (float) (off_y + result->h) + 1;
while (j < result->h) {
// find center of pixel for this scanline
float scan_y_top = y + 0.0f;
float scan_y_bottom = y + 1.0f;
stbtt__active_edge **step = &active;
STBTT_memset(scanline , 0, result->w*sizeof(scanline[0]));
STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0]));
// update all active edges;
// remove all active edges that terminate before the top of this scanline
while (*step) {
stbtt__active_edge * z = *step;
if (z->ey <= scan_y_top) {
*step = z->next; // delete from list
STBTT_assert(z->direction);
z->direction = 0;
stbtt__hheap_free(&hh, z);
} else {
step = &((*step)->next); // advance through list
}
}
// insert all edges that start before the bottom of this scanline
while (e->y0 <= scan_y_bottom) {
if (e->y0 != e->y1) {
stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata);
if (z != NULL) {
if (j == 0 && off_y != 0) {
if (z->ey < scan_y_top) {
// this can happen due to subpixel positioning and some kind of fp rounding error i think
z->ey = scan_y_top;
}
}
STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds
// insert at front
z->next = active;
active = z;
}
}
++e;
}
// now process all active edges
if (active)
stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top);
{
float sum = 0;
for (i=0; i < result->w; ++i) {
float k;
int m;
sum += scanline2[i];
k = scanline[i] + sum;
k = (float) STBTT_fabs(k)*255 + 0.5f;
m = (int) k;
if (m > 255) m = 255;
result->pixels[j*result->stride + i] = (unsigned char) m;
}
}
// advance all the edges
step = &active;
while (*step) {
stbtt__active_edge *z = *step;
z->fx += z->fdx; // advance to position for current scanline
step = &((*step)->next); // advance through list
}
++y;
++j;
}
stbtt__hheap_cleanup(&hh, userdata);
if (scanline != scanline_data)
STBTT_free(scanline, userdata);
}
#else
#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
#endif
#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0)
static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n)
{
int i,j;
for (i=1; i < n; ++i) {
stbtt__edge t = p[i], *a = &t;
j = i;
while (j > 0) {
stbtt__edge *b = &p[j-1];
int c = STBTT__COMPARE(a,b);
if (!c) break;
p[j] = p[j-1];
--j;
}
if (i != j)
p[j] = t;
}
}
static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n)
{
/* threshold for transitioning to insertion sort */
while (n > 12) {
stbtt__edge t;
int c01,c12,c,m,i,j;
/* compute median of three */
m = n >> 1;
c01 = STBTT__COMPARE(&p[0],&p[m]);
c12 = STBTT__COMPARE(&p[m],&p[n-1]);
/* if 0 >= mid >= end, or 0 < mid < end, then use mid */
if (c01 != c12) {
/* otherwise, we'll need to swap something else to middle */
int z;
c = STBTT__COMPARE(&p[0],&p[n-1]);
/* 0>mid && mid<n: 0>n => n; 0<n => 0 */
/* 0<mid && mid>n: 0>n => 0; 0<n => n */
z = (c == c12) ? 0 : n-1;
t = p[z];
p[z] = p[m];
p[m] = t;
}
/* now p[m] is the median-of-three */
/* swap it to the beginning so it won't move around */
t = p[0];
p[0] = p[m];
p[m] = t;
/* partition loop */
i=1;
j=n-1;
for(;;) {
/* handling of equality is crucial here */
/* for sentinels & efficiency with duplicates */
for (;;++i) {
if (!STBTT__COMPARE(&p[i], &p[0])) break;
}
for (;;--j) {
if (!STBTT__COMPARE(&p[0], &p[j])) break;
}
/* make sure we haven't crossed */
if (i >= j) break;
t = p[i];
p[i] = p[j];
p[j] = t;
++i;
--j;
}
/* recurse on smaller side, iterate on larger */
if (j < (n-i)) {
stbtt__sort_edges_quicksort(p,j);
p = p+i;
n = n-i;
} else {
stbtt__sort_edges_quicksort(p+i, n-i);
n = j;
}
}
}
static void stbtt__sort_edges(stbtt__edge *p, int n)
{
stbtt__sort_edges_quicksort(p, n);
stbtt__sort_edges_ins_sort(p, n);
}
typedef struct
{
float x,y;
} stbtt__point;
static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata)
{
float y_scale_inv = invert ? -scale_y : scale_y;
stbtt__edge *e;
int n,i,j,k,m;
#if STBTT_RASTERIZER_VERSION == 1
int vsubsample = result->h < 8 ? 15 : 5;
#elif STBTT_RASTERIZER_VERSION == 2
int vsubsample = 1;
#else
#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
#endif
// vsubsample should divide 255 evenly; otherwise we won't reach full opacity
// now we have to blow out the windings into explicit edge lists
n = 0;
for (i=0; i < windings; ++i)
n += wcount[i];
e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel
if (e == 0) return;
n = 0;
m=0;
for (i=0; i < windings; ++i) {
stbtt__point *p = pts + m;
m += wcount[i];
j = wcount[i]-1;
for (k=0; k < wcount[i]; j=k++) {
int a=k,b=j;
// skip the edge if horizontal
if (p[j].y == p[k].y)
continue;
// add edge from j to k to the list
e[n].invert = 0;
if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {
e[n].invert = 1;
a=j,b=k;
}
e[n].x0 = p[a].x * scale_x + shift_x;
e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample;
e[n].x1 = p[b].x * scale_x + shift_x;
e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample;
++n;
}
}
// now sort the edges by their highest point (should snap to integer, and then by x)
//STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);
stbtt__sort_edges(e, n);
// now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);
STBTT_free(e, userdata);
}
static void stbtt__add_point(stbtt__point *points, int n, float x, float y)
{
if (!points) return; // during first pass, it's unallocated
points[n].x = x;
points[n].y = y;
}
// tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching
static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n)
{
// midpoint
float mx = (x0 + 2*x1 + x2)/4;
float my = (y0 + 2*y1 + y2)/4;
// versus directly drawn line
float dx = (x0+x2)/2 - mx;
float dy = (y0+y2)/2 - my;
if (n > 16) // 65536 segments on one curve better be enough!
return 1;
if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA
stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);
stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);
} else {
stbtt__add_point(points, *num_points,x2,y2);
*num_points = *num_points+1;
}
return 1;
}
static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n)
{
// @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough
float dx0 = x1-x0;
float dy0 = y1-y0;
float dx1 = x2-x1;
float dy1 = y2-y1;
float dx2 = x3-x2;
float dy2 = y3-y2;
float dx = x3-x0;
float dy = y3-y0;
float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2));
float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy);
float flatness_squared = longlen*longlen-shortlen*shortlen;
if (n > 16) // 65536 segments on one curve better be enough!
return;
if (flatness_squared > objspace_flatness_squared) {
float x01 = (x0+x1)/2;
float y01 = (y0+y1)/2;
float x12 = (x1+x2)/2;
float y12 = (y1+y2)/2;
float x23 = (x2+x3)/2;
float y23 = (y2+y3)/2;
float xa = (x01+x12)/2;
float ya = (y01+y12)/2;
float xb = (x12+x23)/2;
float yb = (y12+y23)/2;
float mx = (xa+xb)/2;
float my = (ya+yb)/2;
stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1);
stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1);
} else {
stbtt__add_point(points, *num_points,x3,y3);
*num_points = *num_points+1;
}
}
// returns number of contours
static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)
{
stbtt__point *points=0;
int num_points=0;
float objspace_flatness_squared = objspace_flatness * objspace_flatness;
int i,n=0,start=0, pass;
// count how many "moves" there are to get the contour count
for (i=0; i < num_verts; ++i)
if (vertices[i].type == STBTT_vmove)
++n;
*num_contours = n;
if (n == 0) return 0;
*contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);
if (*contour_lengths == 0) {
*num_contours = 0;
return 0;
}
// make two passes through the points so we don't need to realloc
for (pass=0; pass < 2; ++pass) {
float x=0,y=0;
if (pass == 1) {
points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);
if (points == NULL) goto error;
}
num_points = 0;
n= -1;
for (i=0; i < num_verts; ++i) {
switch (vertices[i].type) {
case STBTT_vmove:
// start the next contour
if (n >= 0)
(*contour_lengths)[n] = num_points - start;
++n;
start = num_points;
x = vertices[i].x, y = vertices[i].y;
stbtt__add_point(points, num_points++, x,y);
break;
case STBTT_vline:
x = vertices[i].x, y = vertices[i].y;
stbtt__add_point(points, num_points++, x, y);
break;
case STBTT_vcurve:
stbtt__tesselate_curve(points, &num_points, x,y,
vertices[i].cx, vertices[i].cy,
vertices[i].x, vertices[i].y,
objspace_flatness_squared, 0);
x = vertices[i].x, y = vertices[i].y;
break;
case STBTT_vcubic:
stbtt__tesselate_cubic(points, &num_points, x,y,
vertices[i].cx, vertices[i].cy,
vertices[i].cx1, vertices[i].cy1,
vertices[i].x, vertices[i].y,
objspace_flatness_squared, 0);
x = vertices[i].x, y = vertices[i].y;
break;
}
}
(*contour_lengths)[n] = num_points - start;
}
return points;
error:
STBTT_free(points, userdata);
STBTT_free(*contour_lengths, userdata);
*contour_lengths = 0;
*num_contours = 0;
return NULL;
}
STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata)
{
float scale = scale_x > scale_y ? scale_y : scale_x;
int winding_count = 0;
int *winding_lengths = NULL;
stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);
if (windings) {
stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);
STBTT_free(winding_lengths, userdata);
STBTT_free(windings, userdata);
}
}
STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)
{
STBTT_free(bitmap, userdata);
}
STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff)
{
int ix0,iy0,ix1,iy1;
stbtt__bitmap gbm;
stbtt_vertex *vertices;
int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
if (scale_x == 0) scale_x = scale_y;
if (scale_y == 0) {
if (scale_x == 0) {
STBTT_free(vertices, info->userdata);
return NULL;
}
scale_y = scale_x;
}
stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1);
// now we get the size
gbm.w = (ix1 - ix0);
gbm.h = (iy1 - iy0);
gbm.pixels = NULL; // in case we error
if (width ) *width = gbm.w;
if (height) *height = gbm.h;
if (xoff ) *xoff = ix0;
if (yoff ) *yoff = iy0;
if (gbm.w && gbm.h) {
gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);
if (gbm.pixels) {
gbm.stride = gbm.w;
stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
}
}
STBTT_free(vertices, info->userdata);
return gbm.pixels;
}
STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff)
{
return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);
}
STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph)
{
int ix0,iy0;
stbtt_vertex *vertices;
int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
stbtt__bitmap gbm;
stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0);
gbm.pixels = output;
gbm.w = out_w;
gbm.h = out_h;
gbm.stride = out_stride;
if (gbm.w && gbm.h)
stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata);
STBTT_free(vertices, info->userdata);
}
STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph)
{
stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph);
}
STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff)
{
return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);
}
STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint)
{
stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint));
}
STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint)
{
stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));
}
STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff)
{
return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff);
}
STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint)
{
stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint);
}
//////////////////////////////////////////////////////////////////////////////
//
// bitmap baking
//
// This is SUPER-CRAPPY packing to keep source code small
static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)
float pixel_height, // height of font in pixels
unsigned char *pixels, int pw, int ph, // bitmap to be filled in
int first_char, int num_chars, // characters to bake
stbtt_bakedchar *chardata)
{
float scale;
int x,y,bottom_y, i;
stbtt_fontinfo f;
f.userdata = NULL;
if (!stbtt_InitFont(&f, data, offset))
return -1;
STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
x=y=1;
bottom_y = 1;
scale = stbtt_ScaleForPixelHeight(&f, pixel_height);
for (i=0; i < num_chars; ++i) {
int advance, lsb, x0,y0,x1,y1,gw,gh;
int g = stbtt_FindGlyphIndex(&f, first_char + i);
stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);
stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);
gw = x1-x0;
gh = y1-y0;
if (x + gw + 1 >= pw)
y = bottom_y, x = 1; // advance to next row
if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row
return -i;
STBTT_assert(x+gw < pw);
STBTT_assert(y+gh < ph);
stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);
chardata[i].x0 = (stbtt_int16) x;
chardata[i].y0 = (stbtt_int16) y;
chardata[i].x1 = (stbtt_int16) (x + gw);
chardata[i].y1 = (stbtt_int16) (y + gh);
chardata[i].xadvance = scale * advance;
chardata[i].xoff = (float) x0;
chardata[i].yoff = (float) y0;
x = x + gw + 1;
if (y+gh+1 > bottom_y)
bottom_y = y+gh+1;
}
return bottom_y;
}
STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)
{
float d3d_bias = opengl_fillrule ? 0 : -0.5f;
float ipw = 1.0f / pw, iph = 1.0f / ph;
const stbtt_bakedchar *b = chardata + char_index;
int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f);
int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f);
q->x0 = round_x + d3d_bias;
q->y0 = round_y + d3d_bias;
q->x1 = round_x + b->x1 - b->x0 + d3d_bias;
q->y1 = round_y + b->y1 - b->y0 + d3d_bias;
q->s0 = b->x0 * ipw;
q->t0 = b->y0 * iph;
q->s1 = b->x1 * ipw;
q->t1 = b->y1 * iph;
*xpos += b->xadvance;
}
//////////////////////////////////////////////////////////////////////////////
//
// rectangle packing replacement routines if you don't have stb_rect_pack.h
//
#ifndef STB_RECT_PACK_VERSION
typedef int stbrp_coord;
////////////////////////////////////////////////////////////////////////////////////
// //
// //
// COMPILER WARNING ?!?!? //
// //
// //
// if you get a compile warning due to these symbols being defined more than //
// once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" //
// //
////////////////////////////////////////////////////////////////////////////////////
typedef struct
{
int width,height;
int x,y,bottom_y;
} stbrp_context;
typedef struct
{
unsigned char x;
} stbrp_node;
struct stbrp_rect
{
stbrp_coord x,y;
int id,w,h,was_packed;
};
static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes)
{
con->width = pw;
con->height = ph;
con->x = 0;
con->y = 0;
con->bottom_y = 0;
STBTT__NOTUSED(nodes);
STBTT__NOTUSED(num_nodes);
}
static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects)
{
int i;
for (i=0; i < num_rects; ++i) {
if (con->x + rects[i].w > con->width) {
con->x = 0;
con->y = con->bottom_y;
}
if (con->y + rects[i].h > con->height)
break;
rects[i].x = con->x;
rects[i].y = con->y;
rects[i].was_packed = 1;
con->x += rects[i].w;
if (con->y + rects[i].h > con->bottom_y)
con->bottom_y = con->y + rects[i].h;
}
for ( ; i < num_rects; ++i)
rects[i].was_packed = 0;
}
#endif
//////////////////////////////////////////////////////////////////////////////
//
// bitmap baking
//
// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If
// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy.
STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context)
{
stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context);
int num_nodes = pw - padding;
stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context);
if (context == NULL || nodes == NULL) {
if (context != NULL) STBTT_free(context, alloc_context);
if (nodes != NULL) STBTT_free(nodes , alloc_context);
return 0;
}
spc->user_allocator_context = alloc_context;
spc->width = pw;
spc->height = ph;
spc->pixels = pixels;
spc->pack_info = context;
spc->nodes = nodes;
spc->padding = padding;
spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw;
spc->h_oversample = 1;
spc->v_oversample = 1;
spc->skip_missing = 0;
stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes);
if (pixels)
STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
return 1;
}
STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc)
{
STBTT_free(spc->nodes , spc->user_allocator_context);
STBTT_free(spc->pack_info, spc->user_allocator_context);
}
STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample)
{
STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE);
STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE);
if (h_oversample <= STBTT_MAX_OVERSAMPLE)
spc->h_oversample = h_oversample;
if (v_oversample <= STBTT_MAX_OVERSAMPLE)
spc->v_oversample = v_oversample;
}
STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip)
{
spc->skip_missing = skip;
}
#define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1)
static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
{
unsigned char buffer[STBTT_MAX_OVERSAMPLE];
int safe_w = w - kernel_width;
int j;
STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze
for (j=0; j < h; ++j) {
int i;
unsigned int total;
STBTT_memset(buffer, 0, kernel_width);
total = 0;
// make kernel_width a constant in common cases so compiler can optimize out the divide
switch (kernel_width) {
case 2:
for (i=0; i <= safe_w; ++i) {
total += pixels[i] - buffer[i & STBTT__OVER_MASK];
buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
pixels[i] = (unsigned char) (total / 2);
}
break;
case 3:
for (i=0; i <= safe_w; ++i) {
total += pixels[i] - buffer[i & STBTT__OVER_MASK];
buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
pixels[i] = (unsigned char) (total / 3);
}
break;
case 4:
for (i=0; i <= safe_w; ++i) {
total += pixels[i] - buffer[i & STBTT__OVER_MASK];
buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
pixels[i] = (unsigned char) (total / 4);
}
break;
case 5:
for (i=0; i <= safe_w; ++i) {
total += pixels[i] - buffer[i & STBTT__OVER_MASK];
buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
pixels[i] = (unsigned char) (total / 5);
}
break;
default:
for (i=0; i <= safe_w; ++i) {
total += pixels[i] - buffer[i & STBTT__OVER_MASK];
buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
pixels[i] = (unsigned char) (total / kernel_width);
}
break;
}
for (; i < w; ++i) {
STBTT_assert(pixels[i] == 0);
total -= buffer[i & STBTT__OVER_MASK];
pixels[i] = (unsigned char) (total / kernel_width);
}
pixels += stride_in_bytes;
}
}
static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
{
unsigned char buffer[STBTT_MAX_OVERSAMPLE];
int safe_h = h - kernel_width;
int j;
STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze
for (j=0; j < w; ++j) {
int i;
unsigned int total;
STBTT_memset(buffer, 0, kernel_width);
total = 0;
// make kernel_width a constant in common cases so compiler can optimize out the divide
switch (kernel_width) {
case 2:
for (i=0; i <= safe_h; ++i) {
total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
pixels[i*stride_in_bytes] = (unsigned char) (total / 2);
}
break;
case 3:
for (i=0; i <= safe_h; ++i) {
total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
pixels[i*stride_in_bytes] = (unsigned char) (total / 3);
}
break;
case 4:
for (i=0; i <= safe_h; ++i) {
total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
pixels[i*stride_in_bytes] = (unsigned char) (total / 4);
}
break;
case 5:
for (i=0; i <= safe_h; ++i) {
total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
pixels[i*stride_in_bytes] = (unsigned char) (total / 5);
}
break;
default:
for (i=0; i <= safe_h; ++i) {
total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
}
break;
}
for (; i < h; ++i) {
STBTT_assert(pixels[i*stride_in_bytes] == 0);
total -= buffer[i & STBTT__OVER_MASK];
pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
}
pixels += 1;
}
}
static float stbtt__oversample_shift(int oversample)
{
if (!oversample)
return 0.0f;
// The prefilter is a box filter of width "oversample",
// which shifts phase by (oversample - 1)/2 pixels in
// oversampled space. We want to shift in the opposite
// direction to counter this.
return (float)-(oversample - 1) / (2.0f * (float)oversample);
}
// rects array must be big enough to accommodate all characters in the given ranges
STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
{
int i,j,k;
k=0;
for (i=0; i < num_ranges; ++i) {
float fh = ranges[i].font_size;
float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
ranges[i].h_oversample = (unsigned char) spc->h_oversample;
ranges[i].v_oversample = (unsigned char) spc->v_oversample;
for (j=0; j < ranges[i].num_chars; ++j) {
int x0,y0,x1,y1;
int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
int glyph = stbtt_FindGlyphIndex(info, codepoint);
if (glyph == 0 && spc->skip_missing) {
rects[k].w = rects[k].h = 0;
} else {
stbtt_GetGlyphBitmapBoxSubpixel(info,glyph,
scale * spc->h_oversample,
scale * spc->v_oversample,
0,0,
&x0,&y0,&x1,&y1);
rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1);
rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1);
}
++k;
}
}
return k;
}
STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph)
{
stbtt_MakeGlyphBitmapSubpixel(info,
output,
out_w - (prefilter_x - 1),
out_h - (prefilter_y - 1),
out_stride,
scale_x,
scale_y,
shift_x,
shift_y,
glyph);
if (prefilter_x > 1)
stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x);
if (prefilter_y > 1)
stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y);
*sub_x = stbtt__oversample_shift(prefilter_x);
*sub_y = stbtt__oversample_shift(prefilter_y);
}
// rects array must be big enough to accommodate all characters in the given ranges
STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
{
int i,j,k, return_value = 1;
// save current values
int old_h_over = spc->h_oversample;
int old_v_over = spc->v_oversample;
k = 0;
for (i=0; i < num_ranges; ++i) {
float fh = ranges[i].font_size;
float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
float recip_h,recip_v,sub_x,sub_y;
spc->h_oversample = ranges[i].h_oversample;
spc->v_oversample = ranges[i].v_oversample;
recip_h = 1.0f / spc->h_oversample;
recip_v = 1.0f / spc->v_oversample;
sub_x = stbtt__oversample_shift(spc->h_oversample);
sub_y = stbtt__oversample_shift(spc->v_oversample);
for (j=0; j < ranges[i].num_chars; ++j) {
stbrp_rect *r = &rects[k];
if (r->was_packed && r->w != 0 && r->h != 0) {
stbtt_packedchar *bc = &ranges[i].chardata_for_range[j];
int advance, lsb, x0,y0,x1,y1;
int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
int glyph = stbtt_FindGlyphIndex(info, codepoint);
stbrp_coord pad = (stbrp_coord) spc->padding;
// pad on left and top
r->x += pad;
r->y += pad;
r->w -= pad;
r->h -= pad;
stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb);
stbtt_GetGlyphBitmapBox(info, glyph,
scale * spc->h_oversample,
scale * spc->v_oversample,
&x0,&y0,&x1,&y1);
stbtt_MakeGlyphBitmapSubpixel(info,
spc->pixels + r->x + r->y*spc->stride_in_bytes,
r->w - spc->h_oversample+1,
r->h - spc->v_oversample+1,
spc->stride_in_bytes,
scale * spc->h_oversample,
scale * spc->v_oversample,
0,0,
glyph);
if (spc->h_oversample > 1)
stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
r->w, r->h, spc->stride_in_bytes,
spc->h_oversample);
if (spc->v_oversample > 1)
stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
r->w, r->h, spc->stride_in_bytes,
spc->v_oversample);
bc->x0 = (stbtt_int16) r->x;
bc->y0 = (stbtt_int16) r->y;
bc->x1 = (stbtt_int16) (r->x + r->w);
bc->y1 = (stbtt_int16) (r->y + r->h);
bc->xadvance = scale * advance;
bc->xoff = (float) x0 * recip_h + sub_x;
bc->yoff = (float) y0 * recip_v + sub_y;
bc->xoff2 = (x0 + r->w) * recip_h + sub_x;
bc->yoff2 = (y0 + r->h) * recip_v + sub_y;
} else {
return_value = 0; // if any fail, report failure
}
++k;
}
}
// restore original values
spc->h_oversample = old_h_over;
spc->v_oversample = old_v_over;
return return_value;
}
STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects)
{
stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects);
}
STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges)
{
stbtt_fontinfo info;
int i,j,n, return_value = 1;
//stbrp_context *context = (stbrp_context *) spc->pack_info;
stbrp_rect *rects;
// flag all characters as NOT packed
for (i=0; i < num_ranges; ++i)
for (j=0; j < ranges[i].num_chars; ++j)
ranges[i].chardata_for_range[j].x0 =
ranges[i].chardata_for_range[j].y0 =
ranges[i].chardata_for_range[j].x1 =
ranges[i].chardata_for_range[j].y1 = 0;
n = 0;
for (i=0; i < num_ranges; ++i)
n += ranges[i].num_chars;
rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context);
if (rects == NULL)
return 0;
info.userdata = spc->user_allocator_context;
stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index));
n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects);
stbtt_PackFontRangesPackRects(spc, rects, n);
return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects);
STBTT_free(rects, spc->user_allocator_context);
return return_value;
}
STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,
int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range)
{
stbtt_pack_range range;
range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range;
range.array_of_unicode_codepoints = NULL;
range.num_chars = num_chars_in_range;
range.chardata_for_range = chardata_for_range;
range.font_size = font_size;
return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1);
}
STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap)
{
int i_ascent, i_descent, i_lineGap;
float scale;
stbtt_fontinfo info;
stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index));
scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size);
stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap);
*ascent = (float) i_ascent * scale;
*descent = (float) i_descent * scale;
*lineGap = (float) i_lineGap * scale;
}
STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer)
{
float ipw = 1.0f / pw, iph = 1.0f / ph;
const stbtt_packedchar *b = chardata + char_index;
if (align_to_integer) {
float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f);
float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f);
q->x0 = x;
q->y0 = y;
q->x1 = x + b->xoff2 - b->xoff;
q->y1 = y + b->yoff2 - b->yoff;
} else {
q->x0 = *xpos + b->xoff;
q->y0 = *ypos + b->yoff;
q->x1 = *xpos + b->xoff2;
q->y1 = *ypos + b->yoff2;
}
q->s0 = b->x0 * ipw;
q->t0 = b->y0 * iph;
q->s1 = b->x1 * ipw;
q->t1 = b->y1 * iph;
*xpos += b->xadvance;
}
//////////////////////////////////////////////////////////////////////////////
//
// sdf computation
//
#define STBTT_min(a,b) ((a) < (b) ? (a) : (b))
#define STBTT_max(a,b) ((a) < (b) ? (b) : (a))
static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2])
{
float q0perp = q0[1]*ray[0] - q0[0]*ray[1];
float q1perp = q1[1]*ray[0] - q1[0]*ray[1];
float q2perp = q2[1]*ray[0] - q2[0]*ray[1];
float roperp = orig[1]*ray[0] - orig[0]*ray[1];
float a = q0perp - 2*q1perp + q2perp;
float b = q1perp - q0perp;
float c = q0perp - roperp;
float s0 = 0., s1 = 0.;
int num_s = 0;
if (a != 0.0) {
float discr = b*b - a*c;
if (discr > 0.0) {
float rcpna = -1 / a;
float d = (float) STBTT_sqrt(discr);
s0 = (b+d) * rcpna;
s1 = (b-d) * rcpna;
if (s0 >= 0.0 && s0 <= 1.0)
num_s = 1;
if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) {
if (num_s == 0) s0 = s1;
++num_s;
}
}
} else {
// 2*b*s + c = 0
// s = -c / (2*b)
s0 = c / (-2 * b);
if (s0 >= 0.0 && s0 <= 1.0)
num_s = 1;
}
if (num_s == 0)
return 0;
else {
float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]);
float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2;
float q0d = q0[0]*rayn_x + q0[1]*rayn_y;
float q1d = q1[0]*rayn_x + q1[1]*rayn_y;
float q2d = q2[0]*rayn_x + q2[1]*rayn_y;
float rod = orig[0]*rayn_x + orig[1]*rayn_y;
float q10d = q1d - q0d;
float q20d = q2d - q0d;
float q0rd = q0d - rod;
hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d;
hits[0][1] = a*s0+b;
if (num_s > 1) {
hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d;
hits[1][1] = a*s1+b;
return 2;
} else {
return 1;
}
}
}
static int equal(float *a, float *b)
{
return (a[0] == b[0] && a[1] == b[1]);
}
static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts)
{
int i;
float orig[2], ray[2] = { 1, 0 };
float y_frac;
int winding = 0;
orig[0] = x;
//orig[1] = y; // [DEAR IMGUI] commmented double assignment
// make sure y never passes through a vertex of the shape
y_frac = (float) STBTT_fmod(y, 1.0f);
if (y_frac < 0.01f)
y += 0.01f;
else if (y_frac > 0.99f)
y -= 0.01f;
orig[1] = y;
// test a ray from (-infinity,y) to (x,y)
for (i=0; i < nverts; ++i) {
if (verts[i].type == STBTT_vline) {
int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y;
int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y;
if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {
float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;
if (x_inter < x)
winding += (y0 < y1) ? 1 : -1;
}
}
if (verts[i].type == STBTT_vcurve) {
int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ;
int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy;
int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ;
int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2));
int by = STBTT_max(y0,STBTT_max(y1,y2));
if (y > ay && y < by && x > ax) {
float q0[2],q1[2],q2[2];
float hits[2][2];
q0[0] = (float)x0;
q0[1] = (float)y0;
q1[0] = (float)x1;
q1[1] = (float)y1;
q2[0] = (float)x2;
q2[1] = (float)y2;
if (equal(q0,q1) || equal(q1,q2)) {
x0 = (int)verts[i-1].x;
y0 = (int)verts[i-1].y;
x1 = (int)verts[i ].x;
y1 = (int)verts[i ].y;
if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {
float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;
if (x_inter < x)
winding += (y0 < y1) ? 1 : -1;
}
} else {
int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits);
if (num_hits >= 1)
if (hits[0][0] < 0)
winding += (hits[0][1] < 0 ? -1 : 1);
if (num_hits >= 2)
if (hits[1][0] < 0)
winding += (hits[1][1] < 0 ? -1 : 1);
}
}
}
}
return winding;
}
static float stbtt__cuberoot( float x )
{
if (x<0)
return -(float) STBTT_pow(-x,1.0f/3.0f);
else
return (float) STBTT_pow( x,1.0f/3.0f);
}
// x^3 + c*x^2 + b*x + a = 0
static int stbtt__solve_cubic(float a, float b, float c, float* r)
{
float s = -a / 3;
float p = b - a*a / 3;
float q = a * (2*a*a - 9*b) / 27 + c;
float p3 = p*p*p;
float d = q*q + 4*p3 / 27;
if (d >= 0) {
float z = (float) STBTT_sqrt(d);
float u = (-q + z) / 2;
float v = (-q - z) / 2;
u = stbtt__cuberoot(u);
v = stbtt__cuberoot(v);
r[0] = s + u + v;
return 1;
} else {
float u = (float) STBTT_sqrt(-p/3);
float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative
float m = (float) STBTT_cos(v);
float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f;
r[0] = s + u * 2 * m;
r[1] = s - u * (m + n);
r[2] = s - u * (m - n);
//STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe?
//STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f);
//STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f);
return 3;
}
}
STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)
{
float scale_x = scale, scale_y = scale;
int ix0,iy0,ix1,iy1;
int w,h;
unsigned char *data;
// if one scale is 0, use same scale for both
if (scale_x == 0) scale_x = scale_y;
if (scale_y == 0) {
if (scale_x == 0) return NULL; // if both scales are 0, return NULL
scale_y = scale_x;
}
stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1);
// if empty, return NULL
if (ix0 == ix1 || iy0 == iy1)
return NULL;
ix0 -= padding;
iy0 -= padding;
ix1 += padding;
iy1 += padding;
w = (ix1 - ix0);
h = (iy1 - iy0);
if (width ) *width = w;
if (height) *height = h;
if (xoff ) *xoff = ix0;
if (yoff ) *yoff = iy0;
// invert for y-downwards bitmaps
scale_y = -scale_y;
{
int x,y,i,j;
float *precompute;
stbtt_vertex *verts;
int num_verts = stbtt_GetGlyphShape(info, glyph, &verts);
data = (unsigned char *) STBTT_malloc(w * h, info->userdata);
precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata);
for (i=0,j=num_verts-1; i < num_verts; j=i++) {
if (verts[i].type == STBTT_vline) {
float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;
float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y;
float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));
precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist;
} else if (verts[i].type == STBTT_vcurve) {
float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y;
float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y;
float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y;
float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;
float len2 = bx*bx + by*by;
if (len2 != 0.0f)
precompute[i] = 1.0f / (bx*bx + by*by);
else
precompute[i] = 0.0f;
} else
precompute[i] = 0.0f;
}
for (y=iy0; y < iy1; ++y) {
for (x=ix0; x < ix1; ++x) {
float val;
float min_dist = 999999.0f;
float sx = (float) x + 0.5f;
float sy = (float) y + 0.5f;
float x_gspace = (sx / scale_x);
float y_gspace = (sy / scale_y);
int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path
for (i=0; i < num_verts; ++i) {
float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;
// check against every point here rather than inside line/curve primitives -- @TODO: wrong if multiple 'moves' in a row produce a garbage point, and given culling, probably more efficient to do within line/curve
float dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy);
if (dist2 < min_dist*min_dist)
min_dist = (float) STBTT_sqrt(dist2);
if (verts[i].type == STBTT_vline) {
float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y;
// coarse culling against bbox
//if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist &&
// sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist)
float dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i];
STBTT_assert(i != 0);
if (dist < min_dist) {
// check position along line
// x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0)
// minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy)
float dx = x1-x0, dy = y1-y0;
float px = x0-sx, py = y0-sy;
// minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy
// derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve
float t = -(px*dx + py*dy) / (dx*dx + dy*dy);
if (t >= 0.0f && t <= 1.0f)
min_dist = dist;
}
} else if (verts[i].type == STBTT_vcurve) {
float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y;
float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y;
float box_x0 = STBTT_min(STBTT_min(x0,x1),x2);
float box_y0 = STBTT_min(STBTT_min(y0,y1),y2);
float box_x1 = STBTT_max(STBTT_max(x0,x1),x2);
float box_y1 = STBTT_max(STBTT_max(y0,y1),y2);
// coarse culling against bbox to avoid computing cubic unnecessarily
if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) {
int num=0;
float ax = x1-x0, ay = y1-y0;
float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;
float mx = x0 - sx, my = y0 - sy;
float res[3],px,py,t,it;
float a_inv = precompute[i];
if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula
float a = 3*(ax*bx + ay*by);
float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by);
float c = mx*ax+my*ay;
if (a == 0.0) { // if a is 0, it's linear
if (b != 0.0) {
res[num++] = -c/b;
}
} else {
float discriminant = b*b - 4*a*c;
if (discriminant < 0)
num = 0;
else {
float root = (float) STBTT_sqrt(discriminant);
res[0] = (-b - root)/(2*a);
res[1] = (-b + root)/(2*a);
num = 2; // don't bother distinguishing 1-solution case, as code below will still work
}
}
} else {
float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point
float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv;
float d = (mx*ax+my*ay) * a_inv;
num = stbtt__solve_cubic(b, c, d, res);
}
if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) {
t = res[0], it = 1.0f - t;
px = it*it*x0 + 2*t*it*x1 + t*t*x2;
py = it*it*y0 + 2*t*it*y1 + t*t*y2;
dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
if (dist2 < min_dist * min_dist)
min_dist = (float) STBTT_sqrt(dist2);
}
if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) {
t = res[1], it = 1.0f - t;
px = it*it*x0 + 2*t*it*x1 + t*t*x2;
py = it*it*y0 + 2*t*it*y1 + t*t*y2;
dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
if (dist2 < min_dist * min_dist)
min_dist = (float) STBTT_sqrt(dist2);
}
if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) {
t = res[2], it = 1.0f - t;
px = it*it*x0 + 2*t*it*x1 + t*t*x2;
py = it*it*y0 + 2*t*it*y1 + t*t*y2;
dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
if (dist2 < min_dist * min_dist)
min_dist = (float) STBTT_sqrt(dist2);
}
}
}
}
if (winding == 0)
min_dist = -min_dist; // if outside the shape, value is negative
val = onedge_value + pixel_dist_scale * min_dist;
if (val < 0)
val = 0;
else if (val > 255)
val = 255;
data[(y-iy0)*w+(x-ix0)] = (unsigned char) val;
}
}
STBTT_free(precompute, info->userdata);
STBTT_free(verts, info->userdata);
}
return data;
}
STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)
{
return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff);
}
STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata)
{
STBTT_free(bitmap, userdata);
}
//////////////////////////////////////////////////////////////////////////////
//
// font name matching -- recommended not to use this
//
// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string
static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2)
{
stbtt_int32 i=0;
// convert utf16 to utf8 and compare the results while converting
while (len2) {
stbtt_uint16 ch = s2[0]*256 + s2[1];
if (ch < 0x80) {
if (i >= len1) return -1;
if (s1[i++] != ch) return -1;
} else if (ch < 0x800) {
if (i+1 >= len1) return -1;
if (s1[i++] != 0xc0 + (ch >> 6)) return -1;
if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;
} else if (ch >= 0xd800 && ch < 0xdc00) {
stbtt_uint32 c;
stbtt_uint16 ch2 = s2[2]*256 + s2[3];
if (i+3 >= len1) return -1;
c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;
if (s1[i++] != 0xf0 + (c >> 18)) return -1;
if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;
if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1;
if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1;
s2 += 2; // plus another 2 below
len2 -= 2;
} else if (ch >= 0xdc00 && ch < 0xe000) {
return -1;
} else {
if (i+2 >= len1) return -1;
if (s1[i++] != 0xe0 + (ch >> 12)) return -1;
if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;
if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1;
}
s2 += 2;
len2 -= 2;
}
return i;
}
static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2)
{
return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2);
}
// returns results in whatever encoding you request... but note that 2-byte encodings
// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare
STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)
{
stbtt_int32 i,count,stringOffset;
stbtt_uint8 *fc = font->data;
stbtt_uint32 offset = font->fontstart;
stbtt_uint32 nm = stbtt__find_table(fc, offset, "name");
if (!nm) return NULL;
count = ttUSHORT(fc+nm+2);
stringOffset = nm + ttUSHORT(fc+nm+4);
for (i=0; i < count; ++i) {
stbtt_uint32 loc = nm + 6 + 12 * i;
if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)
&& languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {
*length = ttUSHORT(fc+loc+8);
return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10));
}
}
return NULL;
}
static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)
{
stbtt_int32 i;
stbtt_int32 count = ttUSHORT(fc+nm+2);
stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);
for (i=0; i < count; ++i) {
stbtt_uint32 loc = nm + 6 + 12 * i;
stbtt_int32 id = ttUSHORT(fc+loc+6);
if (id == target_id) {
// find the encoding
stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);
// is this a Unicode encoding?
if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {
stbtt_int32 slen = ttUSHORT(fc+loc+8);
stbtt_int32 off = ttUSHORT(fc+loc+10);
// check if there's a prefix match
stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);
if (matchlen >= 0) {
// check for target_id+1 immediately following, with same encoding & language
if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) {
slen = ttUSHORT(fc+loc+12+8);
off = ttUSHORT(fc+loc+12+10);
if (slen == 0) {
if (matchlen == nlen)
return 1;
} else if (matchlen < nlen && name[matchlen] == ' ') {
++matchlen;
if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))
return 1;
}
} else {
// if nothing immediately following
if (matchlen == nlen)
return 1;
}
}
}
// @TODO handle other encodings
}
}
return 0;
}
static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)
{
stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name);
stbtt_uint32 nm,hd;
if (!stbtt__isfont(fc+offset)) return 0;
// check italics/bold/underline flags in macStyle...
if (flags) {
hd = stbtt__find_table(fc, offset, "head");
if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;
}
nm = stbtt__find_table(fc, offset, "name");
if (!nm) return 0;
if (flags) {
// if we checked the macStyle flags, then just check the family and ignore the subfamily
if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1;
if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1;
if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
} else {
if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1;
if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1;
if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
}
return 0;
}
static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags)
{
stbtt_int32 i;
for (i=0;;++i) {
stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);
if (off < 0) return off;
if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))
return off;
}
}
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
#endif
STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset,
float pixel_height, unsigned char *pixels, int pw, int ph,
int first_char, int num_chars, stbtt_bakedchar *chardata)
{
return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata);
}
STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index)
{
return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index);
}
STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data)
{
return stbtt_GetNumberOfFonts_internal((unsigned char *) data);
}
STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset)
{
return stbtt_InitFont_internal(info, (unsigned char *) data, offset);
}
STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags)
{
return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags);
}
STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2)
{
return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2);
}
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
#endif // STB_TRUETYPE_IMPLEMENTATION
// FULL VERSION HISTORY
//
// 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod
// 1.18 (2018-01-29) add missing function
// 1.17 (2017-07-23) make more arguments const; doc fix
// 1.16 (2017-07-12) SDF support
// 1.15 (2017-03-03) make more arguments const
// 1.14 (2017-01-16) num-fonts-in-TTC function
// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts
// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
// 1.11 (2016-04-02) fix unused-variable warning
// 1.10 (2016-04-02) allow user-defined fabs() replacement
// fix memory leak if fontsize=0.0
// fix warning from duplicate typedef
// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges
// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
// allow PackFontRanges to pack and render in separate phases;
// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
// fixed an assert() bug in the new rasterizer
// replace assert() with STBTT_assert() in new rasterizer
// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine)
// also more precise AA rasterizer, except if shapes overlap
// remove need for STBTT_sort
// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC
// 1.04 (2015-04-15) typo in example
// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes
// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++
// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match
// non-oversampled; STBTT_POINT_SIZE for packed case only
// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling
// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg)
// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID
// 0.8b (2014-07-07) fix a warning
// 0.8 (2014-05-25) fix a few more warnings
// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back
// 0.6c (2012-07-24) improve documentation
// 0.6b (2012-07-20) fix a few more warnings
// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,
// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty
// 0.5 (2011-12-09) bugfixes:
// subpixel glyph renderer computed wrong bounding box
// first vertex of shape can be off-curve (FreeSans)
// 0.4b (2011-12-03) fixed an error in the font baking example
// 0.4 (2011-12-01) kerning, subpixel rendering (tor)
// bugfixes for:
// codepoint-to-glyph conversion using table fmt=12
// codepoint-to-glyph conversion using table fmt=4
// stbtt_GetBakedQuad with non-square texture (Zer)
// updated Hello World! sample to use kerning and subpixel
// fixed some warnings
// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM)
// userdata, malloc-from-userdata, non-zero fill (stb)
// 0.2 (2009-03-11) Fix unsigned/signed char warnings
// 0.1 (2009-03-09) First public release
//
/*
------------------------------------------------------------------------------
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.
------------------------------------------------------------------------------
*/
|
NVIDIA-Omniverse/PhysX/flow/external/imgui/imstb_textedit.h | // [DEAR IMGUI]
// This is a slightly modified version of stb_textedit.h 1.13.
// Those changes would need to be pushed into nothings/stb:
// - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321)
// Grep for [DEAR IMGUI] to find the changes.
// stb_textedit.h - v1.13 - public domain - Sean Barrett
// Development of this library was sponsored by RAD Game Tools
//
// This C header file implements the guts of a multi-line text-editing
// widget; you implement display, word-wrapping, and low-level string
// insertion/deletion, and stb_textedit will map user inputs into
// insertions & deletions, plus updates to the cursor position,
// selection state, and undo state.
//
// It is intended for use in games and other systems that need to build
// their own custom widgets and which do not have heavy text-editing
// requirements (this library is not recommended for use for editing large
// texts, as its performance does not scale and it has limited undo).
//
// Non-trivial behaviors are modelled after Windows text controls.
//
//
// LICENSE
//
// See end of file for license information.
//
//
// DEPENDENCIES
//
// Uses the C runtime function 'memmove', which you can override
// by defining STB_TEXTEDIT_memmove before the implementation.
// Uses no other functions. Performs no runtime allocations.
//
//
// VERSION HISTORY
//
// 1.13 (2019-02-07) fix bug in undo size management
// 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash
// 1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield
// 1.10 (2016-10-25) supress warnings about casting away const with -Wcast-qual
// 1.9 (2016-08-27) customizable move-by-word
// 1.8 (2016-04-02) better keyboard handling when mouse button is down
// 1.7 (2015-09-13) change y range handling in case baseline is non-0
// 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove
// 1.5 (2014-09-10) add support for secondary keys for OS X
// 1.4 (2014-08-17) fix signed/unsigned warnings
// 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary
// 1.2 (2014-05-27) fix some RAD types that had crept into the new code
// 1.1 (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE )
// 1.0 (2012-07-26) improve documentation, initial public release
// 0.3 (2012-02-24) bugfixes, single-line mode; insert mode
// 0.2 (2011-11-28) fixes to undo/redo
// 0.1 (2010-07-08) initial version
//
// ADDITIONAL CONTRIBUTORS
//
// Ulf Winklemann: move-by-word in 1.1
// Fabian Giesen: secondary key inputs in 1.5
// Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6
//
// Bugfixes:
// Scott Graham
// Daniel Keller
// Omar Cornut
// Dan Thompson
//
// USAGE
//
// This file behaves differently depending on what symbols you define
// before including it.
//
//
// Header-file mode:
//
// If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this,
// it will operate in "header file" mode. In this mode, it declares a
// single public symbol, STB_TexteditState, which encapsulates the current
// state of a text widget (except for the string, which you will store
// separately).
//
// To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a
// primitive type that defines a single character (e.g. char, wchar_t, etc).
//
// To save space or increase undo-ability, you can optionally define the
// following things that are used by the undo system:
//
// STB_TEXTEDIT_POSITIONTYPE small int type encoding a valid cursor position
// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow
// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer
//
// If you don't define these, they are set to permissive types and
// moderate sizes. The undo system does no memory allocations, so
// it grows STB_TexteditState by the worst-case storage which is (in bytes):
//
// [4 + 3 * sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATE_COUNT
// + sizeof(STB_TEXTEDIT_CHARTYPE) * STB_TEXTEDIT_UNDOCHAR_COUNT
//
//
// Implementation mode:
//
// If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it
// will compile the implementation of the text edit widget, depending
// on a large number of symbols which must be defined before the include.
//
// The implementation is defined only as static functions. You will then
// need to provide your own APIs in the same file which will access the
// static functions.
//
// The basic concept is that you provide a "string" object which
// behaves like an array of characters. stb_textedit uses indices to
// refer to positions in the string, implicitly representing positions
// in the displayed textedit. This is true for both plain text and
// rich text; even with rich text stb_truetype interacts with your
// code as if there was an array of all the displayed characters.
//
// Symbols that must be the same in header-file and implementation mode:
//
// STB_TEXTEDIT_CHARTYPE the character type
// STB_TEXTEDIT_POSITIONTYPE small type that is a valid cursor position
// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow
// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer
//
// Symbols you must define for implementation mode:
//
// STB_TEXTEDIT_STRING the type of object representing a string being edited,
// typically this is a wrapper object with other data you need
//
// STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1))
// STB_TEXTEDIT_LAYOUTROW(&r,obj,n) returns the results of laying out a line of characters
// starting from character #n (see discussion below)
// STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of the i'th character
// to the xpos of the i+1'th char for a line of characters
// starting at character #n (i.e. accounts for kerning
// with previous char)
// STB_TEXTEDIT_KEYTOTEXT(k) maps a keyboard input to an insertable character
// (return type is int, -1 means not valid to insert)
// STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 0-based
// STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize
// as manually wordwrapping for end-of-line positioning
//
// STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i
// STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n) insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*)
//
// STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key
//
// STB_TEXTEDIT_K_LEFT keyboard input to move cursor left
// STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right
// STB_TEXTEDIT_K_UP keyboard input to move cursor up
// STB_TEXTEDIT_K_DOWN keyboard input to move cursor down
// STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line // e.g. HOME
// STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line // e.g. END
// STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text // e.g. ctrl-HOME
// STB_TEXTEDIT_K_TEXTEND keyboard input to move cursor to end of text // e.g. ctrl-END
// STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character under cursor
// STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection or character left of cursor
// STB_TEXTEDIT_K_UNDO keyboard input to perform undo
// STB_TEXTEDIT_K_REDO keyboard input to perform redo
//
// Optional:
// STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode
// STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'),
// required for default WORDLEFT/WORDRIGHT handlers
// STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to
// STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to
// STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT
// STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT
// STB_TEXTEDIT_K_LINESTART2 secondary keyboard input to move cursor to start of line
// STB_TEXTEDIT_K_LINEEND2 secondary keyboard input to move cursor to end of line
// STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text
// STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text
//
// Todo:
// STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page
// STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page
//
// Keyboard input must be encoded as a single integer value; e.g. a character code
// and some bitflags that represent shift states. to simplify the interface, SHIFT must
// be a bitflag, so we can test the shifted state of cursor movements to allow selection,
// i.e. (STB_TEXTED_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow.
//
// You can encode other things, such as CONTROL or ALT, in additional bits, and
// then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example,
// my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN
// bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit,
// and I pass both WM_KEYDOWN and WM_CHAR events to the "key" function in the
// API below. The control keys will only match WM_KEYDOWN events because of the
// keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN
// bit so it only decodes WM_CHAR events.
//
// STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed
// row of characters assuming they start on the i'th character--the width and
// the height and the number of characters consumed. This allows this library
// to traverse the entire layout incrementally. You need to compute word-wrapping
// here.
//
// Each textfield keeps its own insert mode state, which is not how normal
// applications work. To keep an app-wide insert mode, update/copy the
// "insert_mode" field of STB_TexteditState before/after calling API functions.
//
// API
//
// void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line)
//
// void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
// void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
// int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
// int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len)
// void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key)
//
// Each of these functions potentially updates the string and updates the
// state.
//
// initialize_state:
// set the textedit state to a known good default state when initially
// constructing the textedit.
//
// click:
// call this with the mouse x,y on a mouse down; it will update the cursor
// and reset the selection start/end to the cursor point. the x,y must
// be relative to the text widget, with (0,0) being the top left.
//
// drag:
// call this with the mouse x,y on a mouse drag/up; it will update the
// cursor and the selection end point
//
// cut:
// call this to delete the current selection; returns true if there was
// one. you should FIRST copy the current selection to the system paste buffer.
// (To copy, just copy the current selection out of the string yourself.)
//
// paste:
// call this to paste text at the current cursor point or over the current
// selection if there is one.
//
// key:
// call this for keyboard inputs sent to the textfield. you can use it
// for "key down" events or for "translated" key events. if you need to
// do both (as in Win32), or distinguish Unicode characters from control
// inputs, set a high bit to distinguish the two; then you can define the
// various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit
// set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is
// clear. STB_TEXTEDIT_KEYTYPE defaults to int, but you can #define it to
// anything other type you wante before including.
//
//
// When rendering, you can read the cursor position and selection state from
// the STB_TexteditState.
//
//
// Notes:
//
// This is designed to be usable in IMGUI, so it allows for the possibility of
// running in an IMGUI that has NOT cached the multi-line layout. For this
// reason, it provides an interface that is compatible with computing the
// layout incrementally--we try to make sure we make as few passes through
// as possible. (For example, to locate the mouse pointer in the text, we
// could define functions that return the X and Y positions of characters
// and binary search Y and then X, but if we're doing dynamic layout this
// will run the layout algorithm many times, so instead we manually search
// forward in one pass. Similar logic applies to e.g. up-arrow and
// down-arrow movement.)
//
// If it's run in a widget that *has* cached the layout, then this is less
// efficient, but it's not horrible on modern computers. But you wouldn't
// want to edit million-line files with it.
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////
//// Header-file mode
////
////
#ifndef INCLUDE_STB_TEXTEDIT_H
#define INCLUDE_STB_TEXTEDIT_H
////////////////////////////////////////////////////////////////////////
//
// STB_TexteditState
//
// Definition of STB_TexteditState which you should store
// per-textfield; it includes cursor position, selection state,
// and undo state.
//
#ifndef STB_TEXTEDIT_UNDOSTATECOUNT
#define STB_TEXTEDIT_UNDOSTATECOUNT 99
#endif
#ifndef STB_TEXTEDIT_UNDOCHARCOUNT
#define STB_TEXTEDIT_UNDOCHARCOUNT 999
#endif
#ifndef STB_TEXTEDIT_CHARTYPE
#define STB_TEXTEDIT_CHARTYPE int
#endif
#ifndef STB_TEXTEDIT_POSITIONTYPE
#define STB_TEXTEDIT_POSITIONTYPE int
#endif
typedef struct
{
// private data
STB_TEXTEDIT_POSITIONTYPE where;
STB_TEXTEDIT_POSITIONTYPE insert_length;
STB_TEXTEDIT_POSITIONTYPE delete_length;
int char_storage;
} StbUndoRecord;
typedef struct
{
// private data
StbUndoRecord undo_rec [STB_TEXTEDIT_UNDOSTATECOUNT];
STB_TEXTEDIT_CHARTYPE undo_char[STB_TEXTEDIT_UNDOCHARCOUNT];
short undo_point, redo_point;
int undo_char_point, redo_char_point;
} StbUndoState;
typedef struct
{
/////////////////////
//
// public data
//
int cursor;
// position of the text cursor within the string
int select_start; // selection start point
int select_end;
// selection start and end point in characters; if equal, no selection.
// note that start may be less than or greater than end (e.g. when
// dragging the mouse, start is where the initial click was, and you
// can drag in either direction)
unsigned char insert_mode;
// each textfield keeps its own insert mode state. to keep an app-wide
// insert mode, copy this value in/out of the app state
/////////////////////
//
// private data
//
unsigned char cursor_at_end_of_line; // not implemented yet
unsigned char initialized;
unsigned char has_preferred_x;
unsigned char single_line;
unsigned char padding1, padding2, padding3;
float preferred_x; // this determines where the cursor up/down tries to seek to along x
StbUndoState undostate;
} STB_TexteditState;
////////////////////////////////////////////////////////////////////////
//
// StbTexteditRow
//
// Result of layout query, used by stb_textedit to determine where
// the text in each row is.
// result of layout query
typedef struct
{
float x0,x1; // starting x location, end x location (allows for align=right, etc)
float baseline_y_delta; // position of baseline relative to previous row's baseline
float ymin,ymax; // height of row above and below baseline
int num_chars;
} StbTexteditRow;
#endif //INCLUDE_STB_TEXTEDIT_H
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////
//// Implementation mode
////
////
// implementation isn't include-guarded, since it might have indirectly
// included just the "header" portion
#ifdef STB_TEXTEDIT_IMPLEMENTATION
#ifndef STB_TEXTEDIT_memmove
#include <string.h>
#define STB_TEXTEDIT_memmove memmove
#endif
/////////////////////////////////////////////////////////////////////////////
//
// Mouse input handling
//
// traverse the layout to locate the nearest character to a display position
static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y)
{
StbTexteditRow r;
int n = STB_TEXTEDIT_STRINGLEN(str);
float base_y = 0, prev_x;
int i=0, k;
r.x0 = r.x1 = 0;
r.ymin = r.ymax = 0;
r.num_chars = 0;
// search rows to find one that straddles 'y'
while (i < n) {
STB_TEXTEDIT_LAYOUTROW(&r, str, i);
if (r.num_chars <= 0)
return n;
if (i==0 && y < base_y + r.ymin)
return 0;
if (y < base_y + r.ymax)
break;
i += r.num_chars;
base_y += r.baseline_y_delta;
}
// below all text, return 'after' last character
if (i >= n)
return n;
// check if it's before the beginning of the line
if (x < r.x0)
return i;
// check if it's before the end of the line
if (x < r.x1) {
// search characters in row for one that straddles 'x'
prev_x = r.x0;
for (k=0; k < r.num_chars; ++k) {
float w = STB_TEXTEDIT_GETWIDTH(str, i, k);
if (x < prev_x+w) {
if (x < prev_x+w/2)
return k+i;
else
return k+i+1;
}
prev_x += w;
}
// shouldn't happen, but if it does, fall through to end-of-line case
}
// if the last character is a newline, return that. otherwise return 'after' the last character
if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE)
return i+r.num_chars-1;
else
return i+r.num_chars;
}
// API click: on mouse down, move the cursor to the clicked location, and reset the selection
static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
{
// In single-line mode, just always make y = 0. This lets the drag keep working if the mouse
// goes off the top or bottom of the text
if( state->single_line )
{
StbTexteditRow r;
STB_TEXTEDIT_LAYOUTROW(&r, str, 0);
y = r.ymin;
}
state->cursor = stb_text_locate_coord(str, x, y);
state->select_start = state->cursor;
state->select_end = state->cursor;
state->has_preferred_x = 0;
}
// API drag: on mouse drag, move the cursor and selection endpoint to the clicked location
static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
{
int p = 0;
// In single-line mode, just always make y = 0. This lets the drag keep working if the mouse
// goes off the top or bottom of the text
if( state->single_line )
{
StbTexteditRow r;
STB_TEXTEDIT_LAYOUTROW(&r, str, 0);
y = r.ymin;
}
if (state->select_start == state->select_end)
state->select_start = state->cursor;
p = stb_text_locate_coord(str, x, y);
state->cursor = state->select_end = p;
}
/////////////////////////////////////////////////////////////////////////////
//
// Keyboard input handling
//
// forward declarations
static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state);
static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state);
static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length);
static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length);
static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length);
typedef struct
{
float x,y; // position of n'th character
float height; // height of line
int first_char, length; // first char of row, and length
int prev_first; // first char of previous row
} StbFindState;
// find the x/y location of a character, and remember info about the previous row in
// case we get a move-up event (for page up, we'll have to rescan)
static void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *str, int n, int single_line)
{
StbTexteditRow r;
int prev_start = 0;
int z = STB_TEXTEDIT_STRINGLEN(str);
int i=0, first;
if (n == z) {
// if it's at the end, then find the last line -- simpler than trying to
// explicitly handle this case in the regular code
if (single_line) {
STB_TEXTEDIT_LAYOUTROW(&r, str, 0);
find->y = 0;
find->first_char = 0;
find->length = z;
find->height = r.ymax - r.ymin;
find->x = r.x1;
} else {
find->y = 0;
find->x = 0;
find->height = 1;
while (i < z) {
STB_TEXTEDIT_LAYOUTROW(&r, str, i);
prev_start = i;
i += r.num_chars;
}
find->first_char = i;
find->length = 0;
find->prev_first = prev_start;
}
return;
}
// search rows to find the one that straddles character n
find->y = 0;
for(;;) {
STB_TEXTEDIT_LAYOUTROW(&r, str, i);
if (n < i + r.num_chars)
break;
prev_start = i;
i += r.num_chars;
find->y += r.baseline_y_delta;
}
find->first_char = first = i;
find->length = r.num_chars;
find->height = r.ymax - r.ymin;
find->prev_first = prev_start;
// now scan to find xpos
find->x = r.x0;
for (i=0; first+i < n; ++i)
find->x += STB_TEXTEDIT_GETWIDTH(str, first, i);
}
#define STB_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end)
// make the selection/cursor state valid if client altered the string
static void stb_textedit_clamp(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
{
int n = STB_TEXTEDIT_STRINGLEN(str);
if (STB_TEXT_HAS_SELECTION(state)) {
if (state->select_start > n) state->select_start = n;
if (state->select_end > n) state->select_end = n;
// if clamping forced them to be equal, move the cursor to match
if (state->select_start == state->select_end)
state->cursor = state->select_start;
}
if (state->cursor > n) state->cursor = n;
}
// delete characters while updating undo
static void stb_textedit_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len)
{
stb_text_makeundo_delete(str, state, where, len);
STB_TEXTEDIT_DELETECHARS(str, where, len);
state->has_preferred_x = 0;
}
// delete the section
static void stb_textedit_delete_selection(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
{
stb_textedit_clamp(str, state);
if (STB_TEXT_HAS_SELECTION(state)) {
if (state->select_start < state->select_end) {
stb_textedit_delete(str, state, state->select_start, state->select_end - state->select_start);
state->select_end = state->cursor = state->select_start;
} else {
stb_textedit_delete(str, state, state->select_end, state->select_start - state->select_end);
state->select_start = state->cursor = state->select_end;
}
state->has_preferred_x = 0;
}
}
// canoncialize the selection so start <= end
static void stb_textedit_sortselection(STB_TexteditState *state)
{
if (state->select_end < state->select_start) {
int temp = state->select_end;
state->select_end = state->select_start;
state->select_start = temp;
}
}
// move cursor to first character of selection
static void stb_textedit_move_to_first(STB_TexteditState *state)
{
if (STB_TEXT_HAS_SELECTION(state)) {
stb_textedit_sortselection(state);
state->cursor = state->select_start;
state->select_end = state->select_start;
state->has_preferred_x = 0;
}
}
// move cursor to last character of selection
static void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
{
if (STB_TEXT_HAS_SELECTION(state)) {
stb_textedit_sortselection(state);
stb_textedit_clamp(str, state);
state->cursor = state->select_end;
state->select_start = state->select_end;
state->has_preferred_x = 0;
}
}
#ifdef STB_TEXTEDIT_IS_SPACE
static int is_word_boundary( STB_TEXTEDIT_STRING *str, int idx )
{
return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1;
}
#ifndef STB_TEXTEDIT_MOVEWORDLEFT
static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *str, int c )
{
--c; // always move at least one character
while( c >= 0 && !is_word_boundary( str, c ) )
--c;
if( c < 0 )
c = 0;
return c;
}
#define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous
#endif
#ifndef STB_TEXTEDIT_MOVEWORDRIGHT
static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *str, int c )
{
const int len = STB_TEXTEDIT_STRINGLEN(str);
++c; // always move at least one character
while( c < len && !is_word_boundary( str, c ) )
++c;
if( c > len )
c = len;
return c;
}
#define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next
#endif
#endif
// update selection and cursor to match each other
static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state)
{
if (!STB_TEXT_HAS_SELECTION(state))
state->select_start = state->select_end = state->cursor;
else
state->cursor = state->select_end;
}
// API cut: delete selection
static int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
{
if (STB_TEXT_HAS_SELECTION(state)) {
stb_textedit_delete_selection(str,state); // implicitly clamps
state->has_preferred_x = 0;
return 1;
}
return 0;
}
// API paste: replace existing selection with passed-in text
static int stb_textedit_paste_internal(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len)
{
// if there's a selection, the paste should delete it
stb_textedit_clamp(str, state);
stb_textedit_delete_selection(str,state);
// try to insert the characters
if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len)) {
stb_text_makeundo_insert(state, state->cursor, len);
state->cursor += len;
state->has_preferred_x = 0;
return 1;
}
// remove the undo since we didn't actually insert the characters
if (state->undostate.undo_point)
--state->undostate.undo_point;
return 0;
}
#ifndef STB_TEXTEDIT_KEYTYPE
#define STB_TEXTEDIT_KEYTYPE int
#endif
// API key: process a keyboard input
static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key)
{
retry:
switch (key) {
default: {
int c = STB_TEXTEDIT_KEYTOTEXT(key);
if (c > 0) {
STB_TEXTEDIT_CHARTYPE ch = (STB_TEXTEDIT_CHARTYPE) c;
// can't add newline in single-line mode
if (c == '\n' && state->single_line)
break;
if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) {
stb_text_makeundo_replace(str, state, state->cursor, 1, 1);
STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1);
if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) {
++state->cursor;
state->has_preferred_x = 0;
}
} else {
stb_textedit_delete_selection(str,state); // implicitly clamps
if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) {
stb_text_makeundo_insert(state, state->cursor, 1);
++state->cursor;
state->has_preferred_x = 0;
}
}
}
break;
}
#ifdef STB_TEXTEDIT_K_INSERT
case STB_TEXTEDIT_K_INSERT:
state->insert_mode = !state->insert_mode;
break;
#endif
case STB_TEXTEDIT_K_UNDO:
stb_text_undo(str, state);
state->has_preferred_x = 0;
break;
case STB_TEXTEDIT_K_REDO:
stb_text_redo(str, state);
state->has_preferred_x = 0;
break;
case STB_TEXTEDIT_K_LEFT:
// if currently there's a selection, move cursor to start of selection
if (STB_TEXT_HAS_SELECTION(state))
stb_textedit_move_to_first(state);
else
if (state->cursor > 0)
--state->cursor;
state->has_preferred_x = 0;
break;
case STB_TEXTEDIT_K_RIGHT:
// if currently there's a selection, move cursor to end of selection
if (STB_TEXT_HAS_SELECTION(state))
stb_textedit_move_to_last(str, state);
else
++state->cursor;
stb_textedit_clamp(str, state);
state->has_preferred_x = 0;
break;
case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT:
stb_textedit_clamp(str, state);
stb_textedit_prep_selection_at_cursor(state);
// move selection left
if (state->select_end > 0)
--state->select_end;
state->cursor = state->select_end;
state->has_preferred_x = 0;
break;
#ifdef STB_TEXTEDIT_MOVEWORDLEFT
case STB_TEXTEDIT_K_WORDLEFT:
if (STB_TEXT_HAS_SELECTION(state))
stb_textedit_move_to_first(state);
else {
state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor);
stb_textedit_clamp( str, state );
}
break;
case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT:
if( !STB_TEXT_HAS_SELECTION( state ) )
stb_textedit_prep_selection_at_cursor(state);
state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor);
state->select_end = state->cursor;
stb_textedit_clamp( str, state );
break;
#endif
#ifdef STB_TEXTEDIT_MOVEWORDRIGHT
case STB_TEXTEDIT_K_WORDRIGHT:
if (STB_TEXT_HAS_SELECTION(state))
stb_textedit_move_to_last(str, state);
else {
state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor);
stb_textedit_clamp( str, state );
}
break;
case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT:
if( !STB_TEXT_HAS_SELECTION( state ) )
stb_textedit_prep_selection_at_cursor(state);
state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor);
state->select_end = state->cursor;
stb_textedit_clamp( str, state );
break;
#endif
case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT:
stb_textedit_prep_selection_at_cursor(state);
// move selection right
++state->select_end;
stb_textedit_clamp(str, state);
state->cursor = state->select_end;
state->has_preferred_x = 0;
break;
case STB_TEXTEDIT_K_DOWN:
case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT: {
StbFindState find;
StbTexteditRow row;
int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;
if (state->single_line) {
// on windows, up&down in single-line behave like left&right
key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT);
goto retry;
}
if (sel)
stb_textedit_prep_selection_at_cursor(state);
else if (STB_TEXT_HAS_SELECTION(state))
stb_textedit_move_to_last(str,state);
// compute current position of cursor point
stb_textedit_clamp(str, state);
stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);
// now find character position down a row
if (find.length) {
float goal_x = state->has_preferred_x ? state->preferred_x : find.x;
float x;
int start = find.first_char + find.length;
state->cursor = start;
STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor);
x = row.x0;
for (i=0; i < row.num_chars; ++i) {
float dx = STB_TEXTEDIT_GETWIDTH(str, start, i);
#ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE
if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE)
break;
#endif
x += dx;
if (x > goal_x)
break;
++state->cursor;
}
stb_textedit_clamp(str, state);
state->has_preferred_x = 1;
state->preferred_x = goal_x;
if (sel)
state->select_end = state->cursor;
}
break;
}
case STB_TEXTEDIT_K_UP:
case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT: {
StbFindState find;
StbTexteditRow row;
int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;
if (state->single_line) {
// on windows, up&down become left&right
key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT);
goto retry;
}
if (sel)
stb_textedit_prep_selection_at_cursor(state);
else if (STB_TEXT_HAS_SELECTION(state))
stb_textedit_move_to_first(state);
// compute current position of cursor point
stb_textedit_clamp(str, state);
stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);
// can only go up if there's a previous row
if (find.prev_first != find.first_char) {
// now find character position up a row
float goal_x = state->has_preferred_x ? state->preferred_x : find.x;
float x;
state->cursor = find.prev_first;
STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor);
x = row.x0;
for (i=0; i < row.num_chars; ++i) {
float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i);
#ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE
if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE)
break;
#endif
x += dx;
if (x > goal_x)
break;
++state->cursor;
}
stb_textedit_clamp(str, state);
state->has_preferred_x = 1;
state->preferred_x = goal_x;
if (sel)
state->select_end = state->cursor;
}
break;
}
case STB_TEXTEDIT_K_DELETE:
case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT:
if (STB_TEXT_HAS_SELECTION(state))
stb_textedit_delete_selection(str, state);
else {
int n = STB_TEXTEDIT_STRINGLEN(str);
if (state->cursor < n)
stb_textedit_delete(str, state, state->cursor, 1);
}
state->has_preferred_x = 0;
break;
case STB_TEXTEDIT_K_BACKSPACE:
case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT:
if (STB_TEXT_HAS_SELECTION(state))
stb_textedit_delete_selection(str, state);
else {
stb_textedit_clamp(str, state);
if (state->cursor > 0) {
stb_textedit_delete(str, state, state->cursor-1, 1);
--state->cursor;
}
}
state->has_preferred_x = 0;
break;
#ifdef STB_TEXTEDIT_K_TEXTSTART2
case STB_TEXTEDIT_K_TEXTSTART2:
#endif
case STB_TEXTEDIT_K_TEXTSTART:
state->cursor = state->select_start = state->select_end = 0;
state->has_preferred_x = 0;
break;
#ifdef STB_TEXTEDIT_K_TEXTEND2
case STB_TEXTEDIT_K_TEXTEND2:
#endif
case STB_TEXTEDIT_K_TEXTEND:
state->cursor = STB_TEXTEDIT_STRINGLEN(str);
state->select_start = state->select_end = 0;
state->has_preferred_x = 0;
break;
#ifdef STB_TEXTEDIT_K_TEXTSTART2
case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT:
#endif
case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT:
stb_textedit_prep_selection_at_cursor(state);
state->cursor = state->select_end = 0;
state->has_preferred_x = 0;
break;
#ifdef STB_TEXTEDIT_K_TEXTEND2
case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT:
#endif
case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT:
stb_textedit_prep_selection_at_cursor(state);
state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str);
state->has_preferred_x = 0;
break;
#ifdef STB_TEXTEDIT_K_LINESTART2
case STB_TEXTEDIT_K_LINESTART2:
#endif
case STB_TEXTEDIT_K_LINESTART:
stb_textedit_clamp(str, state);
stb_textedit_move_to_first(state);
if (state->single_line)
state->cursor = 0;
else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE)
--state->cursor;
state->has_preferred_x = 0;
break;
#ifdef STB_TEXTEDIT_K_LINEEND2
case STB_TEXTEDIT_K_LINEEND2:
#endif
case STB_TEXTEDIT_K_LINEEND: {
int n = STB_TEXTEDIT_STRINGLEN(str);
stb_textedit_clamp(str, state);
stb_textedit_move_to_first(state);
if (state->single_line)
state->cursor = n;
else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE)
++state->cursor;
state->has_preferred_x = 0;
break;
}
#ifdef STB_TEXTEDIT_K_LINESTART2
case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT:
#endif
case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT:
stb_textedit_clamp(str, state);
stb_textedit_prep_selection_at_cursor(state);
if (state->single_line)
state->cursor = 0;
else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE)
--state->cursor;
state->select_end = state->cursor;
state->has_preferred_x = 0;
break;
#ifdef STB_TEXTEDIT_K_LINEEND2
case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT:
#endif
case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: {
int n = STB_TEXTEDIT_STRINGLEN(str);
stb_textedit_clamp(str, state);
stb_textedit_prep_selection_at_cursor(state);
if (state->single_line)
state->cursor = n;
else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE)
++state->cursor;
state->select_end = state->cursor;
state->has_preferred_x = 0;
break;
}
// @TODO:
// STB_TEXTEDIT_K_PGUP - move cursor up a page
// STB_TEXTEDIT_K_PGDOWN - move cursor down a page
}
}
/////////////////////////////////////////////////////////////////////////////
//
// Undo processing
//
// @OPTIMIZE: the undo/redo buffer should be circular
static void stb_textedit_flush_redo(StbUndoState *state)
{
state->redo_point = STB_TEXTEDIT_UNDOSTATECOUNT;
state->redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT;
}
// discard the oldest entry in the undo list
static void stb_textedit_discard_undo(StbUndoState *state)
{
if (state->undo_point > 0) {
// if the 0th undo state has characters, clean those up
if (state->undo_rec[0].char_storage >= 0) {
int n = state->undo_rec[0].insert_length, i;
// delete n characters from all other records
state->undo_char_point -= n;
STB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) (state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE)));
for (i=0; i < state->undo_point; ++i)
if (state->undo_rec[i].char_storage >= 0)
state->undo_rec[i].char_storage -= n; // @OPTIMIZE: get rid of char_storage and infer it
}
--state->undo_point;
STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) (state->undo_point*sizeof(state->undo_rec[0])));
}
}
// discard the oldest entry in the redo list--it's bad if this
// ever happens, but because undo & redo have to store the actual
// characters in different cases, the redo character buffer can
// fill up even though the undo buffer didn't
static void stb_textedit_discard_redo(StbUndoState *state)
{
int k = STB_TEXTEDIT_UNDOSTATECOUNT-1;
if (state->redo_point <= k) {
// if the k'th undo state has characters, clean those up
if (state->undo_rec[k].char_storage >= 0) {
int n = state->undo_rec[k].insert_length, i;
// move the remaining redo character data to the end of the buffer
state->redo_char_point += n;
STB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((STB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE)));
// adjust the position of all the other records to account for above memmove
for (i=state->redo_point; i < k; ++i)
if (state->undo_rec[i].char_storage >= 0)
state->undo_rec[i].char_storage += n;
}
// now move all the redo records towards the end of the buffer; the first one is at 'redo_point'
// {DEAR IMGUI]
size_t move_size = (size_t)((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point - 1) * sizeof(state->undo_rec[0]));
const char* buf_begin = (char*)state->undo_rec; (void)buf_begin;
const char* buf_end = (char*)state->undo_rec + sizeof(state->undo_rec); (void)buf_end;
IM_ASSERT(((char*)(state->undo_rec + state->redo_point)) >= buf_begin);
IM_ASSERT(((char*)(state->undo_rec + state->redo_point + 1) + move_size) <= buf_end);
STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point+1, state->undo_rec + state->redo_point, move_size);
// now move redo_point to point to the new one
++state->redo_point;
}
}
static StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numchars)
{
// any time we create a new undo record, we discard redo
stb_textedit_flush_redo(state);
// if we have no free records, we have to make room, by sliding the
// existing records down
if (state->undo_point == STB_TEXTEDIT_UNDOSTATECOUNT)
stb_textedit_discard_undo(state);
// if the characters to store won't possibly fit in the buffer, we can't undo
if (numchars > STB_TEXTEDIT_UNDOCHARCOUNT) {
state->undo_point = 0;
state->undo_char_point = 0;
return NULL;
}
// if we don't have enough free characters in the buffer, we have to make room
while (state->undo_char_point + numchars > STB_TEXTEDIT_UNDOCHARCOUNT)
stb_textedit_discard_undo(state);
return &state->undo_rec[state->undo_point++];
}
static STB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len)
{
StbUndoRecord *r = stb_text_create_undo_record(state, insert_len);
if (r == NULL)
return NULL;
r->where = pos;
r->insert_length = (STB_TEXTEDIT_POSITIONTYPE) insert_len;
r->delete_length = (STB_TEXTEDIT_POSITIONTYPE) delete_len;
if (insert_len == 0) {
r->char_storage = -1;
return NULL;
} else {
r->char_storage = state->undo_char_point;
state->undo_char_point += insert_len;
return &state->undo_char[r->char_storage];
}
}
static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
{
StbUndoState *s = &state->undostate;
StbUndoRecord u, *r;
if (s->undo_point == 0)
return;
// we need to do two things: apply the undo record, and create a redo record
u = s->undo_rec[s->undo_point-1];
r = &s->undo_rec[s->redo_point-1];
r->char_storage = -1;
r->insert_length = u.delete_length;
r->delete_length = u.insert_length;
r->where = u.where;
if (u.delete_length) {
// if the undo record says to delete characters, then the redo record will
// need to re-insert the characters that get deleted, so we need to store
// them.
// there are three cases:
// there's enough room to store the characters
// characters stored for *redoing* don't leave room for redo
// characters stored for *undoing* don't leave room for redo
// if the last is true, we have to bail
if (s->undo_char_point + u.delete_length >= STB_TEXTEDIT_UNDOCHARCOUNT) {
// the undo records take up too much character space; there's no space to store the redo characters
r->insert_length = 0;
} else {
int i;
// there's definitely room to store the characters eventually
while (s->undo_char_point + u.delete_length > s->redo_char_point) {
// should never happen:
if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT)
return;
// there's currently not enough room, so discard a redo record
stb_textedit_discard_redo(s);
}
r = &s->undo_rec[s->redo_point-1];
r->char_storage = s->redo_char_point - u.delete_length;
s->redo_char_point = s->redo_char_point - u.delete_length;
// now save the characters
for (i=0; i < u.delete_length; ++i)
s->undo_char[r->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i);
}
// now we can carry out the deletion
STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length);
}
// check type of recorded action:
if (u.insert_length) {
// easy case: was a deletion, so we need to insert n characters
STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length);
s->undo_char_point -= u.insert_length;
}
state->cursor = u.where + u.insert_length;
s->undo_point--;
s->redo_point--;
}
static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
{
StbUndoState *s = &state->undostate;
StbUndoRecord *u, r;
if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT)
return;
// we need to do two things: apply the redo record, and create an undo record
u = &s->undo_rec[s->undo_point];
r = s->undo_rec[s->redo_point];
// we KNOW there must be room for the undo record, because the redo record
// was derived from an undo record
u->delete_length = r.insert_length;
u->insert_length = r.delete_length;
u->where = r.where;
u->char_storage = -1;
if (r.delete_length) {
// the redo record requires us to delete characters, so the undo record
// needs to store the characters
if (s->undo_char_point + u->insert_length > s->redo_char_point) {
u->insert_length = 0;
u->delete_length = 0;
} else {
int i;
u->char_storage = s->undo_char_point;
s->undo_char_point = s->undo_char_point + u->insert_length;
// now save the characters
for (i=0; i < u->insert_length; ++i)
s->undo_char[u->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u->where + i);
}
STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length);
}
if (r.insert_length) {
// easy case: need to insert n characters
STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length);
s->redo_char_point += r.insert_length;
}
state->cursor = r.where + r.insert_length;
s->undo_point++;
s->redo_point++;
}
static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length)
{
stb_text_createundo(&state->undostate, where, 0, length);
}
static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length)
{
int i;
STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0);
if (p) {
for (i=0; i < length; ++i)
p[i] = STB_TEXTEDIT_GETCHAR(str, where+i);
}
}
static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length)
{
int i;
STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length);
if (p) {
for (i=0; i < old_length; ++i)
p[i] = STB_TEXTEDIT_GETCHAR(str, where+i);
}
}
// reset the state to default
static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_line)
{
state->undostate.undo_point = 0;
state->undostate.undo_char_point = 0;
state->undostate.redo_point = STB_TEXTEDIT_UNDOSTATECOUNT;
state->undostate.redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT;
state->select_end = state->select_start = 0;
state->cursor = 0;
state->has_preferred_x = 0;
state->preferred_x = 0;
state->cursor_at_end_of_line = 0;
state->initialized = 1;
state->single_line = (unsigned char) is_single_line;
state->insert_mode = 0;
}
// API initialize
static void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line)
{
stb_textedit_clear_state(state, is_single_line);
}
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
#endif
static int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *ctext, int len)
{
return stb_textedit_paste_internal(str, state, (STB_TEXTEDIT_CHARTYPE *) ctext, len);
}
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
#endif//STB_TEXTEDIT_IMPLEMENTATION
/*
------------------------------------------------------------------------------
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.
------------------------------------------------------------------------------
*/
|
NVIDIA-Omniverse/PhysX/flow/external/imgui/LICENSE.txt | The MIT License (MIT)
Copyright (c) 2014-2019 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.
|
NVIDIA-Omniverse/PhysX/flow/external/imgui/imgui.cpp | // dear imgui, v1.72b
// (main code and documentation)
// Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
// Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
// Get latest version at https://github.com/ocornut/imgui
// Releases change-log at https://github.com/ocornut/imgui/releases
// Technical Support for Getting Started https://discourse.dearimgui.org/c/getting-started
// Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/2529
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
// See LICENSE.txt for copyright and licensing details (standard MIT License).
// This library is free but I need your support to sustain development and maintenance.
// Businesses: you can support continued maintenance and development via support contracts or sponsoring, see docs/README.
// Individuals: you can support continued maintenance and development via donations or Patreon https://www.patreon.com/imgui.
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
// to a better solution or official support for them.
/*
Index of this file:
DOCUMENTATION
- MISSION STATEMENT
- END-USER GUIDE
- PROGRAMMER GUIDE (read me!)
- Read first.
- How to update to a newer version of Dear ImGui.
- Getting started with integrating Dear ImGui in your code/engine.
- This is how a simple application may look like (2 variations).
- This is how a simple rendering function may look like.
- Using gamepad/keyboard navigation controls.
- API BREAKING CHANGES (read me when you update!)
- FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
- Where is the documentation?
- Which version should I get?
- Who uses Dear ImGui?
- Why the odd dual naming, "Dear ImGui" vs "ImGui"?
- How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
- How can I display an image? What is ImTextureID, how does it works?
- Why are multiple widgets reacting when I interact with a single one? How can I have
multiple widgets with the same label or with an empty label? A primer on labels and the ID Stack...
- How can I use my own math types instead of ImVec2/ImVec4?
- How can I load a different font than the default?
- How can I easily use icons in my application?
- How can I load multiple fonts?
- How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
- How can I interact with standard C++ types (such as std::string and std::vector)?
- How can I use the drawing facilities without a Dear ImGui window? (using ImDrawList API)
- How can I use Dear ImGui on a platform that doesn't have a mouse or a keyboard? (input share, remoting, gamepad)
- I integrated Dear ImGui in my engine and the text or lines are blurry..
- I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
- How can I help?
CODE
(search for "[SECTION]" in the code to find them)
// [SECTION] FORWARD DECLARATIONS
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
// [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
// [SECTION] MISC HELPERS/UTILITIES (Maths, String, Format, Hash, File functions)
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
// [SECTION] ImGuiStorage
// [SECTION] ImGuiTextFilter
// [SECTION] ImGuiTextBuffer
// [SECTION] ImGuiListClipper
// [SECTION] RENDER HELPERS
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
// [SECTION] SCROLLING
// [SECTION] TOOLTIPS
// [SECTION] POPUPS
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
// [SECTION] DRAG AND DROP
// [SECTION] LOGGING/CAPTURING
// [SECTION] SETTINGS
// [SECTION] PLATFORM DEPENDENT HELPERS
// [SECTION] METRICS/DEBUG WINDOW
*/
//-----------------------------------------------------------------------------
// DOCUMENTATION
//-----------------------------------------------------------------------------
/*
MISSION STATEMENT
=================
- Easy to use to create code-driven and data-driven tools.
- Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
- Easy to hack and improve.
- Minimize screen real-estate usage.
- Minimize setup and maintenance.
- Minimize state storage on user side.
- Portable, minimize dependencies, run on target (consoles, phones, etc.).
- Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,.
opening a tree node for the first time, etc. but a typical frame should not allocate anything).
Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
- Doesn't look fancy, doesn't animate.
- Limited layout features, intricate layouts are typically crafted in code.
END-USER GUIDE
==============
- Double-click on title bar to collapse window.
- Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
- Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
- Click and drag on any empty space to move window.
- TAB/SHIFT+TAB to cycle through keyboard editable fields.
- CTRL+Click on a slider or drag box to input value as text.
- Use mouse wheel to scroll.
- Text editor:
- Hold SHIFT or use mouse to select text.
- CTRL+Left/Right to word jump.
- CTRL+Shift+Left/Right to select words.
- CTRL+A our Double-Click to select all.
- CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
- CTRL+Z,CTRL+Y to undo/redo.
- ESCAPE to revert text to its original value.
- You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
- Controls are automatically adjusted for OSX to match standard OSX text editing operations.
- General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
- General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://goo.gl/9LgVZW
PROGRAMMER GUIDE
================
READ FIRST:
- Read the FAQ below this section!
- Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction
or destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, less bugs.
- Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
- The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
- Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links docs/README.md.
- Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
For every application frame your UI code will be called only once. This is in contrast to e.g. Unity's own implementation of an IMGUI,
where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
- Our origin are on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
- This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
- Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
If you get an assert, read the messages and comments around the assert.
- C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
- C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
- C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI:
- Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
- Or maintain your own branch where you have imconfig.h modified.
- Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
likely be a comment about it. Please report any issue to the GitHub page!
- Try to keep your copy of dear imgui reasonably up to date.
GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE:
- Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
- Add the Dear ImGui source files to your projects or using your preferred build system.
It is recommended you build and statically link the .cpp files as part of your project and not as shared library (DLL).
- You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
- When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
- Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
phases of your own application. All rendering informatioe are stored into command-lists that you will retrieve after calling ImGui::Render().
- Refer to the bindings and demo applications in the examples/ folder for instruction on how to setup your code.
- If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
HOW A SIMPLE APPLICATION MAY LOOK LIKE:
EXHIBIT 1: USING THE EXAMPLE BINDINGS (imgui_impl_XXX.cpp files from the examples/ folder).
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
// Initialize helper Platform and Renderer bindings (here we are using imgui_impl_win32 and imgui_impl_dx11)
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
// Application main loop
while (true)
{
// Feed inputs to dear imgui, start new frame
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
// Any application code here
ImGui::Text("Hello, world!");
// Render dear imgui into screen
ImGui::Render();
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0);
}
// Shutdown
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
HOW A SIMPLE APPLICATION MAY LOOK LIKE:
EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / CUSTOM ENGINE.
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
// Build and load the texture atlas into a texture
// (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
int width, height;
unsigned char* pixels = NULL;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
// At this point you've got the texture data and you need to upload that your your graphic system:
// After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
// This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ below for details about ImTextureID.
MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
io.Fonts->TexID = (void*)texture;
// Application main loop
while (true)
{
// Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
// (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform bindings)
io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
io.DisplaySize.x = 1920.0f; // set the current display width
io.DisplaySize.y = 1280.0f; // set the current display height here
io.MousePos = my_mouse_pos; // set the mouse position
io.MouseDown[0] = my_mouse_buttons[0]; // set the mouse button states
io.MouseDown[1] = my_mouse_buttons[1];
// Call NewFrame(), after this point you can use ImGui::* functions anytime
// (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use Dear ImGui everywhere)
ImGui::NewFrame();
// Most of your application code here
ImGui::Text("Hello, world!");
MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
MyGameRender(); // may use any Dear ImGui functions as well!
// Render dear imgui, swap buffers
// (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
ImGui::EndFrame();
ImGui::Render();
ImDrawData* draw_data = ImGui::GetDrawData();
MyImGuiRenderFunction(draw_data);
SwapBuffers();
}
// Shutdown
ImGui::DestroyContext();
HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE:
void void MyImGuiRenderFunction(ImDrawData* draw_data)
{
// TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
// TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// The texture for the draw call is specified by pcmd->TextureId.
// The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
MyEngineBindTexture((MyTexture*)pcmd->TextureId);
// We are using scissoring to clip some objects. All low-level graphics API should supports it.
// - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
// (some elements visible outside their bounds) but you can fix that once everything else works!
// - Clipping coordinates are provided in imgui coordinates space (from draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize)
// In a single viewport application, draw_data->DisplayPos will always be (0,0) and draw_data->DisplaySize will always be == io.DisplaySize.
// However, in the interest of supporting multi-viewport applications in the future (see 'viewport' branch on github),
// always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
// - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
ImVec2 pos = draw_data->DisplayPos;
MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y));
// Render 'pcmd->ElemCount/3' indexed triangles.
// By default the indices ImDrawIdx are 16-bits, you can change them to 32-bits in imconfig.h if your engine doesn't support 16-bits indices.
MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
}
idx_buffer += pcmd->ElemCount;
}
}
}
- The examples/ folders contains many actual implementation of the pseudo-codes above.
- When calling NewFrame(), the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags are updated.
They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs from the
rest of your application. In every cases you need to pass on the inputs to Dear ImGui. Refer to the FAQ for more information.
- Please read the FAQ below!. Amusingly, it is called a FAQ because people frequently run into the same issues!
USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
- The gamepad/keyboard navigation is fairly functional and keeps being improved.
- Gamepad support is particularly useful to use dear imgui on a console system (e.g. PS4, Switch, XB1) without a mouse!
- You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787
- The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
- Gamepad:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
- Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
Note that io.NavInputs[] is cleared by EndFrame().
- See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
- We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
Your code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
- You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://goo.gl/9LgVZW.
- If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo
to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
- Keyboard:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
- When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
will be set. For more advanced uses, you may want to read from:
- io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
- io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
- or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
Please reach out if you think the game vs navigation input sharing could be improved.
- Mouse:
- PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
- Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
- On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
When that happens your back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding in examples/ do that.
(If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse as moving back and forth!)
(In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
to set a boolean to ignore your other external mouse positions until the external source is moved again.)
API BREAKING CHANGES
====================
Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
You can read releases logs https://github.com/ocornut/imgui/releases for more details.
- 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
- 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
- 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names.
- 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
Please reach out if you are affected.
- 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
- 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
- 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
- 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
- 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
- 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
- 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with a dummy small value!
- 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
- 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
- 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
- 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
- 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
- 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
- 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
- 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
- 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
- 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
- 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
- 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
- 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
- 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
- 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
- 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
- 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
- 2018/06/08 (1.62) - examples: the imgui_impl_xxx files have been split to separate platform (Win32, Glfw, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
old bindings will still work as is, however prefer using the separated bindings as they will be updated to support multi-viewports.
when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call.
in particular, note that old bindings called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
- 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
- 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
- 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
- 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
consistent with other functions. Kept redirection functions (will obsolete).
- 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
- 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some binding ahead of merging the Nav branch).
- 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
- 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
- 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
- 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
- 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
- 2018/02/07 (1.60) - reorganized context handling to be more explicit,
- YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
- removed Shutdown() function, as DestroyContext() serve this purpose.
- you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
- removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
- removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
- 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
- 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
- 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
- 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
- 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
- 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
- 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
- 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
- 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
- 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
- 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
- obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
- 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
- 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
- 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
- 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
- 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
- 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
- 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
- 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
- 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
- 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
- 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
- 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
- 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
- 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
- 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
- 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
- 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
- renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
- renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
- 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
- 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
- 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
- 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
- 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
- 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
- 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
- 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
- changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
- changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))'
- 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
- 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
- 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
- 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild().
- 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
- 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
- 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal.
- 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you.
If your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color.
ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col)
{
float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a;
return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a);
}
If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
- 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
- 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
- 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
- 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
- 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337).
- 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
- 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
- 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
- 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
- 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
- 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
- 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
- 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
- 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
- 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
- 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
- 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
- if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
- the signature of the io.RenderDrawListsFn handler has changed!
old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
- each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
- if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
- refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
- 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
- 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
- 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
- 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
- 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry!
- 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
- 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
- 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
- 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
- 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
- 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
- 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
- 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
- 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
- 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
- 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
- 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
- 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
- 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
- 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
- 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
- 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
- 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
- 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
- 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
- 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
(1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
font init: { const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); <..Upload texture to GPU..>; }
became: { unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); <..Upload texture to GPU>; io.Fonts->TexId = YourTextureIdentifier; }
you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs.
it is now recommended that you sample the font texture with bilinear interpolation.
(1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
(1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
(1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
- 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
- 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
- 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
- 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
- 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
- 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
- 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
- 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
- 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
- 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
- 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
======================================
Q: Where is the documentation?
A: This library is poorly documented at the moment and expects of the user to be acquainted with C/C++.
- Run the examples/ and explore them.
- See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
- The demo covers most features of Dear ImGui, so you can read the code and see its output.
- See documentation and comments at the top of imgui.cpp + effectively imgui.h.
- Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the examples/
folder to explain how to integrate Dear ImGui with your own engine/application.
- Your programming IDE is your friend, find the type or function declaration to find comments
associated to it.
Q: Which version should I get?
A: I occasionally tag Releases (https://github.com/ocornut/imgui/releases) but it is generally safe
and recommended to sync to master/latest. The library is fairly stable and regressions tend to be
fixed fast when reported. You may also peak at the 'docking' branch which includes:
- Docking/Merging features (https://github.com/ocornut/imgui/issues/2109)
- Multi-viewport features (https://github.com/ocornut/imgui/issues/1542)
Many projects are using this branch and it is kept in sync with master regularly.
Q: Who uses Dear ImGui?
A: See "Quotes" (https://github.com/ocornut/imgui/wiki/Quotes) and
"Software using Dear ImGui" (https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) Wiki pages
for a list of games/software which are publicly known to use dear imgui. Please add yours if you can!
Q: Why the odd dual naming, "Dear ImGui" vs "ImGui"?
A: The library started its life as "ImGui" due to the fact that I didn't give it a proper name when
when I released 1.0, and had no particular expectation that it would take off. However, the term IMGUI
(immediate-mode graphical user interface) was coined before and is being used in variety of other
situations (e.g. Unity uses it own implementation of the IMGUI paradigm).
To reduce the ambiguity without affecting existing code bases, I have decided on an alternate,
longer name "Dear ImGui" that people can use to refer to this specific library.
Please try to refer to this library as "Dear ImGui".
Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application?
A: You can read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags from the ImGuiIO structure (e.g. if (ImGui::GetIO().WantCaptureMouse) { ... } )
- When 'io.WantCaptureMouse' is set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application.
- When 'io.WantCaptureKeyboard' is set, imgui wants to use your keyboard state, and you may want to discard/hide the inputs from the rest of your application.
- When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS).
Note: you should always pass your mouse/keyboard inputs to imgui, even when the io.WantCaptureXXX flag are set false.
This is because imgui needs to detect that you clicked in the void to unfocus its own windows.
Note: The 'io.WantCaptureMouse' is more accurate that any attempt to "check if the mouse is hovering a window" (don't do that!).
It handle mouse dragging correctly (both dragging that started over your application or over an imgui window) and handle e.g. modal windows blocking inputs.
Those flags are updated by ImGui::NewFrame(). Preferably read the flags after calling NewFrame() if you can afford it, but reading them before is also
perfectly fine, as the bool toggle fairly rarely. If you have on a touch device, you might find use for an early call to UpdateHoveredWindowAndCaptureFlags().
Note: Text input widget releases focus on "Return KeyDown", so the subsequent "Return KeyUp" event that your application receive will typically
have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs
were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.)
Q: How can I display an image? What is ImTextureID, how does it works?
A: Short explanation:
- You may use functions such as ImGui::Image(), ImGui::ImageButton() or lower-level ImDrawList::AddImage() to emit draw calls that will use your own textures.
- Actual textures are identified in a way that is up to the user/engine. Those identifiers are stored and passed as ImTextureID (void*) value.
- Loading image files from the disk and turning them into a texture is not within the scope of Dear ImGui (for a good reason).
Please read documentations or tutorials on your graphics API to understand how to display textures on the screen before moving onward.
Long explanation:
- Dear ImGui's job is to create "meshes", defined in a renderer-agnostic format made of draw commands and vertices.
At the end of the frame those meshes (ImDrawList) will be displayed by your rendering function. They are made up of textured polygons and the code
to render them is generally fairly short (a few dozen lines). In the examples/ folder we provide functions for popular graphics API (OpenGL, DirectX, etc.).
- Each rendering function decides on a data type to represent "textures". The concept of what is a "texture" is entirely tied to your underlying engine/graphics API.
We carry the information to identify a "texture" in the ImTextureID type.
ImTextureID is nothing more that a void*, aka 4/8 bytes worth of data: just enough to store 1 pointer or 1 integer of your choice.
Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely pass ImTextureID values until they reach your rendering function.
- In the examples/ bindings, for each graphics API binding we decided on a type that is likely to be a good representation for specifying
an image from the end-user perspective. This is what the _examples_ rendering functions are using:
OpenGL: ImTextureID = GLuint (see ImGui_ImplGlfwGL3_RenderDrawData() function in imgui_impl_glfw_gl3.cpp)
DirectX9: ImTextureID = LPDIRECT3DTEXTURE9 (see ImGui_ImplDX9_RenderDrawData() function in imgui_impl_dx9.cpp)
DirectX11: ImTextureID = ID3D11ShaderResourceView* (see ImGui_ImplDX11_RenderDrawData() function in imgui_impl_dx11.cpp)
DirectX12: ImTextureID = D3D12_GPU_DESCRIPTOR_HANDLE (see ImGui_ImplDX12_RenderDrawData() function in imgui_impl_dx12.cpp)
For example, in the OpenGL example binding we store raw OpenGL texture identifier (GLuint) inside ImTextureID.
Whereas in the DirectX11 example binding we store a pointer to ID3D11ShaderResourceView inside ImTextureID, which is a higher-level structure
tying together both the texture and information about its format and how to read it.
- If you have a custom engine built over e.g. OpenGL, instead of passing GLuint around you may decide to use a high-level data type to carry information about
the texture as well as how to display it (shaders, etc.). The decision of what to use as ImTextureID can always be made better knowing how your codebase
is designed. If your engine has high-level data types for "textures" and "material" then you may want to use them.
If you are starting with OpenGL or DirectX or Vulkan and haven't built much of a rendering engine over them, keeping the default ImTextureID
representation suggested by the example bindings is probably the best choice.
(Advanced users may also decide to keep a low-level type in ImTextureID, and use ImDrawList callback and pass information to their renderer)
User code may do:
// Cast our texture type to ImTextureID / void*
MyTexture* texture = g_CoffeeTableTexture;
ImGui::Image((void*)texture, ImVec2(texture->Width, texture->Height));
The renderer function called after ImGui::Render() will receive that same value that the user code passed:
// Cast ImTextureID / void* stored in the draw command as our texture type
MyTexture* texture = (MyTexture*)pcmd->TextureId;
MyEngineBindTexture2D(texture);
Once you understand this design you will understand that loading image files and turning them into displayable textures is not within the scope of Dear ImGui.
This is by design and is actually a good thing, because it means your code has full control over your data types and how you display them.
If you want to display an image file (e.g. PNG file) into the screen, please refer to documentation and tutorials for the graphics API you are using.
Here's a simplified OpenGL example using stb_image.h:
// Use stb_image.h to load a PNG from disk and turn it into raw RGBA pixel data:
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
[...]
int my_image_width, my_image_height;
unsigned char* my_image_data = stbi_load("my_image.png", &my_image_width, &my_image_height, NULL, 4);
// Turn the RGBA pixel data into an OpenGL texture:
GLuint my_opengl_texture;
glGenTextures(1, &my_opengl_texture);
glBindTexture(GL_TEXTURE_2D, my_opengl_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
// Now that we have an OpenGL texture, assuming our imgui rendering function (imgui_impl_xxx.cpp file) takes GLuint as ImTextureID, we can display it:
ImGui::Image((void*)(intptr_t)my_opengl_texture, ImVec2(my_image_width, my_image_height));
C/C++ tip: a void* is pointer-sized storage. You may safely store any pointer or integer into it by casting your value to ImTextureID / void*, and vice-versa.
Because both end-points (user code and rendering function) are under your control, you know exactly what is stored inside the ImTextureID / void*.
Examples:
GLuint my_tex = XXX;
void* my_void_ptr;
my_void_ptr = (void*)(intptr_t)my_tex; // cast a GLuint into a void* (we don't take its address! we literally store the value inside the pointer)
my_tex = (GLuint)(intptr_t)my_void_ptr; // cast a void* into a GLuint
ID3D11ShaderResourceView* my_dx11_srv = XXX;
void* my_void_ptr;
my_void_ptr = (void*)my_dx11_srv; // cast a ID3D11ShaderResourceView* into an opaque void*
my_dx11_srv = (ID3D11ShaderResourceView*)my_void_ptr; // cast a void* into a ID3D11ShaderResourceView*
Finally, you may call ImGui::ShowMetricsWindow() to explore/visualize/understand how the ImDrawList are generated.
Q: Why are multiple widgets reacting when I interact with a single one?
Q: How can I have multiple widgets with the same label or with an empty label?
A: A primer on labels and the ID Stack...
Dear ImGui internally need to uniquely identify UI elements.
Elements that are typically not clickable (such as calls to the Text functions) don't need an ID.
Interactive widgets (such as calls to Button buttons) need a unique ID.
Unique ID are used internally to track active widgets and occasionally associate state to widgets.
Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element.
- Unique ID are often derived from a string label:
Button("OK"); // Label = "OK", ID = hash of (..., "OK")
Button("Cancel"); // Label = "Cancel", ID = hash of (..., "Cancel")
- ID are uniquely scoped within windows, tree nodes, etc. which all pushes to the ID stack. Having
two buttons labeled "OK" in different windows or different tree locations is fine.
We used "..." above to signify whatever was already pushed to the ID stack previously:
Begin("MyWindow");
Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK")
End();
Begin("MyOtherWindow");
Button("OK"); // Label = "OK", ID = hash of ("MyOtherWindow", "OK")
End();
- If you have a same ID twice in the same location, you'll have a conflict:
Button("OK");
Button("OK"); // ID collision! Interacting with either button will trigger the first one.
Fear not! this is easy to solve and there are many ways to solve it!
- Solving ID conflict in a simple/local context:
When passing a label you can optionally specify extra ID information within string itself.
Use "##" to pass a complement to the ID that won't be visible to the end-user.
This helps solving the simple collision cases when you know e.g. at compilation time which items
are going to be created:
Begin("MyWindow");
Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play")
Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above
Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo2") // Different from above
End();
- If you want to completely hide the label, but still need an ID:
Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox!
- Occasionally/rarely you might want change a label while preserving a constant ID. This allows
you to animate labels. For example you may want to include varying information in a window title bar,
but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID:
Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID")
Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same as above, even though the label looks different
sprintf(buf, "My game (%f FPS)###MyGame", fps);
Begin(buf); // Variable title, ID = hash of "MyGame"
- Solving ID conflict in a more general manner:
Use PushID() / PopID() to create scopes and manipulate the ID stack, as to avoid ID conflicts
within the same window. This is the most convenient way of distinguishing ID when iterating and
creating many UI elements programmatically.
You can push a pointer, a string or an integer value into the ID stack.
Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack.
At each level of the stack we store the seed used for items at this level of the ID stack.
Begin("Window");
for (int i = 0; i < 100; i++)
{
PushID(i); // Push i to the id tack
Button("Click"); // Label = "Click", ID = hash of ("Window", i, "Click")
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj);
Button("Click"); // Label = "Click", ID = hash of ("Window", obj pointer, "Click")
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj->Name);
Button("Click"); // Label = "Click", ID = hash of ("Window", obj->Name, "Click")
PopID();
}
End();
- You can stack multiple prefixes into the ID stack:
Button("Click"); // Label = "Click", ID = hash of (..., "Click")
PushID("node");
Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
PushID(my_ptr);
Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click")
PopID();
PopID();
- Tree nodes implicitly creates a scope for you by calling PushID().
Button("Click"); // Label = "Click", ID = hash of (..., "Click")
if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag)
{
Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
TreePop();
}
- When working with trees, ID are used to preserve the open/close state of each tree node.
Depending on your use cases you may want to use strings, indices or pointers as ID.
e.g. when following a single pointer that may change over time, using a static string as ID
will preserve your node open/closed state when the targeted object change.
e.g. when displaying a list of objects, using indices or pointers as ID will preserve the
node open/closed state differently. See what makes more sense in your situation!
Q: How can I use my own math types instead of ImVec2/ImVec4?
A: You can edit imconfig.h and setup the IM_VEC2_CLASS_EXTRA/IM_VEC4_CLASS_EXTRA macros to add implicit type conversions.
This way you'll be able to use your own types everywhere, e.g. passing glm::vec2 to ImGui functions instead of ImVec2.
Q: How can I load a different font than the default?
A: Use the font atlas to load the TTF/OTF file you want:
ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
Default is ProggyClean.ttf, monospace, rendered at size 13, embedded in dear imgui's source code.
(Tip: monospace fonts are convenient because they allow to facilitate horizontal alignment directly at the string level.)
(Read the 'misc/fonts/README.txt' file for more details about font loading.)
New programmers: remember that in C/C++ and most programming languages if you want to use a
backslash \ within a string literal, you need to write it double backslash "\\":
io.Fonts->AddFontFromFileTTF("MyDataFolder\MyFontFile.ttf", size_in_pixels); // WRONG (you are escape the M here!)
io.Fonts->AddFontFromFileTTF("MyDataFolder\\MyFontFile.ttf", size_in_pixels); // CORRECT
io.Fonts->AddFontFromFileTTF("MyDataFolder/MyFontFile.ttf", size_in_pixels); // ALSO CORRECT
Q: How can I easily use icons in my application?
A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you
main font. Then you can refer to icons within your strings.
You may want to see ImFontConfig::GlyphMinAdvanceX to make your icon look monospace to facilitate alignment.
(Read the 'misc/fonts/README.txt' file for more details about icons font loading.)
With some extra effort, you may use colorful icon by registering custom rectangle space inside the font atlas,
and copying your own graphics data into it. See misc/fonts/README.txt about using the AddCustomRectFontGlyph API.
Q: How can I load multiple fonts?
A: Use the font atlas to pack them into a single texture:
(Read the 'misc/fonts/README.txt' file and the code in ImFontAtlas for more details.)
ImGuiIO& io = ImGui::GetIO();
ImFont* font0 = io.Fonts->AddFontDefault();
ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels);
io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
// the first loaded font gets used by default
// use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime
// Options
ImFontConfig config;
config.OversampleH = 2;
config.OversampleV = 1;
config.GlyphOffset.y -= 1.0f; // Move everything by 1 pixels up
config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, &config);
// Combine multiple fonts into one (e.g. for icon fonts)
static ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
ImFontConfig config;
config.MergeMode = true;
io.Fonts->AddFontDefault();
io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs
Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
A: When loading a font, pass custom Unicode ranges to specify the glyphs to load.
// Add default Japanese ranges
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese());
// Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need)
ImVector<ImWchar> ranges;
ImFontGlyphRangesBuilder builder;
builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters)
builder.AddChar(0x7262); // Add a specific character
builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges
builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted)
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data);
All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8
by using the u8"hello" syntax. Specifying literal in your source code using a local code page
(such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work!
Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
Text input: it is up to your application to pass the right character code by calling io.AddInputCharacter().
The applications in examples/ are doing that.
Windows: you can use the WM_CHAR or WM_UNICHAR or WM_IME_CHAR message (depending if your app is built using Unicode or MultiByte mode).
You may also use MultiByteToWideChar() or ToUnicode() to retrieve Unicode codepoints from MultiByte characters or keyboard state.
Windows: if your language is relying on an Input Method Editor (IME), you copy the HWND of your window to io.ImeWindowHandle in order for
the default implementation of io.ImeSetInputScreenPosFn() to set your Microsoft IME position correctly.
Q: How can I interact with standard C++ types (such as std::string and std::vector)?
A: - Being highly portable (bindings for several languages, frameworks, programming style, obscure or older platforms/compilers),
and aiming for compatibility & performance suitable for every modern real-time game engines, dear imgui does not use
any of std C++ types. We use raw types (e.g. char* instead of std::string) because they adapt to more use cases.
- To use ImGui::InputText() with a std::string or any resizable string class, see misc/cpp/imgui_stdlib.h.
- To use combo boxes and list boxes with std::vector or any other data structure: the BeginCombo()/EndCombo() API
lets you iterate and submit items yourself, so does the ListBoxHeader()/ListBoxFooter() API.
Prefer using them over the old and awkward Combo()/ListBox() api.
- Generally for most high-level types you should be able to access the underlying data type.
You may write your own one-liner wrappers to facilitate user code (tip: add new functions in ImGui:: namespace from your code).
- Dear ImGui applications often need to make intensive use of strings. It is expected that many of the strings you will pass
to the API are raw literals (free in C/C++) or allocated in a manner that won't incur a large cost on your application.
Please bear in mind that using std::string on applications with large amount of UI may incur unsatisfactory performances.
Modern implementations of std::string often include small-string optimization (which is often a local buffer) but those
are not configurable and not the same across implementations.
- If you are finding your UI traversal cost to be too large, make sure your string usage is not leading to excessive amount
of heap allocations. Consider using literals, statically sized buffers and your own helper functions. A common pattern
is that you will need to build lots of strings on the fly, and their maximum length can be easily be scoped ahead.
One possible implementation of a helper to facilitate printf-style building of strings: https://github.com/ocornut/Str
This is a small helper where you can instance strings with configurable local buffers length. Many game engines will
provide similar or better string helpers.
Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
A: - You can create a dummy window. Call Begin() with the NoBackground | NoDecoration | NoSavedSettings | NoInputs flags.
(The ImGuiWindowFlags_NoDecoration flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse)
Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
- You can call ImGui::GetBackgroundDrawList() or ImGui::GetForegroundDrawList() and use those draw list to display
contents behind or over every other imgui windows (one bg/fg drawlist per viewport).
- You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create
your own ImDrawListSharedData, and then call your rendered code with your own ImDrawList or ImDrawData data.
Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
A: - You can control Dear ImGui with a gamepad. Read about navigation in "Using gamepad/keyboard navigation controls".
(short version: map gamepad inputs into the io.NavInputs[] array + set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad)
- You can share your computer mouse seamlessly with your console/tablet/phone using Synergy (https://symless.com/synergy)
This is the preferred solution for developer productivity.
In particular, the "micro-synergy-client" repository (https://github.com/symless/micro-synergy-client) has simple
and portable source code (uSynergy.c/.h) for a small embeddable client that you can use on any platform to connect
to your host computer, based on the Synergy 1.x protocol. Make sure you download the Synergy 1 server on your computer.
Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-like protocols.
- You may also use a third party solution such as Remote ImGui (https://github.com/JordiRos/remoteimgui) which sends
the vertices to render over the local network, allowing you to use Dear ImGui even on a screen-less machine.
- For touch inputs, you can increase the hit box of widgets (via the style.TouchPadding setting) to accommodate
for the lack of precision of touch inputs, but it is recommended you use a mouse or gamepad to allow optimizing
for screen real-estate and precision.
Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension.
Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
A: You are probably mishandling the clipping rectangles in your render function.
Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height).
Q: How can I help?
A: - If you are experienced with Dear ImGui and C++, look at the github issues, look at the Wiki, read docs/TODO.txt
and see how you want to help and can help!
- Businesses: convince your company to fund development via support contracts/sponsoring! This is among the most useful thing you can do for dear imgui.
- Individuals: you can also become a Patron (http://www.patreon.com/imgui) or donate on PayPal! See README.
- Disclose your usage of dear imgui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/1902). Visuals are ideal as they inspire other programmers.
But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions.
- If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately).
- tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window.
this is also useful to set yourself in the context of another window (to get/set other settings)
- tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug".
- tip: the ImGuiOnceUponAFrame helper will allow run the block of code only once a frame. You can use it to quickly add custom UI in the middle
of a deep nested inner loop in your code.
- tip: you can call Render() multiple times (e.g for VR renders).
- tip: call and read the ShowDemoWindow() code in imgui_demo.cpp for more example of how to use ImGui!
*/
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
#include <ctype.h> // toupper
#include <stdio.h> // vsnprintf, sscanf, printf
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
// Debug options
#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
#define IMGUI_DEBUG_INI_SETTINGS 0 // Save additional comments in .ini file
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great!
#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference is.
#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
#pragma clang diagnostic ignored "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
#endif
#if __has_warning("-Wdouble-promotion")
#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
#endif
#elif defined(__GNUC__)
// We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association.
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by back-end)
static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow().
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certaint time, unless mouse moved.
//-------------------------------------------------------------------------
// [SECTION] FORWARD DECLARATIONS
//-------------------------------------------------------------------------
static void SetCurrentWindow(ImGuiWindow* window);
static void FindHoveredWindow();
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
static void CheckStacksSize(ImGuiWindow* window, bool write);
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges);
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
static ImRect GetViewportRect();
// Settings
static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
// Platform Dependents default implementation for IO functions
static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
namespace ImGui
{
static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags);
// Navigation
static void NavUpdate();
static void NavUpdateWindowing();
static void NavUpdateWindowingList();
static void NavUpdateMoveResult();
static float NavUpdatePageUpPageDown(int allowed_dir_flags);
static inline void NavUpdateAnyRequestFlag();
static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id);
static ImVec2 NavCalcPreferredRefPos();
static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
static int FindWindowFocusIndex(ImGuiWindow* window);
// Misc
static void UpdateMouseInputs();
static void UpdateMouseWheel();
static bool UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
static void UpdateDebugToolItemPicker();
static void RenderWindowOuterBorders(ImGuiWindow* window);
static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
}
//-----------------------------------------------------------------------------
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
//-----------------------------------------------------------------------------
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
// ImGui::CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext().
// 1) Important: globals are not shared across DLL boundaries! If you use DLLs or any form of hot-reloading: you will need to call
// SetCurrentContext() (with the pointer you got from CreateContext) from each unique static/DLL boundary, and after each hot-reloading.
// In your debugger, add GImGui to your watch window and notice how its value changes depending on which location you are currently stepping into.
// 2) Important: Dear ImGui functions are not thread-safe because of this pointer.
// If you want thread-safety to allow N threads to access N different contexts, you can:
// - Change this variable to use thread local storage so each thread can refer to a different context, in imconfig.h:
// struct ImGuiContext;
// extern thread_local ImGuiContext* MyImGuiTLS;
// #define GImGui MyImGuiTLS
// And then define MyImGuiTLS in one of your cpp file. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
// - Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from different namespace.
#ifndef GImGui
ImGuiContext* GImGui = NULL;
#endif
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
// If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file.
// Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
#else
static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
#endif
static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper;
static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper;
static void* GImAllocatorUserData = NULL;
//-----------------------------------------------------------------------------
// [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
//-----------------------------------------------------------------------------
ImGuiStyle::ImGuiStyle()
{
Alpha = 1.0f; // Global alpha applies to everything in ImGui
WindowPadding = ImVec2(8,8); // Padding within a window
WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
WindowMinSize = ImVec2(32,32); // Minimum window size
WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
TabBorderSize = 0.0f; // Thickness of border around tabs.
ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text when button is larger than text.
DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows.
DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
// Default theme
ImGui::StyleColorsDark(this);
}
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
void ImGuiStyle::ScaleAllSizes(float scale_factor)
{
WindowPadding = ImFloor(WindowPadding * scale_factor);
WindowRounding = ImFloor(WindowRounding * scale_factor);
WindowMinSize = ImFloor(WindowMinSize * scale_factor);
ChildRounding = ImFloor(ChildRounding * scale_factor);
PopupRounding = ImFloor(PopupRounding * scale_factor);
FramePadding = ImFloor(FramePadding * scale_factor);
FrameRounding = ImFloor(FrameRounding * scale_factor);
ItemSpacing = ImFloor(ItemSpacing * scale_factor);
ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
IndentSpacing = ImFloor(IndentSpacing * scale_factor);
ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
GrabMinSize = ImFloor(GrabMinSize * scale_factor);
GrabRounding = ImFloor(GrabRounding * scale_factor);
TabRounding = ImFloor(TabRounding * scale_factor);
DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
}
ImGuiIO::ImGuiIO()
{
// Most fields are initialized with zero
memset(this, 0, sizeof(*this));
// Settings
ConfigFlags = ImGuiConfigFlags_None;
BackendFlags = ImGuiBackendFlags_None;
DisplaySize = ImVec2(-1.0f, -1.0f);
DeltaTime = 1.0f/60.0f;
IniSavingRate = 5.0f;
IniFilename = "imgui.ini";
LogFilename = "imgui_log.txt";
MouseDoubleClickTime = 0.30f;
MouseDoubleClickMaxDist = 6.0f;
for (int i = 0; i < ImGuiKey_COUNT; i++)
KeyMap[i] = -1;
KeyRepeatDelay = 0.250f;
KeyRepeatRate = 0.050f;
UserData = NULL;
Fonts = NULL;
FontGlobalScale = 1.0f;
FontDefault = NULL;
FontAllowUserScaling = false;
DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
// Miscellaneous options
MouseDrawCursor = false;
#ifdef __APPLE__
ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
#else
ConfigMacOSXBehaviors = false;
#endif
ConfigInputTextCursorBlink = true;
ConfigWindowsResizeFromEdges = true;
ConfigWindowsMoveFromTitleBarOnly = false;
// Platform Functions
BackendPlatformName = BackendRendererName = NULL;
BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
ClipboardUserData = NULL;
ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
ImeWindowHandle = NULL;
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
RenderDrawListsFn = NULL;
#endif
// Input (NB: we already have memset zero the entire structure!)
MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
MouseDragThreshold = 6.0f;
for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;
}
// Pass in translated ASCII characters for text input.
// - with glfw you can get those from the callback set in glfwSetCharCallback()
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
void ImGuiIO::AddInputCharacter(unsigned int c)
{
if (c > 0 && c < 0x10000)
InputQueueCharacters.push_back((ImWchar)c);
}
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
{
while (*utf8_chars != 0)
{
unsigned int c = 0;
utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
if (c > 0 && c < 0x10000)
InputQueueCharacters.push_back((ImWchar)c);
}
}
void ImGuiIO::ClearInputCharacters()
{
InputQueueCharacters.resize(0);
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (Maths, String, Format, Hash, File functions)
//-----------------------------------------------------------------------------
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
{
ImVec2 ap = p - a;
ImVec2 ab_dir = b - a;
float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
if (dot < 0.0f)
return a;
float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
if (dot > ab_len_sqr)
return b;
return a + ab_dir * dot / ab_len_sqr;
}
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
{
bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
return ((b1 == b2) && (b2 == b3));
}
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
{
ImVec2 v0 = b - a;
ImVec2 v1 = c - a;
ImVec2 v2 = p - a;
const float denom = v0.x * v1.y - v1.x * v0.y;
out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
out_u = 1.0f - out_v - out_w;
}
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
{
ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
float dist2_ab = ImLengthSqr(p - proj_ab);
float dist2_bc = ImLengthSqr(p - proj_bc);
float dist2_ca = ImLengthSqr(p - proj_ca);
float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
if (m == dist2_ab)
return proj_ab;
if (m == dist2_bc)
return proj_bc;
return proj_ca;
}
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
int ImStricmp(const char* str1, const char* str2)
{
int d;
while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
return d;
}
int ImStrnicmp(const char* str1, const char* str2, size_t count)
{
int d = 0;
while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
return d;
}
void ImStrncpy(char* dst, const char* src, size_t count)
{
if (count < 1)
return;
if (count > 1)
strncpy(dst, src, count - 1);
dst[count - 1] = 0;
}
char* ImStrdup(const char* str)
{
size_t len = strlen(str);
void* buf = IM_ALLOC(len + 1);
return (char*)memcpy(buf, (const void*)str, len + 1);
}
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
{
size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
size_t src_size = strlen(src) + 1;
if (dst_buf_size < src_size)
{
IM_FREE(dst);
dst = (char*)IM_ALLOC(src_size);
if (p_dst_size)
*p_dst_size = src_size;
}
return (char*)memcpy(dst, (const void*)src, src_size);
}
const char* ImStrchrRange(const char* str, const char* str_end, char c)
{
const char* p = (const char*)memchr(str, (int)c, str_end - str);
return p;
}
int ImStrlenW(const ImWchar* str)
{
//return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bits
int n = 0;
while (*str++) n++;
return n;
}
// Find end-of-line. Return pointer will point to either first \n, either str_end.
const char* ImStreolRange(const char* str, const char* str_end)
{
const char* p = (const char*)memchr(str, '\n', str_end - str);
return p ? p : str_end;
}
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
{
while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
buf_mid_line--;
return buf_mid_line;
}
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
{
if (!needle_end)
needle_end = needle + strlen(needle);
const char un0 = (char)toupper(*needle);
while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
{
if (toupper(*haystack) == un0)
{
const char* b = needle + 1;
for (const char* a = haystack + 1; b < needle_end; a++, b++)
if (toupper(*a) != toupper(*b))
break;
if (b == needle_end)
return haystack;
}
haystack++;
}
return NULL;
}
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
void ImStrTrimBlanks(char* buf)
{
char* p = buf;
while (p[0] == ' ' || p[0] == '\t') // Leading blanks
p++;
char* p_start = p;
while (*p != 0) // Find end of string
p++;
while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
p--;
if (p_start != buf) // Copy memory if we had leading blanks
memmove(buf, p_start, p - p_start);
buf[p - p_start] = 0; // Zero terminate
}
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
// B) When buf==NULL vsnprintf() will return the output size.
#ifndef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
//#define IMGUI_USE_STB_SPRINTF
#ifdef IMGUI_USE_STB_SPRINTF
#define STB_SPRINTF_IMPLEMENTATION
#include "imstb_sprintf.h"
#endif
#if defined(_MSC_VER) && !defined(vsnprintf)
#define vsnprintf _vsnprintf
#endif
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
#ifdef IMGUI_USE_STB_SPRINTF
int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
#else
int w = vsnprintf(buf, buf_size, fmt, args);
#endif
va_end(args);
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
{
#ifdef IMGUI_USE_STB_SPRINTF
int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
#else
int w = vsnprintf(buf, buf_size, fmt, args);
#endif
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
#endif // #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
// CRC32 needs a 1KB lookup table (not cache friendly)
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
static const ImU32 GCrc32LookupTable[256] =
{
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
};
// Known size hash
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed)
{
ImU32 crc = ~seed;
const unsigned char* data = (const unsigned char*)data_p;
const ImU32* crc32_lut = GCrc32LookupTable;
while (data_size-- != 0)
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
return ~crc;
}
// Zero-terminated string hash, with support for ### to reset back to seed value
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
// Because this syntax is rarely used we are optimizing for the common case.
// - If we reach ### in the string we discard the hash so far and reset to the seed.
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImU32 ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
{
seed = ~seed;
ImU32 crc = seed;
const unsigned char* data = (const unsigned char*)data_p;
const ImU32* crc32_lut = GCrc32LookupTable;
if (data_size != 0)
{
while (data_size-- != 0)
{
unsigned char c = *data++;
if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
else
{
while (unsigned char c = *data++)
{
if (c == '#' && data[0] == '#' && data[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
return ~crc;
}
FILE* ImFileOpen(const char* filename, const char* mode)
{
#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__GNUC__)
// We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can)
const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1;
const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1;
ImVector<ImWchar> buf;
buf.resize(filename_wsize + mode_wsize);
ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL);
ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL);
return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]);
#else
return fopen(filename, mode);
#endif
}
// Load file content into memory
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size, int padding_bytes)
{
IM_ASSERT(filename && file_open_mode);
if (out_file_size)
*out_file_size = 0;
FILE* f;
if ((f = ImFileOpen(filename, file_open_mode)) == NULL)
return NULL;
long file_size_signed;
if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET))
{
fclose(f);
return NULL;
}
size_t file_size = (size_t)file_size_signed;
void* file_data = IM_ALLOC(file_size + padding_bytes);
if (file_data == NULL)
{
fclose(f);
return NULL;
}
if (fread(file_data, 1, file_size, f) != file_size)
{
fclose(f);
IM_FREE(file_data);
return NULL;
}
if (padding_bytes > 0)
memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
fclose(f);
if (out_file_size)
*out_file_size = file_size;
return file_data;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
//-----------------------------------------------------------------------------
// Convert UTF-8 to 32-bits character, process single character input.
// Based on stb_from_utf8() from github.com/nothings/stb/
// We handle UTF-8 decoding error by skipping forward.
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
{
unsigned int c = (unsigned int)-1;
const unsigned char* str = (const unsigned char*)in_text;
if (!(*str & 0x80))
{
c = (unsigned int)(*str++);
*out_char = c;
return 1;
}
if ((*str & 0xe0) == 0xc0)
{
*out_char = 0xFFFD; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 2) return 1;
if (*str < 0xc2) return 2;
c = (unsigned int)((*str++ & 0x1f) << 6);
if ((*str & 0xc0) != 0x80) return 2;
c += (*str++ & 0x3f);
*out_char = c;
return 2;
}
if ((*str & 0xf0) == 0xe0)
{
*out_char = 0xFFFD; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 3) return 1;
if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
c = (unsigned int)((*str++ & 0x0f) << 12);
if ((*str & 0xc0) != 0x80) return 3;
c += (unsigned int)((*str++ & 0x3f) << 6);
if ((*str & 0xc0) != 0x80) return 3;
c += (*str++ & 0x3f);
*out_char = c;
return 3;
}
if ((*str & 0xf8) == 0xf0)
{
*out_char = 0xFFFD; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 4) return 1;
if (*str > 0xf4) return 4;
if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below
c = (unsigned int)((*str++ & 0x07) << 18);
if ((*str & 0xc0) != 0x80) return 4;
c += (unsigned int)((*str++ & 0x3f) << 12);
if ((*str & 0xc0) != 0x80) return 4;
c += (unsigned int)((*str++ & 0x3f) << 6);
if ((*str & 0xc0) != 0x80) return 4;
c += (*str++ & 0x3f);
// utf-8 encodings of values used in surrogate pairs are invalid
if ((c & 0xFFFFF800) == 0xD800) return 4;
*out_char = c;
return 4;
}
*out_char = 0;
return 0;
}
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
{
ImWchar* buf_out = buf;
ImWchar* buf_end = buf + buf_size;
while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c;
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes
*buf_out++ = (ImWchar)c;
}
*buf_out = 0;
if (in_text_remaining)
*in_text_remaining = in_text;
return (int)(buf_out - buf);
}
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
{
int char_count = 0;
while ((!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c;
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
if (c < 0x10000)
char_count++;
}
return char_count;
}
// Based on stb_to_utf8() from github.com/nothings/stb/
static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
{
if (c < 0x80)
{
buf[0] = (char)c;
return 1;
}
if (c < 0x800)
{
if (buf_size < 2) return 0;
buf[0] = (char)(0xc0 + (c >> 6));
buf[1] = (char)(0x80 + (c & 0x3f));
return 2;
}
if (c >= 0xdc00 && c < 0xe000)
{
return 0;
}
if (c >= 0xd800 && c < 0xdc00)
{
if (buf_size < 4) return 0;
buf[0] = (char)(0xf0 + (c >> 18));
buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
buf[3] = (char)(0x80 + ((c ) & 0x3f));
return 4;
}
//else if (c < 0x10000)
{
if (buf_size < 3) return 0;
buf[0] = (char)(0xe0 + (c >> 12));
buf[1] = (char)(0x80 + ((c>> 6) & 0x3f));
buf[2] = (char)(0x80 + ((c ) & 0x3f));
return 3;
}
}
// Not optimal but we very rarely use this function.
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
{
unsigned int dummy = 0;
return ImTextCharFromUtf8(&dummy, in_text, in_text_end);
}
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
{
if (c < 0x80) return 1;
if (c < 0x800) return 2;
if (c >= 0xdc00 && c < 0xe000) return 0;
if (c >= 0xd800 && c < 0xdc00) return 4;
return 3;
}
int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
{
char* buf_out = buf;
const char* buf_end = buf + buf_size;
while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
*buf_out++ = (char)c;
else
buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c);
}
*buf_out = 0;
return (int)(buf_out - buf);
}
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
{
int bytes_count = 0;
while ((!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
bytes_count++;
else
bytes_count += ImTextCountUtf8BytesFromChar(c);
}
return bytes_count;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILTIES (Color functions)
// Note: The Convert functions are early design which are not consistent with other API.
//-----------------------------------------------------------------------------
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
{
float s = 1.0f/255.0f;
return ImVec4(
((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
}
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
{
ImU32 out;
out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
return out;
}
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
{
float K = 0.f;
if (g < b)
{
ImSwap(g, b);
K = -1.f;
}
if (r < g)
{
ImSwap(r, g);
K = -2.f / 6.f - K;
}
const float chroma = r - (g < b ? g : b);
out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
out_s = chroma / (r + 1e-20f);
out_v = r;
}
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
// also http://en.wikipedia.org/wiki/HSL_and_HSV
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
{
if (s == 0.0f)
{
// gray
out_r = out_g = out_b = v;
return;
}
h = ImFmod(h, 1.0f) / (60.0f/360.0f);
int i = (int)h;
float f = h - (float)i;
float p = v * (1.0f - s);
float q = v * (1.0f - s * f);
float t = v * (1.0f - s * (1.0f - f));
switch (i)
{
case 0: out_r = v; out_g = t; out_b = p; break;
case 1: out_r = q; out_g = v; out_b = p; break;
case 2: out_r = p; out_g = v; out_b = t; break;
case 3: out_r = p; out_g = q; out_b = v; break;
case 4: out_r = t; out_g = p; out_b = v; break;
case 5: default: out_r = v; out_g = p; out_b = q; break;
}
}
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
{
ImGuiStyle& style = GImGui->Style;
ImVec4 c = style.Colors[idx];
c.w *= style.Alpha * alpha_mul;
return ColorConvertFloat4ToU32(c);
}
ImU32 ImGui::GetColorU32(const ImVec4& col)
{
ImGuiStyle& style = GImGui->Style;
ImVec4 c = col;
c.w *= style.Alpha;
return ColorConvertFloat4ToU32(c);
}
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
{
ImGuiStyle& style = GImGui->Style;
return style.Colors[idx];
}
ImU32 ImGui::GetColorU32(ImU32 col)
{
float style_alpha = GImGui->Style.Alpha;
if (style_alpha >= 1.0f)
return col;
ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
a = (ImU32)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiStorage
// Helper: Key->value storage
//-----------------------------------------------------------------------------
// std::lower_bound but without the bullshit
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
{
ImGuiStorage::ImGuiStoragePair* first = data.Data;
ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
size_t count = (size_t)(last - first);
while (count > 0)
{
size_t count2 = count >> 1;
ImGuiStorage::ImGuiStoragePair* mid = first + count2;
if (mid->key < key)
{
first = ++mid;
count -= count2 + 1;
}
else
{
count = count2;
}
}
return first;
}
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
void ImGuiStorage::BuildSortByKey()
{
struct StaticFunc
{
static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs)
{
// We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
return 0;
}
};
if (Data.Size > 1)
ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairCompareByID);
}
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
{
ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_i;
}
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
{
return GetInt(key, default_val ? 1 : 0) != 0;
}
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
{
ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_f;
}
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
{
ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return NULL;
return it->val_p;
}
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_i;
}
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
{
return (bool*)GetIntRef(key, default_val ? 1 : 0);
}
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_f;
}
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_p;
}
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
void ImGuiStorage::SetInt(ImGuiID key, int val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_i = val;
}
void ImGuiStorage::SetBool(ImGuiID key, bool val)
{
SetInt(key, val ? 1 : 0);
}
void ImGuiStorage::SetFloat(ImGuiID key, float val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_f = val;
}
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_p = val;
}
void ImGuiStorage::SetAllInt(int v)
{
for (int i = 0; i < Data.Size; i++)
Data[i].val_i = v;
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiTextFilter
//-----------------------------------------------------------------------------
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
{
if (default_filter)
{
ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
Build();
}
else
{
InputBuf[0] = 0;
CountGrep = 0;
}
}
bool ImGuiTextFilter::Draw(const char* label, float width)
{
if (width != 0.0f)
ImGui::SetNextItemWidth(width);
bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
if (value_changed)
Build();
return value_changed;
}
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
{
out->resize(0);
const char* wb = b;
const char* we = wb;
while (we < e)
{
if (*we == separator)
{
out->push_back(ImGuiTextRange(wb, we));
wb = we + 1;
}
we++;
}
if (wb != we)
out->push_back(ImGuiTextRange(wb, we));
}
void ImGuiTextFilter::Build()
{
Filters.resize(0);
ImGuiTextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
input_range.split(',', &Filters);
CountGrep = 0;
for (int i = 0; i != Filters.Size; i++)
{
ImGuiTextRange& f = Filters[i];
while (f.b < f.e && ImCharIsBlankA(f.b[0]))
f.b++;
while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
f.e--;
if (f.empty())
continue;
if (Filters[i].b[0] != '-')
CountGrep += 1;
}
}
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
{
if (Filters.empty())
return true;
if (text == NULL)
text = "";
for (int i = 0; i != Filters.Size; i++)
{
const ImGuiTextRange& f = Filters[i];
if (f.empty())
continue;
if (f.b[0] == '-')
{
// Subtract
if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
return false;
}
else
{
// Grep
if (ImStristr(text, text_end, f.b, f.e) != NULL)
return true;
}
}
// Implicit * grep
if (CountGrep == 0)
return true;
return false;
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiTextBuffer
//-----------------------------------------------------------------------------
// On some platform vsnprintf() takes va_list by reference and modifies it.
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
#ifndef va_copy
#if defined(__GNUC__) || defined(__clang__)
#define va_copy(dest, src) __builtin_va_copy(dest, src)
#else
#define va_copy(dest, src) (dest = src)
#endif
#endif
char ImGuiTextBuffer::EmptyString[1] = { 0 };
void ImGuiTextBuffer::append(const char* str, const char* str_end)
{
int len = str_end ? (int)(str_end - str) : (int)strlen(str);
// Add zero-terminator the first time
const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int new_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
}
Buf.resize(needed_sz);
memcpy(&Buf[write_off - 1], str, (size_t)len);
Buf[write_off - 1 + len] = 0;
}
void ImGuiTextBuffer::appendf(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
appendfv(fmt, args);
va_end(args);
}
// Helper: Text buffer for logging/accumulating text
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
{
va_list args_copy;
va_copy(args_copy, args);
int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
if (len <= 0)
{
va_end(args_copy);
return;
}
// Add zero-terminator the first time
const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int new_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
}
Buf.resize(needed_sz);
ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
va_end(args_copy);
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiListClipper
// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
//-----------------------------------------------------------------------------
// Helper to calculate coarse clipping of large list of evenly sized items.
// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.LogEnabled)
{
// If logging is active, do not perform any clipping
*out_items_display_start = 0;
*out_items_display_end = items_count;
return;
}
if (window->SkipItems)
{
*out_items_display_start = *out_items_display_end = 0;
return;
}
// We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect
ImRect unclipped_rect = window->ClipRect;
if (g.NavMoveRequest)
unclipped_rect.Add(g.NavScoringRectScreen);
const ImVec2 pos = window->DC.CursorPos;
int start = (int)((unclipped_rect.Min.y - pos.y) / items_height);
int end = (int)((unclipped_rect.Max.y - pos.y) / items_height);
// When performing a navigation request, ensure we have one item extra in the direction we are moving to
if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up)
start--;
if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down)
end++;
start = ImClamp(start, 0, items_count);
end = ImClamp(end + 1, start, items_count);
*out_items_display_start = start;
*out_items_display_end = end;
}
static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
{
// Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
// FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
// The clipper should probably have a 4th step to display the last item in a regular manner.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DC.CursorPos.y = pos_y;
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y);
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
if (ImGuiColumns* columns = window->DC.CurrentColumns)
columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
}
// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
// Use case B: Begin() called from constructor with items_height>0
// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
void ImGuiListClipper::Begin(int count, float items_height)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
StartPosY = window->DC.CursorPos.y;
ItemsHeight = items_height;
ItemsCount = count;
StepNo = 0;
DisplayEnd = DisplayStart = -1;
if (ItemsHeight > 0.0f)
{
ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display
if (DisplayStart > 0)
SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
StepNo = 2;
}
}
void ImGuiListClipper::End()
{
if (ItemsCount < 0)
return;
// In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user.
if (ItemsCount < INT_MAX)
SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor
ItemsCount = -1;
StepNo = 3;
}
bool ImGuiListClipper::Step()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (ItemsCount == 0 || window->SkipItems)
{
ItemsCount = -1;
return false;
}
if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height.
{
DisplayStart = 0;
DisplayEnd = 1;
StartPosY = window->DC.CursorPos.y;
StepNo = 1;
return true;
}
if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
{
if (ItemsCount == 1) { ItemsCount = -1; return false; }
float items_height = window->DC.CursorPos.y - StartPosY;
IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
Begin(ItemsCount - 1, items_height);
DisplayStart++;
DisplayEnd++;
StepNo = 3;
return true;
}
if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3.
{
IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0);
StepNo = 3;
return true;
}
if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
End();
return false;
}
//-----------------------------------------------------------------------------
// [SECTION] RENDER HELPERS
// Those (internal) functions are currently quite a legacy mess - their signature and behavior will change.
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: state.
//-----------------------------------------------------------------------------
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
{
const char* text_display_end = text;
if (!text_end)
text_end = (const char*)-1;
while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
text_display_end++;
return text_display_end;
}
// Internal ImGui functions to render text
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// Hide anything after a '##' string
const char* text_display_end;
if (hide_text_after_hash)
{
text_display_end = FindRenderedTextEnd(text, text_end);
}
else
{
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
text_display_end = text_end;
}
if (text != text_display_end)
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
if (g.LogEnabled)
LogRenderedText(&pos, text, text_display_end);
}
}
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
if (text != text_end)
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
if (g.LogEnabled)
LogRenderedText(&pos, text, text_end);
}
}
// Default clip_rect uses (pos_min,pos_max)
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
{
// Perform CPU side clipping for single clipped element to avoid using scissor state
ImVec2 pos = pos_min;
const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
// Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
// Render
if (need_clipping)
{
ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
}
else
{
draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
}
}
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
{
// Hide anything after a '##' string
const char* text_display_end = FindRenderedTextEnd(text, text_end);
const int text_len = (int)(text_display_end - text);
if (text_len == 0)
return;
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
if (g.LogEnabled)
LogRenderedText(&pos_min, text, text_display_end);
}
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
{
ImGuiContext& g = *GImGui;
if (text_end_full == NULL)
text_end_full = FindRenderedTextEnd(text);
const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
if (text_size.x > pos_max.x - pos_min.x)
{
// Hello wo...
// | | |
// min max ellipsis_max
// <-> this is generally some padding value
// FIXME-STYLE: RenderPixelEllipsis() style should use actual font data.
const ImFont* font = draw_list->_Data->Font;
const float font_size = draw_list->_Data->FontSize;
const int ellipsis_dot_count = 3;
const float ellipsis_width = (1.0f + 1.0f) * ellipsis_dot_count - 1.0f;
const char* text_end_ellipsis = NULL;
float text_width = ImMax((pos_max.x - ellipsis_width) - pos_min.x, 1.0f);
float text_size_clipped_x = font->CalcTextSizeA(font_size, text_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
{
// Always display at least 1 character if there's no room for character + ellipsis
text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
}
while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
{
// Trim trailing space before ellipsis
text_end_ellipsis--;
text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
}
RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
const float ellipsis_x = pos_min.x + text_size_clipped_x + 1.0f;
if (ellipsis_x + ellipsis_width - 1.0f <= ellipsis_max_x)
RenderPixelEllipsis(draw_list, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_dot_count);
}
else
{
RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
}
if (g.LogEnabled)
LogRenderedText(&pos_min, text, text_end_full);
}
// Render a rectangle shaped with optional rounding and borders
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
const float border_size = g.Style.FrameBorderSize;
if (border && border_size > 0.0f)
{
window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const float border_size = g.Style.FrameBorderSize;
if (border_size > 0.0f)
{
window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
// Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state
void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale)
{
const float h = draw_list->_Data->FontSize * 1.00f;
float r = h * 0.40f * scale;
ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale);
ImVec2 a, b, c;
switch (dir)
{
case ImGuiDir_Up:
case ImGuiDir_Down:
if (dir == ImGuiDir_Up) r = -r;
a = ImVec2(+0.000f,+0.750f) * r;
b = ImVec2(-0.866f,-0.750f) * r;
c = ImVec2(+0.866f,-0.750f) * r;
break;
case ImGuiDir_Left:
case ImGuiDir_Right:
if (dir == ImGuiDir_Left) r = -r;
a = ImVec2(+0.750f,+0.000f) * r;
b = ImVec2(-0.750f,+0.866f) * r;
c = ImVec2(-0.750f,-0.866f) * r;
break;
case ImGuiDir_None:
case ImGuiDir_COUNT:
IM_ASSERT(0);
break;
}
draw_list->AddTriangleFilled(center + a, center + b, center + c, col);
}
void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col)
{
draw_list->AddCircleFilled(pos, draw_list->_Data->FontSize * 0.20f, col, 8);
}
void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float thickness = ImMax(sz / 5.0f, 1.0f);
sz -= thickness*0.5f;
pos += ImVec2(thickness*0.25f, thickness*0.25f);
float third = sz / 3.0f;
float bx = pos.x + third;
float by = pos.y + sz - third*0.5f;
window->DrawList->PathLineTo(ImVec2(bx - third, by - third));
window->DrawList->PathLineTo(ImVec2(bx, by));
window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2));
window->DrawList->PathStroke(col, false, thickness);
}
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
{
ImGuiContext& g = *GImGui;
if (id != g.NavId)
return;
if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
return;
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.NavHideHighlightOneFrame)
return;
float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
ImRect display_rect = bb;
display_rect.ClipWith(window->ClipRect);
if (flags & ImGuiNavHighlightFlags_TypeDefault)
{
const float THICKNESS = 2.0f;
const float DISTANCE = 3.0f + THICKNESS * 0.5f;
display_rect.Expand(ImVec2(DISTANCE,DISTANCE));
bool fully_visible = window->ClipRect.Contains(display_rect);
if (!fully_visible)
window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), display_rect.Max - ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS);
if (!fully_visible)
window->DrawList->PopClipRect();
}
if (flags & ImGuiNavHighlightFlags_TypeThin)
{
window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f);
}
}
//-----------------------------------------------------------------------------
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
//-----------------------------------------------------------------------------
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
: DrawListInst(&context->DrawListSharedData)
{
Name = ImStrdup(name);
ID = ImHashStr(name);
IDStack.push_back(ID);
Flags = ImGuiWindowFlags_None;
Pos = ImVec2(0.0f, 0.0f);
Size = SizeFull = ImVec2(0.0f, 0.0f);
ContentSize = ContentSizeExplicit = ImVec2(0.0f, 0.0f);
WindowPadding = ImVec2(0.0f, 0.0f);
WindowRounding = 0.0f;
WindowBorderSize = 0.0f;
NameBufLen = (int)strlen(name) + 1;
MoveId = GetID("#MOVE");
ChildId = 0;
Scroll = ImVec2(0.0f, 0.0f);
ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
ScrollbarSizes = ImVec2(0.0f, 0.0f);
ScrollbarX = ScrollbarY = false;
Active = WasActive = false;
WriteAccessed = false;
Collapsed = false;
WantCollapseToggle = false;
SkipItems = false;
Appearing = false;
Hidden = false;
HasCloseButton = false;
ResizeBorderHeld = -1;
BeginCount = 0;
BeginOrderWithinParent = -1;
BeginOrderWithinContext = -1;
PopupId = 0;
AutoFitFramesX = AutoFitFramesY = -1;
AutoFitOnlyGrows = false;
AutoFitChildAxises = 0x00;
AutoPosLastDirection = ImGuiDir_None;
HiddenFramesCanSkipItems = HiddenFramesCannotSkipItems = 0;
SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
LastFrameActive = -1;
ItemWidthDefault = 0.0f;
FontWindowScale = 1.0f;
SettingsIdx = -1;
DrawList = &DrawListInst;
DrawList->_OwnerName = Name;
ParentWindow = NULL;
RootWindow = NULL;
RootWindowForTitleBarHighlight = NULL;
RootWindowForNav = NULL;
NavLastIds[0] = NavLastIds[1] = 0;
NavRectRel[0] = NavRectRel[1] = ImRect();
NavLastChildNavWindow = NULL;
}
ImGuiWindow::~ImGuiWindow()
{
IM_ASSERT(DrawList == &DrawListInst);
IM_DELETE(Name);
for (int i = 0; i != ColumnsStorage.Size; i++)
ColumnsStorage[i].~ImGuiColumns();
}
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetID(const void* ptr)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetID(int n)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&n, sizeof(n), seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
return ImHashStr(str, str_end ? (str_end - str) : 0, seed);
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)
{
ImGuiID seed = IDStack.back();
return ImHashData(&ptr, sizeof(void*), seed);
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(int n)
{
ImGuiID seed = IDStack.back();
return ImHashData(&n, sizeof(n), seed);
}
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
{
ImGuiID seed = IDStack.back();
const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) };
ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
ImGui::KeepAliveID(id);
return id;
}
static void SetCurrentWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.CurrentWindow = window;
if (window)
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
void ImGui::SetNavID(ImGuiID id, int nav_layer)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindow);
IM_ASSERT(nav_layer == 0 || nav_layer == 1);
g.NavId = id;
g.NavWindow->NavLastIds[nav_layer] = id;
}
void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, const ImRect& rect_rel)
{
ImGuiContext& g = *GImGui;
SetNavID(id, nav_layer);
g.NavWindow->NavRectRel[nav_layer] = rect_rel;
g.NavMousePosDirty = true;
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
}
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.ActiveIdIsJustActivated = (g.ActiveId != id);
if (g.ActiveIdIsJustActivated)
{
g.ActiveIdTimer = 0.0f;
g.ActiveIdHasBeenPressedBefore = false;
g.ActiveIdHasBeenEditedBefore = false;
if (id != 0)
{
g.LastActiveId = id;
g.LastActiveIdTimer = 0.0f;
}
}
g.ActiveId = id;
g.ActiveIdAllowNavDirFlags = 0;
g.ActiveIdBlockNavInputFlags = 0;
g.ActiveIdAllowOverlap = false;
g.ActiveIdWindow = window;
g.ActiveIdHasBeenEditedThisFrame = false;
if (id)
{
g.ActiveIdIsAlive = id;
g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
}
}
// FIXME-NAV: The existence of SetNavID/SetNavIDWithRectRel/SetFocusID is incredibly messy and confusing and needs some explanation or refactoring.
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(id != 0);
// Assume that SetFocusID() is called in the context where its NavLayer is the current layer, which is the case everywhere we call it.
const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
if (g.NavWindow != window)
g.NavInitRequest = false;
g.NavId = id;
g.NavWindow = window;
g.NavLayer = nav_layer;
window->NavLastIds[nav_layer] = id;
if (window->DC.LastItemId == id)
window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
if (g.ActiveIdSource == ImGuiInputSource_Nav)
g.NavDisableMouseHover = true;
else
g.NavDisableHighlight = true;
}
void ImGui::ClearActiveID()
{
SetActiveID(0, NULL);
}
void ImGui::SetHoveredID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.HoveredId = id;
g.HoveredIdAllowOverlap = false;
if (id != 0 && g.HoveredIdPreviousFrame != id)
g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
}
ImGuiID ImGui::GetHoveredID()
{
ImGuiContext& g = *GImGui;
return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
}
void ImGui::KeepAliveID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (g.ActiveId == id)
g.ActiveIdIsAlive = id;
if (g.ActiveIdPreviousFrame == id)
g.ActiveIdPreviousFrameIsAlive = true;
}
void ImGui::MarkItemEdited(ImGuiID id)
{
// This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
// ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data.
ImGuiContext& g = *GImGui;
IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
//IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
g.ActiveIdHasBeenEditedThisFrame = true;
g.ActiveIdHasBeenEditedBefore = true;
g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
}
static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
{
// An active popup disable hovering on other windows (apart from its own children)
// FIXME-OPT: This could be cached/stored within the window.
ImGuiContext& g = *GImGui;
if (g.NavWindow)
if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
{
// For the purpose of those flags we differentiate "standard popup" from "modal popup"
// NB: The order of those two tests is important because Modal windows are also Popups.
if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
return false;
if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
return false;
}
return true;
}
// Advance cursor given item size for layout.
void ImGui::ItemSize(const ImVec2& size, float text_offset_y)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
// Always align ourselves on pixel boundaries
const float line_height = ImMax(window->DC.CurrLineSize.y, size.y);
const float text_base_offset = ImMax(window->DC.CurrLineTextBaseOffset, text_offset_y);
//if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y;
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
window->DC.CursorPos.y = (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y);
window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
//if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
window->DC.PrevLineSize.y = line_height;
window->DC.PrevLineTextBaseOffset = text_base_offset;
window->DC.CurrLineSize.y = window->DC.CurrLineTextBaseOffset = 0.0f;
// Horizontal layout mode
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
SameLine();
}
void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
{
ItemSize(bb.GetSize(), text_offset_y);
}
// Declare item bounding box for clipping and interaction.
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
// declare their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (id != 0)
{
// Navigation processing runs prior to clipping early-out
// (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
// (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
// unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
// thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
// We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
// to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
// We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
// If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask;
if (g.NavId == id || g.NavAnyRequest)
if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
// [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd()
#ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
if (id == g.DebugItemPickerBreakID)
{
IM_DEBUG_BREAK();
g.DebugItemPickerBreakID = 0;
}
#endif
}
window->DC.LastItemId = id;
window->DC.LastItemRect = bb;
window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None;
g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (id != 0)
IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
#endif
// Clipping test
const bool is_clipped = IsClippedEx(bb, id, false);
if (is_clipped)
return false;
//if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
// We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
if (IsMouseHoveringRect(bb.Min, bb.Max))
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
return true;
}
// This is roughly matching the behavior of internal-facing ItemHoverable()
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavDisableMouseHover && !g.NavDisableHighlight)
return IsItemFocused();
// Test for bounding box overlap, as updated as ItemAdd()
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function
// Test if we are hovering the right window (our window could be behind another window)
// [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself.
// Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while.
//if (g.HoveredWindow != window)
// return false;
if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped))
return false;
// Test if another item is active (e.g. being dragged)
if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
return false;
// Test if interactions on this window are blocked by an active popup or modal.
// The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
if (!IsWindowContentHoverable(window, flags))
return false;
// Test if the item is disabled
if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
return false;
// Special handling for the dummy item after Begin() which represent the title bar or tab.
// When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
if (window->DC.LastItemId == window->MoveId && window->WriteAccessed)
return false;
return true;
}
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (g.HoveredWindow != window)
return false;
if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
return false;
if (!IsMouseHoveringRect(bb.Min, bb.Max))
return false;
if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
return false;
if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
return false;
SetHoveredID(id);
// [DEBUG] Item Picker tool!
// We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
// the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
// items if we perform the test in ItemAdd(), but that would incur a small runtime cost.
// #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd().
if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
if (g.DebugItemPickerBreakID == id)
IM_DEBUG_BREAK();
return true;
}
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!bb.Overlaps(window->ClipRect))
if (id == 0 || id != g.ActiveId)
if (clip_even_when_logged || !g.LogEnabled)
return true;
return false;
}
// Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out.
bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id)
{
ImGuiContext& g = *GImGui;
// Increment counters
const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
window->DC.FocusCounterAll++;
if (is_tab_stop)
window->DC.FocusCounterTab++;
// Process TAB/Shift-TAB to tab *OUT* of the currently focused item.
// (Note that we can always TAB out of a widget that doesn't allow tabbing in)
if (g.ActiveId == id && g.FocusTabPressed && !(g.ActiveIdBlockNavInputFlags & (1 << ImGuiNavInput_KeyTab_)) && g.FocusRequestNextWindow == NULL)
{
g.FocusRequestNextWindow = window;
g.FocusRequestNextCounterTab = window->DC.FocusCounterTab + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
}
// Handle focus requests
if (g.FocusRequestCurrWindow == window)
{
if (window->DC.FocusCounterAll == g.FocusRequestCurrCounterAll)
return true;
if (is_tab_stop && window->DC.FocusCounterTab == g.FocusRequestCurrCounterTab)
{
g.NavJustTabbedId = id;
return true;
}
// If another item is about to be focused, we clear our own active id
if (g.ActiveId == id)
ClearActiveID();
}
return false;
}
void ImGui::FocusableItemUnregister(ImGuiWindow* window)
{
window->DC.FocusCounterAll--;
window->DC.FocusCounterTab--;
}
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
{
if (wrap_pos_x < 0.0f)
return 0.0f;
ImGuiWindow* window = GImGui->CurrentWindow;
if (wrap_pos_x == 0.0f)
wrap_pos_x = window->WorkRect.Max.x;
else if (wrap_pos_x > 0.0f)
wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
return ImMax(wrap_pos_x - pos.x, 1.0f);
}
// IM_ALLOC() == ImGui::MemAlloc()
void* ImGui::MemAlloc(size_t size)
{
if (ImGuiContext* ctx = GImGui)
ctx->IO.MetricsActiveAllocations++;
return GImAllocatorAllocFunc(size, GImAllocatorUserData);
}
// IM_FREE() == ImGui::MemFree()
void ImGui::MemFree(void* ptr)
{
if (ptr)
if (ImGuiContext* ctx = GImGui)
ctx->IO.MetricsActiveAllocations--;
return GImAllocatorFreeFunc(ptr, GImAllocatorUserData);
}
const char* ImGui::GetClipboardText()
{
ImGuiContext& g = *GImGui;
return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
}
void ImGui::SetClipboardText(const char* text)
{
ImGuiContext& g = *GImGui;
if (g.IO.SetClipboardTextFn)
g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
}
const char* ImGui::GetVersion()
{
return IMGUI_VERSION;
}
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
ImGuiContext* ImGui::GetCurrentContext()
{
return GImGui;
}
void ImGui::SetCurrentContext(ImGuiContext* ctx)
{
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
#else
GImGui = ctx;
#endif
}
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
// If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code
// may see different structures than what imgui.cpp sees, which is problematic.
// We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui.
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
{
bool error = false;
if (strcmp(version, IMGUI_VERSION)!=0) { error = true; IM_ASSERT(strcmp(version,IMGUI_VERSION)==0 && "Mismatched version string!"); }
if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
return !error;
}
void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
{
GImAllocatorAllocFunc = alloc_func;
GImAllocatorFreeFunc = free_func;
GImAllocatorUserData = user_data;
}
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
{
ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
if (GImGui == NULL)
SetCurrentContext(ctx);
Initialize(ctx);
return ctx;
}
void ImGui::DestroyContext(ImGuiContext* ctx)
{
if (ctx == NULL)
ctx = GImGui;
Shutdown(ctx);
if (GImGui == ctx)
SetCurrentContext(NULL);
IM_DELETE(ctx);
}
ImGuiIO& ImGui::GetIO()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
return GImGui->IO;
}
ImGuiStyle& ImGui::GetStyle()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
return GImGui->Style;
}
// Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame()
ImDrawData* ImGui::GetDrawData()
{
ImGuiContext& g = *GImGui;
return g.DrawData.Valid ? &g.DrawData : NULL;
}
double ImGui::GetTime()
{
return GImGui->Time;
}
int ImGui::GetFrameCount()
{
return GImGui->FrameCount;
}
ImDrawList* ImGui::GetBackgroundDrawList()
{
return &GImGui->BackgroundDrawList;
}
static ImDrawList* GetForegroundDrawList(ImGuiWindow*)
{
// This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches.
return &GImGui->ForegroundDrawList;
}
ImDrawList* ImGui::GetForegroundDrawList()
{
return &GImGui->ForegroundDrawList;
}
ImDrawListSharedData* ImGui::GetDrawListSharedData()
{
return &GImGui->DrawListSharedData;
}
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
{
// Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
// We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
// This is because we want ActiveId to be set even when the window is not permitted to move.
ImGuiContext& g = *GImGui;
FocusWindow(window);
SetActiveID(window->MoveId, window);
g.NavDisableHighlight = true;
g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos;
bool can_move_window = true;
if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
can_move_window = false;
if (can_move_window)
g.MovingWindow = window;
}
// Handle mouse moving window
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
void ImGui::UpdateMouseMovingWindowNewFrame()
{
ImGuiContext& g = *GImGui;
if (g.MovingWindow != NULL)
{
// We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
// We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
KeepAliveID(g.ActiveId);
IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))
{
ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
{
MarkIniSettingsDirty(moving_window);
SetWindowPos(moving_window, pos, ImGuiCond_Always);
}
FocusWindow(g.MovingWindow);
}
else
{
ClearActiveID();
g.MovingWindow = NULL;
}
}
else
{
// When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
{
KeepAliveID(g.ActiveId);
if (!g.IO.MouseDown[0])
ClearActiveID();
}
}
}
// Initiate moving window, handle left-click and right-click focus
void ImGui::UpdateMouseMovingWindowEndFrame()
{
// Initiate moving window
ImGuiContext& g = *GImGui;
if (g.ActiveId != 0 || g.HoveredId != 0)
return;
// Unless we just made a window/popup appear
if (g.NavWindow && g.NavWindow->Appearing)
return;
// Click to focus window and start moving (after we're done with all our widgets)
if (g.IO.MouseClicked[0])
{
if (g.HoveredRootWindow != NULL)
{
StartMouseMovingWindow(g.HoveredWindow);
if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoTitleBar))
if (!g.HoveredRootWindow->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
g.MovingWindow = NULL;
}
else if (g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
{
// Clicking on void disable focus
FocusWindow(NULL);
}
}
// With right mouse button we close popups without changing focus based on where the mouse is aimed
// Instead, focus will be restored to the window under the bottom-most closed popup.
// (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
if (g.IO.MouseClicked[1])
{
// Find the top-most window between HoveredWindow and the top-most Modal Window.
// This is where we can trim the popup stack.
ImGuiWindow* modal = GetTopMostPopupModal();
bool hovered_window_above_modal = false;
if (modal == NULL)
hovered_window_above_modal = true;
for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--)
{
ImGuiWindow* window = g.Windows[i];
if (window == modal)
break;
if (window == g.HoveredWindow)
hovered_window_above_modal = true;
}
ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
}
}
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
{
return (window->Active) && (!window->Hidden);
}
static void ImGui::UpdateMouseInputs()
{
ImGuiContext& g = *GImGui;
// Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
if (IsMousePosValid(&g.IO.MousePos))
g.IO.MousePos = g.LastValidMousePos = ImFloor(g.IO.MousePos);
// If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
else
g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)
g.NavDisableMouseHover = false;
g.IO.MousePosPrev = g.IO.MousePos;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f;
g.IO.MouseDoubleClicked[i] = false;
if (g.IO.MouseClicked[i])
{
if ((float)(g.Time - g.IO.MouseClickedTime[i]) < g.IO.MouseDoubleClickTime)
{
ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
g.IO.MouseDoubleClicked[i] = true;
g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click
}
else
{
g.IO.MouseClickedTime[i] = g.Time;
}
g.IO.MouseClickedPos[i] = g.IO.MousePos;
g.IO.MouseDownWasDoubleClick[i] = g.IO.MouseDoubleClicked[i];
g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
}
else if (g.IO.MouseDown[i])
{
// Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
}
if (!g.IO.MouseDown[i] && !g.IO.MouseReleased[i])
g.IO.MouseDownWasDoubleClick[i] = false;
if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
g.NavDisableMouseHover = false;
}
}
static void StartLockWheelingWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.WheelingWindow == window)
return;
g.WheelingWindow = window;
g.WheelingWindowRefMousePos = g.IO.MousePos;
g.WheelingWindowTimer = WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER;
}
void ImGui::UpdateMouseWheel()
{
ImGuiContext& g = *GImGui;
// Reset the locked window if we move the mouse or after the timer elapses
if (g.WheelingWindow != NULL)
{
g.WheelingWindowTimer -= g.IO.DeltaTime;
if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
g.WheelingWindowTimer = 0.0f;
if (g.WheelingWindowTimer <= 0.0f)
{
g.WheelingWindow = NULL;
g.WheelingWindowTimer = 0.0f;
}
}
if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f)
return;
ImGuiWindow* window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
if (!window || window->Collapsed)
return;
// Zoom / Scale window
// FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
{
StartLockWheelingWindow(window);
const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
const float scale = new_font_scale / window->FontWindowScale;
window->FontWindowScale = new_font_scale;
if (!(window->Flags & ImGuiWindowFlags_ChildWindow))
{
const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
SetWindowPos(window, window->Pos + offset, 0);
window->Size = ImFloor(window->Size * scale);
window->SizeFull = ImFloor(window->SizeFull * scale);
}
return;
}
// Mouse wheel scrolling
// If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent
// Vertical Mouse Wheel scrolling
const float wheel_y = (g.IO.MouseWheel != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f;
if (wheel_y != 0.0f && !g.IO.KeyCtrl)
{
StartLockWheelingWindow(window);
while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
window = window->ParentWindow;
if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
{
float max_step = window->InnerRect.GetHeight() * 0.67f;
float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
SetScrollY(window, window->Scroll.y - wheel_y * scroll_step);
}
}
// Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held
const float wheel_x = (g.IO.MouseWheelH != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheelH : (g.IO.MouseWheel != 0.0f && g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f;
if (wheel_x != 0.0f && !g.IO.KeyCtrl)
{
StartLockWheelingWindow(window);
while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
window = window->ParentWindow;
if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
{
float max_step = window->InnerRect.GetWidth() * 0.67f;
float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
SetScrollX(window, window->Scroll.x - wheel_x * scroll_step);
}
}
}
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
void ImGui::UpdateHoveredWindowAndCaptureFlags()
{
ImGuiContext& g = *GImGui;
// Find the window hovered by mouse:
// - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
// - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
// - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
FindHoveredWindow();
// Modal windows prevents cursor from hovering behind them.
ImGuiWindow* modal_window = GetTopMostPopupModal();
if (modal_window)
if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
g.HoveredRootWindow = g.HoveredWindow = NULL;
// Disabled mouse?
if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse)
g.HoveredWindow = g.HoveredRootWindow = NULL;
// We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward.
int mouse_earliest_button_down = -1;
bool mouse_any_down = false;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
if (g.IO.MouseClicked[i])
g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty());
mouse_any_down |= g.IO.MouseDown[i];
if (g.IO.MouseDown[i])
if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down])
mouse_earliest_button_down = i;
}
const bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
// If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
// FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
g.HoveredWindow = g.HoveredRootWindow = NULL;
// Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to Dear ImGui + app)
if (g.WantCaptureMouseNextFrame != -1)
g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0);
else
g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty());
// Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to Dear ImGui + app)
if (g.WantCaptureKeyboardNextFrame != -1)
g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
else
g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
if (g.IO.NavActive && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
g.IO.WantCaptureKeyboard = true;
// Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
}
static void NewFrameSanityChecks()
{
ImGuiContext& g = *GImGui;
// Check user data
// (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
IM_ASSERT(g.Initialized);
IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)!");
IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
for (int n = 0; n < ImGuiKey_COUNT; n++)
IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)");
// Perform simple check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only recently added in 1.60 WIP)
if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
// Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires back-end to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
g.IO.ConfigWindowsResizeFromEdges = false;
}
void ImGui::NewFrame()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
ImGuiContext& g = *GImGui;
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiTestEngineHook_PreNewFrame(&g);
#endif
// Check and assert for various common IO and Configuration mistakes
NewFrameSanityChecks();
// Load settings on first frame (if not explicitly loaded manually before)
if (!g.SettingsLoaded)
{
IM_ASSERT(g.SettingsWindows.empty());
if (g.IO.IniFilename)
LoadIniSettingsFromDisk(g.IO.IniFilename);
g.SettingsLoaded = true;
}
// Save settings (with a delay after the last modification, so we don't spam disk too much)
if (g.SettingsDirtyTimer > 0.0f)
{
g.SettingsDirtyTimer -= g.IO.DeltaTime;
if (g.SettingsDirtyTimer <= 0.0f)
{
if (g.IO.IniFilename != NULL)
SaveIniSettingsToDisk(g.IO.IniFilename);
else
g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
g.SettingsDirtyTimer = 0.0f;
}
}
g.Time += g.IO.DeltaTime;
g.FrameScopeActive = true;
g.FrameCount += 1;
g.TooltipOverrideCount = 0;
g.WindowsActiveCount = 0;
// Setup current font and draw list shared data
g.IO.Fonts->Locked = true;
SetCurrentFont(GetDefaultFont());
IM_ASSERT(g.Font->IsLoaded());
g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
if (g.Style.AntiAliasedLines)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
if (g.Style.AntiAliasedFill)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
g.BackgroundDrawList.Clear();
g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID);
g.BackgroundDrawList.PushClipRectFullScreen();
g.ForegroundDrawList.Clear();
g.ForegroundDrawList.PushTextureID(g.IO.Fonts->TexID);
g.ForegroundDrawList.PushClipRectFullScreen();
// Mark rendering data as invalid to prevent user who may have a handle on it to use it.
g.DrawData.Clear();
// Drag and drop keep the source ID alive so even if the source disappear our state is consistent
if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
KeepAliveID(g.DragDropPayload.SourceId);
// Clear reference to active widget if the widget isn't alive anymore
if (!g.HoveredIdPreviousFrame)
g.HoveredIdTimer = 0.0f;
if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
g.HoveredIdNotActiveTimer = 0.0f;
if (g.HoveredId)
g.HoveredIdTimer += g.IO.DeltaTime;
if (g.HoveredId && g.ActiveId != g.HoveredId)
g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
g.HoveredIdPreviousFrame = g.HoveredId;
g.HoveredId = 0;
g.HoveredIdAllowOverlap = false;
if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
ClearActiveID();
if (g.ActiveId)
g.ActiveIdTimer += g.IO.DeltaTime;
g.LastActiveIdTimer += g.IO.DeltaTime;
g.ActiveIdPreviousFrame = g.ActiveId;
g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
g.ActiveIdIsAlive = 0;
g.ActiveIdHasBeenEditedThisFrame = false;
g.ActiveIdPreviousFrameIsAlive = false;
g.ActiveIdIsJustActivated = false;
if (g.TempInputTextId != 0 && g.ActiveId != g.TempInputTextId)
g.TempInputTextId = 0;
// Drag and drop
g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
g.DragDropAcceptIdCurr = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropWithinSourceOrTarget = false;
// Update keyboard input state
memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f;
// Update gamepad/keyboard directional navigation
NavUpdate();
// Update mouse input state
UpdateMouseInputs();
// Calculate frame-rate for the user, as a purely luxurious feature
g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX;
// Find hovered window
// (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
UpdateHoveredWindowAndCaptureFlags();
// Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
UpdateMouseMovingWindowNewFrame();
// Background darkening/whitening
if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
else
g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
g.MouseCursor = ImGuiMouseCursor_Arrow;
g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
g.PlatformImePos = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
// Mouse wheel scrolling, scale
UpdateMouseWheel();
// Pressing TAB activate widget focus
g.FocusTabPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab));
if (g.ActiveId == 0 && g.FocusTabPressed)
{
// Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also
// manipulate the Next fields even, even though they will be turned into Curr fields by the code below.
g.FocusRequestNextWindow = g.NavWindow;
g.FocusRequestNextCounterAll = INT_MAX;
if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
g.FocusRequestNextCounterTab = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1);
else
g.FocusRequestNextCounterTab = g.IO.KeyShift ? -1 : 0;
}
// Turn queued focus request into current one
g.FocusRequestCurrWindow = NULL;
g.FocusRequestCurrCounterAll = g.FocusRequestCurrCounterTab = INT_MAX;
if (g.FocusRequestNextWindow != NULL)
{
ImGuiWindow* window = g.FocusRequestNextWindow;
g.FocusRequestCurrWindow = window;
if (g.FocusRequestNextCounterAll != INT_MAX && window->DC.FocusCounterAll != -1)
g.FocusRequestCurrCounterAll = ImModPositive(g.FocusRequestNextCounterAll, window->DC.FocusCounterAll + 1);
if (g.FocusRequestNextCounterTab != INT_MAX && window->DC.FocusCounterTab != -1)
g.FocusRequestCurrCounterTab = ImModPositive(g.FocusRequestNextCounterTab, window->DC.FocusCounterTab + 1);
g.FocusRequestNextWindow = NULL;
g.FocusRequestNextCounterAll = g.FocusRequestNextCounterTab = INT_MAX;
}
g.NavIdTabCounter = INT_MAX;
// Mark all windows as not visible
IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size);
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
window->WasActive = window->Active;
window->BeginCount = 0;
window->Active = false;
window->WriteAccessed = false;
}
// Closing the focused window restore focus to the first active root window in descending z-order
if (g.NavWindow && !g.NavWindow->WasActive)
FocusTopMostWindowUnderOne(NULL, NULL);
// No window should be open at the beginning of the frame.
// But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
g.CurrentWindowStack.resize(0);
g.BeginPopupStack.resize(0);
ClosePopupsOverWindow(g.NavWindow, false);
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
UpdateDebugToolItemPicker();
// Create implicit/fallback window - which we will only render it if the user has added something to it.
// We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
// This fallback is particularly important as it avoid ImGui:: calls from crashing.
SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver);
Begin("Debug##Default");
g.FrameScopePushedImplicitWindow = true;
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiTestEngineHook_PostNewFrame(&g);
#endif
}
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
void ImGui::UpdateDebugToolItemPicker()
{
ImGuiContext& g = *GImGui;
g.DebugItemPickerBreakID = 0;
if (g.DebugItemPickerActive)
{
const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
ImGui::SetMouseCursor(ImGuiMouseCursor_Hand);
if (ImGui::IsKeyPressedMap(ImGuiKey_Escape))
g.DebugItemPickerActive = false;
if (ImGui::IsMouseClicked(0) && hovered_id)
{
g.DebugItemPickerBreakID = hovered_id;
g.DebugItemPickerActive = false;
}
ImGui::SetNextWindowBgAlpha(0.60f);
ImGui::BeginTooltip();
ImGui::Text("HoveredId: 0x%08X", hovered_id);
ImGui::Text("Press ESC to abort picking.");
ImGui::TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!");
ImGui::EndTooltip();
}
}
void ImGui::Initialize(ImGuiContext* context)
{
ImGuiContext& g = *context;
IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
// Add .ini handle for ImGuiWindow type
ImGuiSettingsHandler ini_handler;
ini_handler.TypeName = "Window";
ini_handler.TypeHash = ImHashStr("Window");
ini_handler.ReadOpenFn = SettingsHandlerWindow_ReadOpen;
ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine;
ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll;
g.SettingsHandlers.push_back(ini_handler);
g.Initialized = true;
}
// This function is merely here to free heap allocations.
void ImGui::Shutdown(ImGuiContext* context)
{
// The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
ImGuiContext& g = *context;
if (g.IO.Fonts && g.FontAtlasOwnedByContext)
{
g.IO.Fonts->Locked = false;
IM_DELETE(g.IO.Fonts);
}
g.IO.Fonts = NULL;
// Cleanup of other data are conditional on actually having initialized Dear ImGui.
if (!g.Initialized)
return;
// Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
if (g.SettingsLoaded && g.IO.IniFilename != NULL)
{
ImGuiContext* backup_context = GImGui;
SetCurrentContext(context);
SaveIniSettingsToDisk(g.IO.IniFilename);
SetCurrentContext(backup_context);
}
// Clear everything else
for (int i = 0; i < g.Windows.Size; i++)
IM_DELETE(g.Windows[i]);
g.Windows.clear();
g.WindowsFocusOrder.clear();
g.WindowsSortBuffer.clear();
g.CurrentWindow = NULL;
g.CurrentWindowStack.clear();
g.WindowsById.Clear();
g.NavWindow = NULL;
g.HoveredWindow = g.HoveredRootWindow = NULL;
g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
g.MovingWindow = NULL;
g.ColorModifiers.clear();
g.StyleModifiers.clear();
g.FontStack.clear();
g.OpenPopupStack.clear();
g.BeginPopupStack.clear();
g.DrawDataBuilder.ClearFreeMemory();
g.BackgroundDrawList.ClearFreeMemory();
g.ForegroundDrawList.ClearFreeMemory();
g.TabBars.Clear();
g.CurrentTabBarStack.clear();
g.ShrinkWidthBuffer.clear();
g.PrivateClipboard.clear();
g.InputTextState.ClearFreeMemory();
for (int i = 0; i < g.SettingsWindows.Size; i++)
IM_DELETE(g.SettingsWindows[i].Name);
g.SettingsWindows.clear();
g.SettingsHandlers.clear();
if (g.LogFile && g.LogFile != stdout)
{
fclose(g.LogFile);
g.LogFile = NULL;
}
g.LogBuffer.clear();
g.Initialized = false;
}
// FIXME: Add a more explicit sort order in the window structure.
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
{
const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
return d;
if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
return d;
return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
}
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
{
out_sorted_windows->push_back(window);
if (window->Active)
{
int count = window->DC.ChildWindows.Size;
if (count > 1)
ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
for (int i = 0; i < count; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (child->Active)
AddWindowToSortBuffer(out_sorted_windows, child);
}
}
}
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
{
if (draw_list->CmdBuffer.empty())
return;
// Remove trailing command if unused
ImDrawCmd& last_cmd = draw_list->CmdBuffer.back();
if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL)
{
draw_list->CmdBuffer.pop_back();
if (draw_list->CmdBuffer.empty())
return;
}
// Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
// May trigger for you if you are using PrimXXX functions incorrectly.
IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
// Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
// If this assert triggers because you are drawing lots of stuff manually:
// - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
// Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics window to inspect draw list contents.
// - If you want large meshes with more than 64K vertices, you can either:
// (A) Handle the ImDrawCmd::VtxOffset value in your renderer back-end, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
// Most example back-ends already support this from 1.71. Pre-1.71 back-ends won't.
// Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
// (B) Or handle 32-bits indices in your renderer back-end, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
// Most example back-ends already support this. For example, the OpenGL example code detect index size at compile-time:
// glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
// Your own engine or render API may use different parameters or function calls to specify index sizes.
// 2 and 4 bytes indices are generally supported by most graphics API.
// - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
// the 64K limit to split your draw commands in multiple draw lists.
if (sizeof(ImDrawIdx) == 2)
IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
out_list->push_back(draw_list);
}
static void AddWindowToDrawData(ImVector<ImDrawList*>* out_render_list, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.IO.MetricsRenderWindows++;
AddDrawListToDrawData(out_render_list, window->DrawList);
for (int i = 0; i < window->DC.ChildWindows.Size; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (IsWindowActiveAndVisible(child)) // clipped children may have been marked not active
AddWindowToDrawData(out_render_list, child);
}
}
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
static void AddRootWindowToDrawData(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (window->Flags & ImGuiWindowFlags_Tooltip)
AddWindowToDrawData(&g.DrawDataBuilder.Layers[1], window);
else
AddWindowToDrawData(&g.DrawDataBuilder.Layers[0], window);
}
void ImDrawDataBuilder::FlattenIntoSingleLayer()
{
int n = Layers[0].Size;
int size = n;
for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
size += Layers[i].Size;
Layers[0].resize(size);
for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
{
ImVector<ImDrawList*>& layer = Layers[layer_n];
if (layer.empty())
continue;
memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
n += layer.Size;
layer.resize(0);
}
}
static void SetupDrawData(ImVector<ImDrawList*>* draw_lists, ImDrawData* draw_data)
{
ImGuiIO& io = ImGui::GetIO();
draw_data->Valid = true;
draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
draw_data->CmdListsCount = draw_lists->Size;
draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
draw_data->DisplayPos = ImVec2(0.0f, 0.0f);
draw_data->DisplaySize = io.DisplaySize;
draw_data->FramebufferScale = io.DisplayFramebufferScale;
for (int n = 0; n < draw_lists->Size; n++)
{
draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
}
}
// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result.
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
window->ClipRect = window->DrawList->_ClipRectStack.back();
}
void ImGui::PopClipRect()
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->PopClipRect();
window->ClipRect = window->DrawList->_ClipRectStack.back();
}
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
void ImGui::EndFrame()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times.
return;
IM_ASSERT(g.FrameScopeActive && "Forgot to call ImGui::NewFrame()?");
// Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
if (g.IO.ImeSetInputScreenPosFn && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImeLastPos - g.PlatformImePos) > 0.0001f))
{
g.IO.ImeSetInputScreenPosFn((int)g.PlatformImePos.x, (int)g.PlatformImePos.y);
g.PlatformImeLastPos = g.PlatformImePos;
}
// Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
// to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
if (g.CurrentWindowStack.Size != 1)
{
if (g.CurrentWindowStack.Size > 1)
{
IM_ASSERT(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
while (g.CurrentWindowStack.Size > 1) // FIXME-ERRORHANDLING
End();
}
else
{
IM_ASSERT(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
}
}
// Hide implicit/fallback "Debug" window if it hasn't been used
g.FrameScopePushedImplicitWindow = false;
if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
g.CurrentWindow->Active = false;
End();
// Show CTRL+TAB list window
if (g.NavWindowingTarget)
NavUpdateWindowingList();
// Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
if (g.DragDropActive)
{
bool is_delivered = g.DragDropPayload.Delivery;
bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
if (is_delivered || is_elapsed)
ClearDragDrop();
}
// Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount)
{
g.DragDropWithinSourceOrTarget = true;
SetTooltip("...");
g.DragDropWithinSourceOrTarget = false;
}
// End frame
g.FrameScopeActive = false;
g.FrameCountEnded = g.FrameCount;
// Initiate moving window + handle left-click and right-click focus
UpdateMouseMovingWindowEndFrame();
// Sort the window list so that all child windows are after their parent
// We cannot do that on FocusWindow() because childs may not exist yet
g.WindowsSortBuffer.resize(0);
g.WindowsSortBuffer.reserve(g.Windows.Size);
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
continue;
AddWindowToSortBuffer(&g.WindowsSortBuffer, window);
}
// This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size);
g.Windows.swap(g.WindowsSortBuffer);
g.IO.MetricsActiveWindows = g.WindowsActiveCount;
// Unlock font atlas
g.IO.Fonts->Locked = false;
// Clear Input data for next frame
g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
g.IO.InputQueueCharacters.resize(0);
memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
}
void ImGui::Render()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
if (g.FrameCountEnded != g.FrameCount)
EndFrame();
g.FrameCountRendered = g.FrameCount;
// Gather ImDrawList to render (for each active window)
g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsRenderWindows = 0;
g.DrawDataBuilder.Clear();
if (!g.BackgroundDrawList.VtxBuffer.empty())
AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.BackgroundDrawList);
ImGuiWindow* windows_to_render_top_most[2];
windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
windows_to_render_top_most[1] = g.NavWindowingTarget ? g.NavWindowingList : NULL;
for (int n = 0; n != g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
AddRootWindowToDrawData(window);
}
for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
AddRootWindowToDrawData(windows_to_render_top_most[n]);
g.DrawDataBuilder.FlattenIntoSingleLayer();
// Draw software mouse cursor if requested
if (g.IO.MouseDrawCursor)
RenderMouseCursor(&g.ForegroundDrawList, g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor);
if (!g.ForegroundDrawList.VtxBuffer.empty())
AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.ForegroundDrawList);
// Setup ImDrawData structure for end-user
SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData);
g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount;
g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount;
// (Legacy) Call the Render callback function. The current prefer way is to let the user retrieve GetDrawData() and call the render function themselves.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
g.IO.RenderDrawListsFn(&g.DrawData);
#endif
}
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
// CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize)
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
{
ImGuiContext& g = *GImGui;
const char* text_display_end;
if (hide_text_after_double_hash)
text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
else
text_display_end = text_end;
ImFont* font = g.Font;
const float font_size = g.FontSize;
if (text == text_display_end)
return ImVec2(0.0f, font_size);
ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
// Round
text_size.x = (float)(int)(text_size.x + 0.95f);
return text_size;
}
// Find window given position, search front-to-back
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programatically
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
// called, aka before the next Begin(). Moving window isn't affected.
static void FindHoveredWindow()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* hovered_window = NULL;
if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
hovered_window = g.MovingWindow;
ImVec2 padding_regular = g.Style.TouchExtraPadding;
ImVec2 padding_for_resize_from_edges = g.IO.ConfigWindowsResizeFromEdges ? ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS)) : padding_regular;
for (int i = g.Windows.Size - 1; i >= 0; i--)
{
ImGuiWindow* window = g.Windows[i];
if (!window->Active || window->Hidden)
continue;
if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
continue;
// Using the clipped AABB, a child window will typically be clipped by its parent (not always)
ImRect bb(window->OuterRectClipped);
if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
bb.Expand(padding_regular);
else
bb.Expand(padding_for_resize_from_edges);
if (!bb.Contains(g.IO.MousePos))
continue;
// Those seemingly unnecessary extra tests are because the code here is a little different in viewport/docking branches.
if (hovered_window == NULL)
hovered_window = window;
if (hovered_window)
break;
}
g.HoveredWindow = hovered_window;
g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
}
// Test if mouse cursor is hovering given rectangle
// NB- Rectangle is clipped by our current clip setting
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
{
ImGuiContext& g = *GImGui;
// Clip
ImRect rect_clipped(r_min, r_max);
if (clip)
rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
// Expand for touch input
const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
if (!rect_for_touch.Contains(g.IO.MousePos))
return false;
return true;
}
int ImGui::GetKeyIndex(ImGuiKey imgui_key)
{
IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
ImGuiContext& g = *GImGui;
return g.IO.KeyMap[imgui_key];
}
// Note that imgui doesn't know the semantic of each entry of io.KeysDown[]. Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]!
bool ImGui::IsKeyDown(int user_key_index)
{
if (user_key_index < 0)
return false;
ImGuiContext& g = *GImGui;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
return g.IO.KeysDown[user_key_index];
}
int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate)
{
if (t == 0.0f)
return 1;
if (t <= repeat_delay || repeat_rate <= 0.0f)
return 0;
const int count = (int)((t - repeat_delay) / repeat_rate) - (int)((t_prev - repeat_delay) / repeat_rate);
return (count > 0) ? count : 0;
}
int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
{
ImGuiContext& g = *GImGui;
if (key_index < 0)
return 0;
IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[key_index];
return CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, repeat_delay, repeat_rate);
}
bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
{
ImGuiContext& g = *GImGui;
if (user_key_index < 0)
return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[user_key_index];
if (t == 0.0f)
return true;
if (repeat && t > g.IO.KeyRepeatDelay)
return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
return false;
}
bool ImGui::IsKeyReleased(int user_key_index)
{
ImGuiContext& g = *GImGui;
if (user_key_index < 0) return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
}
bool ImGui::IsMouseDown(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDown[button];
}
bool ImGui::IsAnyMouseDown()
{
ImGuiContext& g = *GImGui;
for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
if (g.IO.MouseDown[n])
return true;
return false;
}
bool ImGui::IsMouseClicked(int button, bool repeat)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
const float t = g.IO.MouseDownDuration[button];
if (t == 0.0f)
return true;
if (repeat && t > g.IO.KeyRepeatDelay)
{
// FIXME: 2019/05/03: Our old repeat code was wrong here and led to doubling the repeat rate, which made it an ok rate for repeat on mouse hold.
int amount = CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.5f);
if (amount > 0)
return true;
}
return false;
}
bool ImGui::IsMouseReleased(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseReleased[button];
}
bool ImGui::IsMouseDoubleClicked(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDoubleClicked[button];
}
// [Internal] This doesn't test if the button is presed
bool ImGui::IsMouseDragPastThreshold(int button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
}
bool ImGui::IsMouseDragging(int button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (!g.IO.MouseDown[button])
return false;
return IsMouseDragPastThreshold(button, lock_threshold);
}
ImVec2 ImGui::GetMousePos()
{
return GImGui->IO.MousePos;
}
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
{
ImGuiContext& g = *GImGui;
if (g.BeginPopupStack.Size > 0)
return g.OpenPopupStack[g.BeginPopupStack.Size-1].OpenMousePos;
return g.IO.MousePos;
}
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
{
// The assert is only to silence a false-positive in XCode Static Analysis.
// Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
IM_ASSERT(GImGui != NULL);
const float MOUSE_INVALID = -256000.0f;
ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
}
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
// NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window.
ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
return g.IO.MousePos - g.IO.MouseClickedPos[button];
return ImVec2(0.0f, 0.0f);
}
void ImGui::ResetMouseDragDelta(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
// NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
g.IO.MouseClickedPos[button] = g.IO.MousePos;
}
ImGuiMouseCursor ImGui::GetMouseCursor()
{
return GImGui->MouseCursor;
}
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
{
GImGui->MouseCursor = cursor_type;
}
void ImGui::CaptureKeyboardFromApp(bool capture)
{
GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0;
}
void ImGui::CaptureMouseFromApp(bool capture)
{
GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0;
}
bool ImGui::IsItemActive()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
ImGuiWindow* window = g.CurrentWindow;
return g.ActiveId == window->DC.LastItemId;
}
return false;
}
bool ImGui::IsItemActivated()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
ImGuiWindow* window = g.CurrentWindow;
if (g.ActiveId == window->DC.LastItemId && g.ActiveIdPreviousFrame != window->DC.LastItemId)
return true;
}
return false;
}
bool ImGui::IsItemDeactivated()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDeactivated)
return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId);
}
bool ImGui::IsItemDeactivatedAfterEdit()
{
ImGuiContext& g = *GImGui;
return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
}
bool ImGui::IsItemFocused()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavId == 0 || g.NavDisableHighlight || g.NavId != window->DC.LastItemId)
return false;
return true;
}
bool ImGui::IsItemClicked(int mouse_button)
{
return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
}
bool ImGui::IsItemToggledSelection()
{
ImGuiContext& g = *GImGui;
return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
}
bool ImGui::IsAnyItemHovered()
{
ImGuiContext& g = *GImGui;
return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
}
bool ImGui::IsAnyItemActive()
{
ImGuiContext& g = *GImGui;
return g.ActiveId != 0;
}
bool ImGui::IsAnyItemFocused()
{
ImGuiContext& g = *GImGui;
return g.NavId != 0 && !g.NavDisableHighlight;
}
bool ImGui::IsItemVisible()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ClipRect.Overlaps(window->DC.LastItemRect);
}
bool ImGui::IsItemEdited()
{
ImGuiWindow* window = GetCurrentWindowRead();
return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Edited) != 0;
}
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
void ImGui::SetItemAllowOverlap()
{
ImGuiContext& g = *GImGui;
if (g.HoveredId == g.CurrentWindow->DC.LastItemId)
g.HoveredIdAllowOverlap = true;
if (g.ActiveId == g.CurrentWindow->DC.LastItemId)
g.ActiveIdAllowOverlap = true;
}
ImVec2 ImGui::GetItemRectMin()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.Min;
}
ImVec2 ImGui::GetItemRectMax()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.Max;
}
ImVec2 ImGui::GetItemRectSize()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.GetSize();
}
static ImRect GetViewportRect()
{
ImGuiContext& g = *GImGui;
return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
}
static bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
flags |= ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow;
flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
// Size
const ImVec2 content_avail = GetContentRegionAvail();
ImVec2 size = ImFloor(size_arg);
const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
if (size.x <= 0.0f)
size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
if (size.y <= 0.0f)
size.y = ImMax(content_avail.y + size.y, 4.0f);
SetNextWindowSize(size);
// Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
char title[256];
if (name)
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id);
else
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id);
const float backup_border_size = g.Style.ChildBorderSize;
if (!border)
g.Style.ChildBorderSize = 0.0f;
bool ret = Begin(title, NULL, flags);
g.Style.ChildBorderSize = backup_border_size;
ImGuiWindow* child_window = g.CurrentWindow;
child_window->ChildId = id;
child_window->AutoFitChildAxises = auto_fit_axises;
// Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
// While this is not really documented/defined, it seems that the expected thing to do.
if (child_window->BeginCount == 1)
parent_window->DC.CursorPos = child_window->Pos;
// Process navigation-in immediately so NavInit can run on first frame
if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll))
{
FocusWindow(child_window);
NavInitWindow(child_window, false);
SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item
g.ActiveIdSource = ImGuiInputSource_Nav;
}
return ret;
}
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
ImGuiWindow* window = GetCurrentWindow();
return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
}
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
IM_ASSERT(id != 0);
return BeginChildEx(NULL, id, size_arg, border, extra_flags);
}
void ImGui::EndChild()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
if (window->BeginCount > 1)
{
End();
}
else
{
ImVec2 sz = window->Size;
if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
sz.x = ImMax(4.0f, sz.x);
if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
sz.y = ImMax(4.0f, sz.y);
End();
ImGuiWindow* parent_window = g.CurrentWindow;
ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
ItemSize(sz);
if ((window->DC.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
{
ItemAdd(bb, window->ChildId);
RenderNavHighlight(bb, window->ChildId);
// When browsing a window that has no activable items (scroll only) we keep a highlight on the child
if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow)
RenderNavHighlight(ImRect(bb.Min - ImVec2(2,2), bb.Max + ImVec2(2,2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
}
else
{
// Not navigable into
ItemAdd(bb, 0);
}
}
}
// Helper to create a child window / scrolling region that looks like a normal widget frame.
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
PopStyleVar(3);
PopStyleColor();
return ret;
}
void ImGui::EndChildFrame()
{
EndChild();
}
// Save and compare stack sizes on Begin()/End() to detect usage errors
static void CheckStacksSize(ImGuiWindow* window, bool write)
{
// NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
ImGuiContext& g = *GImGui;
short* p_backup = &window->DC.StackSizesBackup[0];
{ int current = window->IDStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop()
{ int current = window->DC.GroupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup()
{ int current = g.BeginPopupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup()
// For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
{ int current = g.ColorModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor()
{ int current = g.StyleModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar()
{ int current = g.FontStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont()
IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
}
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
{
window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
}
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
}
ImGuiWindow* ImGui::FindWindowByName(const char* name)
{
ImGuiID id = ImHashStr(name);
return FindWindowByID(id);
}
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
//IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
// Create window the first time
ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
window->Flags = flags;
g.WindowsById.SetVoidPtr(window->ID, window);
// Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
window->Pos = ImVec2(60, 60);
// User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
if (!(flags & ImGuiWindowFlags_NoSavedSettings))
if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
{
// Retrieve settings from .ini file
window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings);
SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
window->Pos = ImFloor(settings->Pos);
window->Collapsed = settings->Collapsed;
if (ImLengthSqr(settings->Size) > 0.00001f)
size = ImFloor(settings->Size);
}
window->Size = window->SizeFull = ImFloor(size);
window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
{
window->AutoFitFramesX = window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = false;
}
else
{
if (window->Size.x <= 0.0f)
window->AutoFitFramesX = 2;
if (window->Size.y <= 0.0f)
window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
}
g.WindowsFocusOrder.push_back(window);
if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
g.Windows.push_front(window); // Quite slow but rare and only once
else
g.Windows.push_back(window);
return window;
}
static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
{
ImGuiContext& g = *GImGui;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
{
// Using -1,-1 on either X/Y axis to preserve the current size.
ImRect cr = g.NextWindowData.SizeConstraintRect;
new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
if (g.NextWindowData.SizeCallback)
{
ImGuiSizeCallbackData data;
data.UserData = g.NextWindowData.SizeCallbackUserData;
data.Pos = window->Pos;
data.CurrentSize = window->SizeFull;
data.DesiredSize = new_size;
g.NextWindowData.SizeCallback(&data);
new_size = data.DesiredSize;
}
new_size.x = ImFloor(new_size.x);
new_size.y = ImFloor(new_size.y);
}
// Minimum size
if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
{
new_size = ImMax(new_size, g.Style.WindowMinSize);
new_size.y = ImMax(new_size.y, window->TitleBarHeight() + window->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
}
return new_size;
}
static ImVec2 CalcContentSize(ImGuiWindow* window)
{
if (window->Collapsed)
if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
return window->ContentSize;
if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
return window->ContentSize;
ImVec2 sz;
sz.x = (float)(int)((window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
sz.y = (float)(int)((window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
return sz;
}
static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImVec2 size_decorations = ImVec2(0.0f, window->TitleBarHeight() + window->MenuBarHeight());
ImVec2 size_pad = window->WindowPadding * 2.0f;
ImVec2 size_desired = size_contents + size_pad + size_decorations;
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Tooltip always resize
return size_desired;
}
else
{
// Maximum window size is determined by the viewport size or monitor size
const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
ImVec2 size_min = style.WindowMinSize;
if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, g.IO.DisplaySize - style.DisplaySafeAreaPadding * 2.0f));
// When the window cannot fit all contents (either because of constraints, either because screen is too small),
// we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit);
bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - size_decorations.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - size_decorations.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
if (will_have_scrollbar_x)
size_auto_fit.y += style.ScrollbarSize;
if (will_have_scrollbar_y)
size_auto_fit.x += style.ScrollbarSize;
return size_auto_fit;
}
}
ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window)
{
ImVec2 size_contents = CalcContentSize(window);
return CalcSizeAfterConstraint(window, CalcSizeAutoFit(window, size_contents));
}
static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)
{
if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
return ImGuiCol_PopupBg;
if (flags & ImGuiWindowFlags_ChildWindow)
return ImGuiCol_ChildBg;
return ImGuiCol_WindowBg;
}
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
{
ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
ImVec2 size_expected = pos_max - pos_min;
ImVec2 size_constrained = CalcSizeAfterConstraint(window, size_expected);
*out_pos = pos_min;
if (corner_norm.x == 0.0f)
out_pos->x -= (size_constrained.x - size_expected.x);
if (corner_norm.y == 0.0f)
out_pos->y -= (size_constrained.y - size_expected.y);
*out_size = size_constrained;
}
struct ImGuiResizeGripDef
{
ImVec2 CornerPosN;
ImVec2 InnerDir;
int AngleMin12, AngleMax12;
};
static const ImGuiResizeGripDef resize_grip_def[4] =
{
{ ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower right
{ ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower left
{ ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper left
{ ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper right
};
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
{
ImRect rect = window->Rect();
if (thickness == 0.0f) rect.Max -= ImVec2(1,1);
if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); // Top
if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); // Right
if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); // Bottom
if (border_n == 3) return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); // Left
IM_ASSERT(0);
return ImRect();
}
// Handle resize for: Resize Grips, Borders, Gamepad
// Return true when using auto-fit (double click on resize grip)
static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4])
{
ImGuiContext& g = *GImGui;
ImGuiWindowFlags flags = window->Flags;
if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
return false;
if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window.
return false;
bool ret_auto_fit = false;
const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
const float grip_hover_inner_size = (float)(int)(grip_draw_size * 0.75f);
const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS : 0.0f;
ImVec2 pos_target(FLT_MAX, FLT_MAX);
ImVec2 size_target(FLT_MAX, FLT_MAX);
// Resize grips and borders are on layer 1
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
// Manual resize grips
PushID("#RESIZE");
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
// Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
ImRect resize_rect(corner - grip.InnerDir * grip_hover_outer_size, corner + grip.InnerDir * grip_hover_inner_size);
if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
bool hovered, held;
ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
//GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
if (hovered || held)
g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
{
// Manual auto-fit when double-clicking
size_target = CalcSizeAfterConstraint(window, size_auto_fit);
ret_auto_fit = true;
ClearActiveID();
}
else if (held)
{
// Resize from any of the four corners
// We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip
CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target);
}
if (resize_grip_n == 0 || held || hovered)
resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
}
for (int border_n = 0; border_n < resize_border_count; border_n++)
{
bool hovered, held;
ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS);
ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
//GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
{
g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
if (held)
*border_held = border_n;
}
if (held)
{
ImVec2 border_target = window->Pos;
ImVec2 border_posn;
if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Top
if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right
if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom
if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left
CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
}
}
PopID();
// Navigation resize (keyboard/gamepad)
if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
{
ImVec2 nav_resize_delta;
if (g.NavInputSource == ImGuiInputSource_NavKeyboard && g.IO.KeyShift)
nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_NavGamepad)
nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down);
if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f)
{
const float NAV_RESIZE_SPEED = 600.0f;
nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
g.NavWindowingToggleLayer = false;
g.NavDisableMouseHover = true;
resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
// FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
size_target = CalcSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
}
}
// Apply back modified position/size to window
if (size_target.x != FLT_MAX)
{
window->SizeFull = size_target;
MarkIniSettingsDirty(window);
}
if (pos_target.x != FLT_MAX)
{
window->Pos = ImFloor(pos_target);
MarkIniSettingsDirty(window);
}
// Resize nav layer
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->Size = window->SizeFull;
return ret_auto_fit;
}
static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& rect, const ImVec2& padding)
{
ImGuiContext& g = *GImGui;
ImVec2 size_for_clamping = (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size;
window->Pos = ImMin(rect.Max - padding, ImMax(window->Pos + size_for_clamping, rect.Min + padding) - size_for_clamping);
}
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
float rounding = window->WindowRounding;
float border_size = window->WindowBorderSize;
if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
int border_held = window->ResizeBorderHeld;
if (border_held != -1)
{
struct ImGuiResizeBorderDef
{
ImVec2 InnerDir;
ImVec2 CornerPosN1, CornerPosN2;
float OuterAngle;
};
static const ImGuiResizeBorderDef resize_border_def[4] =
{
{ ImVec2(0,+1), ImVec2(0,0), ImVec2(1,0), IM_PI*1.50f }, // Top
{ ImVec2(-1,0), ImVec2(1,0), ImVec2(1,1), IM_PI*0.00f }, // Right
{ ImVec2(0,-1), ImVec2(1,1), ImVec2(0,1), IM_PI*0.50f }, // Bottom
{ ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left
};
const ImGuiResizeBorderDef& def = resize_border_def[border_held];
ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI*0.25f, def.OuterAngle);
window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI*0.25f);
window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), false, ImMax(2.0f, border_size)); // Thicker than usual
}
if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
{
float y = window->Pos.y + window->TitleBarHeight() - 1;
window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
}
}
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImGuiWindowFlags flags = window->Flags;
// Draw window + handle manual resize
// As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame.
const float window_rounding = window->WindowRounding;
const float window_border_size = window->WindowBorderSize;
if (window->Collapsed)
{
// Title bar only
float backup_border_size = style.FrameBorderSize;
g.Style.FrameBorderSize = window->WindowBorderSize;
ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
g.Style.FrameBorderSize = backup_border_size;
}
else
{
// Window background
if (!(flags & ImGuiWindowFlags_NoBackground))
{
ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
float alpha = 1.0f;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
alpha = g.NextWindowData.BgAlphaVal;
if (alpha != 1.0f)
bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
}
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
{
ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top);
}
// Menu bar
if (flags & ImGuiWindowFlags_MenuBar)
{
ImRect menu_bar_rect = window->MenuBarRect();
menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top);
if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
}
// Scrollbars
if (window->ScrollbarX)
Scrollbar(ImGuiAxis_X);
if (window->ScrollbarY)
Scrollbar(ImGuiAxis_Y);
// Render resize grips (after their input handling so we don't have a frame of latency)
if (!(flags & ImGuiWindowFlags_NoResize))
{
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
}
}
// Borders
RenderWindowOuterBorders(window);
}
}
// Render title text, collapse button, close button
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImGuiWindowFlags flags = window->Flags;
const bool has_close_button = (p_open != NULL);
const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse);
// Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
// Layout buttons
// FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
float pad_l = style.FramePadding.x;
float pad_r = style.FramePadding.x;
float button_sz = g.FontSize;
ImVec2 close_button_pos;
ImVec2 collapse_button_pos;
if (has_close_button)
{
pad_r += button_sz;
close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
}
if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
{
pad_r += button_sz;
collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
}
if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
{
collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
pad_l += button_sz;
}
// Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
if (has_collapse_button)
if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos))
window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
// Close button
if (has_close_button)
if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
*p_open = false;
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->DC.ItemFlags = item_flags_backup;
// Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
// FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
const char* UNSAVED_DOCUMENT_MARKER = "*";
const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f;
const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
// As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
// while uncentered title text will still reach edges correct.
if (pad_l > style.FramePadding.x)
pad_l += g.Style.ItemInnerSpacing.x;
if (pad_r > style.FramePadding.x)
pad_r += g.Style.ItemInnerSpacing.x;
if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
{
float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
pad_l = ImMax(pad_l, pad_extend * centerness);
pad_r = ImMax(pad_r, pad_extend * centerness);
}
ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
ImRect clip_r(layout_r.Min.x, layout_r.Min.y, layout_r.Max.x + g.Style.ItemInnerSpacing.x, layout_r.Max.y);
//if (g.IO.KeyCtrl) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
if (flags & ImGuiWindowFlags_UnsavedDocument)
{
ImVec2 marker_pos = ImVec2(ImMax(layout_r.Min.x, layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, layout_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f);
ImVec2 off = ImVec2(0.0f, (float)(int)(-g.FontSize * 0.25f));
RenderTextClipped(marker_pos + off, layout_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_r);
}
}
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
{
window->ParentWindow = parent_window;
window->RootWindow = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
window->RootWindow = parent_window->RootWindow;
if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
{
IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
}
}
// Push a new Dear ImGui window to add widgets to.
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
// - Begin/End can be called multiple times during the frame with the same window name to append content.
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
IM_ASSERT(g.FrameScopeActive); // Forgot to call ImGui::NewFrame()
IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
// Find or create
ImGuiWindow* window = FindWindowByName(name);
const bool window_just_created = (window == NULL);
if (window_just_created)
{
ImVec2 size_on_first_use = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here.
window = CreateNewWindow(name, size_on_first_use, flags);
}
// Automatically disable manual moving/resizing when NoInputs is set
if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
if (flags & ImGuiWindowFlags_NavFlattened)
IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
const int current_frame = g.FrameCount;
const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
// Update the Appearing flag
bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
window_just_activated_by_user |= (window != popup_ref.Window);
}
window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize);
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
// Update Flags, LastFrameActive, BeginOrderXXX fields
if (first_begin_of_the_frame)
{
window->Flags = (ImGuiWindowFlags)flags;
window->LastFrameActive = current_frame;
window->BeginOrderWithinParent = 0;
window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
}
else
{
flags = window->Flags;
}
// Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
// Add to stack
// We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
g.CurrentWindowStack.push_back(window);
g.CurrentWindow = NULL;
CheckStacksSize(window, true);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
popup_ref.Window = window;
g.BeginPopupStack.push_back(popup_ref);
window->PopupId = popup_ref.PopupId;
}
if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow))
window->NavLastIds[0] = 0;
// Process SetNextWindow***() calls
bool window_pos_set_by_api = false;
bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
{
window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
{
// May be processed on the next frame if this is our first frame and we are measuring size
// FIXME: Look into removing the branch so everything can go through this same code path for consistency.
window->SetWindowPosVal = g.NextWindowData.PosVal;
window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
}
else
{
SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
}
}
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
{
window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
}
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
else if (first_begin_of_the_frame)
window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
FocusWindow(window);
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
// When reusing window again multiple times a frame, just append content (don't need to setup again)
if (first_begin_of_the_frame)
{
// Initialize
const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
UpdateWindowParentAndRootLinks(window, flags, parent_window);
window->Active = true;
window->HasCloseButton = (p_open != NULL);
window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
window->IDStack.resize(1);
// Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
// The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
bool window_title_visible_elsewhere = false;
if (g.NavWindowingList != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
window_title_visible_elsewhere = true;
if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
{
size_t buf_len = (size_t)window->NameBufLen;
window->Name = ImStrdupcpy(window->Name, &buf_len, name);
window->NameBufLen = (int)buf_len;
}
// UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
// Update contents size from last frame for auto-fitting (or use explicit size)
window->ContentSize = CalcContentSize(window);
if (window->HiddenFramesCanSkipItems > 0)
window->HiddenFramesCanSkipItems--;
if (window->HiddenFramesCannotSkipItems > 0)
window->HiddenFramesCannotSkipItems--;
// Hide new windows for one frame until they calculate their size
if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
window->HiddenFramesCannotSkipItems = 1;
// Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
// We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
{
window->HiddenFramesCannotSkipItems = 1;
if (flags & ImGuiWindowFlags_AlwaysAutoResize)
{
if (!window_size_x_set_by_api)
window->Size.x = window->SizeFull.x = 0.f;
if (!window_size_y_set_by_api)
window->Size.y = window->SizeFull.y = 0.f;
window->ContentSize = ImVec2(0.f, 0.f);
}
}
// FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style)
SetCurrentWindow(window);
// LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
if (flags & ImGuiWindowFlags_ChildWindow)
window->WindowBorderSize = style.ChildBorderSize;
else
window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
window->WindowPadding = style.WindowPadding;
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
// Collapse window by double-clicking on title bar
// At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
{
// We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
ImRect title_bar_rect = window->TitleBarRect();
if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
window->WantCollapseToggle = true;
if (window->WantCollapseToggle)
{
window->Collapsed = !window->Collapsed;
MarkIniSettingsDirty(window);
FocusWindow(window);
}
}
else
{
window->Collapsed = false;
}
window->WantCollapseToggle = false;
// SIZE
// Calculate auto-fit size, handle automatic resize
const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->ContentSize);
bool use_current_size_for_scrollbar_x = window_just_created;
bool use_current_size_for_scrollbar_y = window_just_created;
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
{
// Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
if (!window_size_x_set_by_api)
{
window->SizeFull.x = size_auto_fit.x;
use_current_size_for_scrollbar_x = true;
}
if (!window_size_y_set_by_api)
{
window->SizeFull.y = size_auto_fit.y;
use_current_size_for_scrollbar_y = true;
}
}
else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
{
// Auto-fit may only grow window during the first few frames
// We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
{
window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
use_current_size_for_scrollbar_x = true;
}
if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
{
window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
use_current_size_for_scrollbar_y = true;
}
if (!window->Collapsed)
MarkIniSettingsDirty(window);
}
// Apply minimum/maximum window size constraints and final size
window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull);
window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
// Decoration size
const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
// POSITION
// Popup latch its initial position, will position itself when it appears next frame
if (window_just_activated_by_user)
{
window->AutoPosLastDirection = ImGuiDir_None;
if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
window->Pos = g.BeginPopupStack.back().OpenPopupPos;
}
// Position child window
if (flags & ImGuiWindowFlags_ChildWindow)
{
IM_ASSERT(parent_window && parent_window->Active);
window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
parent_window->DC.ChildWindows.push_back(window);
if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = parent_window->DC.CursorPos;
}
const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
if (window_pos_with_pivot)
SetWindowPos(window, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = FindBestWindowPosForPopup(window);
// Clamp position/size so window stays visible within its viewport or monitor
// Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
ImRect viewport_rect(GetViewportRect());
if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
{
if (g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
{
ImVec2 clamp_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
ClampWindowRect(window, viewport_rect, clamp_padding);
}
}
window->Pos = ImFloor(window->Pos);
// Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
// Apply window focus (new and reactivated windows are moved to front)
bool want_focus = false;
if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
{
if (flags & ImGuiWindowFlags_Popup)
want_focus = true;
else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0)
want_focus = true;
}
// Handle manual resize: Resize Grips, Borders, Gamepad
int border_held = -1;
ImU32 resize_grip_col[4] = { 0 };
const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // 4
const float resize_grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
if (!window->Collapsed)
if (UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]))
use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
window->ResizeBorderHeld = (signed char)border_held;
// SCROLLBAR VISIBILITY
// Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
if (!window->Collapsed)
{
// When reading the current size we need to read it after size constraints have been applied.
// When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again.
ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height);
ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes;
ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
//bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
if (window->ScrollbarX && !window->ScrollbarY)
window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
}
// UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
// Update various regions. Variables they depends on should be set above in this function.
// We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
// Outer rectangle
// Not affected by window border size. Used by:
// - FindHoveredWindow() (w/ extra padding when border resize is enabled)
// - Begin() initial clipping rect for drawing window background and borders.
// - Begin() clipping whole child
const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
const ImRect outer_rect = window->Rect();
const ImRect title_bar_rect = window->TitleBarRect();
window->OuterRectClipped = outer_rect;
window->OuterRectClipped.ClipWith(host_rect);
// Inner rectangle
// Not affected by window border size. Used by:
// - InnerClipRect
// - ScrollToBringRectIntoView()
// - NavUpdatePageUpPageDown()
// - Scrollbar()
window->InnerRect.Min.x = window->Pos.x;
window->InnerRect.Min.y = window->Pos.y + decoration_up_height;
window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x;
window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y;
// Inner clipping rectangle.
// Will extend a little bit outside the normal work region.
// This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
// Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
// Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
// Affected by window/frame border size. Used by:
// - Begin() initial clip rect
float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
window->InnerClipRect.ClipWithFull(host_rect);
// Default item width. Make it proportional to window size if window manually resizes
if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f);
else
window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f);
// SCROLLING
// Lock down maximum scrolling
// The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
// for right/bottom aligned items without creating a scrollbar.
window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
// Apply scrolling
window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true);
window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
// DRAWING
// Setup draw list and outer clipping rectangle
window->DrawList->Clear();
window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
PushClipRect(host_rect.Min, host_rect.Max, false);
// Draw modal window background (darkens what is behind them, all viewports)
const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetTopMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0;
const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && (window == g.NavWindowingTargetAnim->RootWindow);
if (dim_bg_for_modal || dim_bg_for_window_list)
{
const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, dim_bg_col);
}
// Draw navigation selection/windowing rectangle background
if (dim_bg_for_window_list && window == g.NavWindowingTargetAnim)
{
ImRect bb = window->Rect();
bb.Expand(g.FontSize);
if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway
window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding);
}
// Since 1.71, child window can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call.
// When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
// We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping child.
// We also disabled this when we have dimming overlay behind this specific one child.
// FIXME: More code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected.
bool render_decorations_in_parent = false;
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_window->DrawList->VtxBuffer.Size > 0)
render_decorations_in_parent = true;
if (render_decorations_in_parent)
window->DrawList = parent_window->DrawList;
// Handle title bar, scrollbar, resize grips and resize borders
const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size);
if (render_decorations_in_parent)
window->DrawList = &window->DrawListInst;
// Draw navigation selection/windowing rectangle border
if (g.NavWindowingTargetAnim == window)
{
float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
ImRect bb = window->Rect();
bb.Expand(g.FontSize);
if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward
{
bb.Expand(-g.FontSize - 1.0f);
rounding = window->WindowRounding;
}
window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f);
}
// UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
// Work rectangle.
// Affected by window padding and border size. Used by:
// - Columns() for right-most edge
// - TreeNode(), CollapsingHeader() for right-most edge
// - BeginTabBar() for right-most edge
const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
// [LEGACY] Contents Region
// FIXME-OBSOLETE: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
// Used by:
// - Mouse wheel scrolling + many other things
window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height;
window->ContentsRegionRect.Max.x = window->ContentsRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
window->ContentsRegionRect.Max.y = window->ContentsRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
// Setup drawing context
// (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;
window->DC.GroupOffset.x = 0.0f;
window->DC.ColumnsOffset.x = 0.0f;
window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, decoration_up_height + window->WindowPadding.y - window->Scroll.y);
window->DC.CursorPos = window->DC.CursorStartPos;
window->DC.CursorPosPrevLine = window->DC.CursorPos;
window->DC.CursorMaxPos = window->DC.CursorStartPos;
window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
window->DC.NavHideHighlightOneFrame = false;
window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext;
window->DC.NavLayerActiveMaskNext = 0x00;
window->DC.MenuBarAppending = false;
window->DC.ChildWindows.resize(0);
window->DC.LayoutType = ImGuiLayoutType_Vertical;
window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
window->DC.FocusCounterAll = window->DC.FocusCounterTab = -1;
window->DC.ItemFlags = parent_window ? parent_window->DC.ItemFlags : ImGuiItemFlags_Default_;
window->DC.ItemWidth = window->ItemWidthDefault;
window->DC.TextWrapPos = -1.0f; // disabled
window->DC.ItemFlagsStack.resize(0);
window->DC.ItemWidthStack.resize(0);
window->DC.TextWrapPosStack.resize(0);
window->DC.CurrentColumns = NULL;
window->DC.TreeDepth = 0;
window->DC.TreeStoreMayJumpToParentOnPop = 0x00;
window->DC.StateStorage = &window->StateStorage;
window->DC.GroupStack.resize(0);
window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
if ((flags & ImGuiWindowFlags_ChildWindow) && (window->DC.ItemFlags != parent_window->DC.ItemFlags))
{
window->DC.ItemFlags = parent_window->DC.ItemFlags;
window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
}
if (window->AutoFitFramesX > 0)
window->AutoFitFramesX--;
if (window->AutoFitFramesY > 0)
window->AutoFitFramesY--;
// Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
if (want_focus)
{
FocusWindow(window);
NavInitWindow(window, false);
}
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
RenderWindowTitleBarContents(window, title_bar_rect, name, p_open);
// Pressing CTRL+C while holding on a window copy its content to the clipboard
// This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
// Maybe we can support CTRL+C on every element?
/*
if (g.ActiveId == move_id)
if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
LogToClipboard();
*/
// We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
// This is useful to allow creating context menus on title bar only, etc.
window->DC.LastItemId = window->MoveId;
window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
window->DC.LastItemRect = title_bar_rect;
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
IMGUI_TEST_ENGINE_ITEM_ADD(window->DC.LastItemRect, window->DC.LastItemId);
#endif
}
else
{
// Append
SetCurrentWindow(window);
}
PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
// Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
if (first_begin_of_the_frame)
window->WriteAccessed = false;
window->BeginCount++;
g.NextWindowData.ClearFlags();
if (flags & ImGuiWindowFlags_ChildWindow)
{
// Child window can be out of sight and have "negative" clip windows.
// Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
window->HiddenFramesCanSkipItems = 1;
// Hide along with parent or if parent is collapsed
if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
window->HiddenFramesCanSkipItems = 1;
if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
window->HiddenFramesCannotSkipItems = 1;
}
// Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
if (style.Alpha <= 0.0f)
window->HiddenFramesCanSkipItems = 1;
// Update the Hidden flag
window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
// Update the SkipItems flag, used to early out of all items functions (no layout required)
bool skip_items = false;
if (window->Collapsed || !window->Active || window->Hidden)
if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
skip_items = true;
window->SkipItems = skip_items;
return !skip_items;
}
// Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()/SetNextWindowBgAlpha() + Begin() instead.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_first_use, float bg_alpha_override, ImGuiWindowFlags flags)
{
// Old API feature: we could pass the initial window size as a parameter. This was misleading because it only had an effect if the window didn't have data in the .ini file.
if (size_first_use.x != 0.0f || size_first_use.y != 0.0f)
SetNextWindowSize(size_first_use, ImGuiCond_FirstUseEver);
// Old API feature: override the window background alpha with a parameter.
if (bg_alpha_override >= 0.0f)
SetNextWindowBgAlpha(bg_alpha_override);
return Begin(name, p_open, flags);
}
#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS
void ImGui::End()
{
ImGuiContext& g = *GImGui;
if (g.CurrentWindowStack.Size <= 1 && g.FrameScopePushedImplicitWindow)
{
IM_ASSERT(g.CurrentWindowStack.Size > 1 && "Calling End() too many times!");
return; // FIXME-ERRORHANDLING
}
IM_ASSERT(g.CurrentWindowStack.Size > 0);
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.CurrentColumns)
EndColumns();
PopClipRect(); // Inner window clip rectangle
// Stop logging
if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
LogFinish();
// Pop from window stack
g.CurrentWindowStack.pop_back();
if (window->Flags & ImGuiWindowFlags_Popup)
g.BeginPopupStack.pop_back();
CheckStacksSize(window, false);
SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
}
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.WindowsFocusOrder.back() == window)
return;
for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the top-most window
if (g.WindowsFocusOrder[i] == window)
{
memmove(&g.WindowsFocusOrder[i], &g.WindowsFocusOrder[i + 1], (size_t)(g.WindowsFocusOrder.Size - i - 1) * sizeof(ImGuiWindow*));
g.WindowsFocusOrder[g.WindowsFocusOrder.Size - 1] = window;
break;
}
}
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* current_front_window = g.Windows.back();
if (current_front_window == window || current_front_window->RootWindow == window)
return;
for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
if (g.Windows[i] == window)
{
memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
g.Windows[g.Windows.Size - 1] = window;
break;
}
}
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.Windows[0] == window)
return;
for (int i = 0; i < g.Windows.Size; i++)
if (g.Windows[i] == window)
{
memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
g.Windows[0] = window;
break;
}
}
// Moving window to front of display and set focus (which happens to be back of our sorted list)
void ImGui::FocusWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.NavWindow != window)
{
g.NavWindow = window;
if (window && g.NavDisableMouseHover)
g.NavMousePosDirty = true;
g.NavInitRequest = false;
g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
g.NavIdIsAlive = false;
g.NavLayer = ImGuiNavLayer_Main;
//IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL);
}
// Close popups if any
ClosePopupsOverWindow(window, false);
// Passing NULL allow to disable keyboard focus
if (!window)
return;
// Move the root window to the top of the pile
if (window->RootWindow)
window = window->RootWindow;
// Steal focus on active widgets
if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it..
if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window)
ClearActiveID();
// Bring to front
BringWindowToFocusFront(window);
if (!(window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus))
BringWindowToDisplayFront(window);
}
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
{
ImGuiContext& g = *GImGui;
int start_idx = g.WindowsFocusOrder.Size - 1;
if (under_this_window != NULL)
{
int under_this_window_idx = FindWindowFocusIndex(under_this_window);
if (under_this_window_idx != -1)
start_idx = under_this_window_idx - 1;
}
for (int i = start_idx; i >= 0; i--)
{
// We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
ImGuiWindow* window = g.WindowsFocusOrder[i];
if (window != ignore_window && window->WasActive && !(window->Flags & ImGuiWindowFlags_ChildWindow))
if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
{
ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
FocusWindow(focus_window);
return;
}
}
FocusWindow(NULL);
}
void ImGui::SetNextItemWidth(float item_width)
{
ImGuiContext& g = *GImGui;
g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
g.NextItemData.Width = item_width;
}
void ImGui::PushItemWidth(float item_width)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
}
void ImGui::PushMultiItemsWidths(int components, float w_full)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiStyle& style = g.Style;
const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
window->DC.ItemWidthStack.push_back(w_item_last);
for (int i = 0; i < components-1; i++)
window->DC.ItemWidthStack.push_back(w_item_one);
window->DC.ItemWidth = window->DC.ItemWidthStack.back();
g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
}
void ImGui::PopItemWidth()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemWidthStack.pop_back();
window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
}
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
float ImGui::CalcItemWidth()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float w;
if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
w = g.NextItemData.Width;
else
w = window->DC.ItemWidth;
if (w < 0.0f)
{
float region_max_x = GetContentRegionMaxAbs().x;
w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
}
w = (float)(int)w;
return w;
}
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
// Note that only CalcItemWidth() is publicly exposed.
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
{
ImGuiWindow* window = GImGui->CurrentWindow;
ImVec2 region_max;
if (size.x < 0.0f || size.y < 0.0f)
region_max = GetContentRegionMaxAbs();
if (size.x == 0.0f)
size.x = default_w;
else if (size.x < 0.0f)
size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
if (size.y == 0.0f)
size.y = default_h;
else if (size.y < 0.0f)
size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
return size;
}
void ImGui::SetCurrentFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
IM_ASSERT(font->Scale > 0.0f);
g.Font = font;
g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
ImFontAtlas* atlas = g.Font->ContainerAtlas;
g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
g.DrawListSharedData.Font = g.Font;
g.DrawListSharedData.FontSize = g.FontSize;
}
void ImGui::PushFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
if (!font)
font = GetDefaultFont();
SetCurrentFont(font);
g.FontStack.push_back(font);
g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
}
void ImGui::PopFont()
{
ImGuiContext& g = *GImGui;
g.CurrentWindow->DrawList->PopTextureID();
g.FontStack.pop_back();
SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
}
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (enabled)
window->DC.ItemFlags |= option;
else
window->DC.ItemFlags &= ~option;
window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
}
void ImGui::PopItemFlag()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemFlagsStack.pop_back();
window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back();
}
// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
{
PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
}
void ImGui::PopAllowKeyboardFocus()
{
PopItemFlag();
}
void ImGui::PushButtonRepeat(bool repeat)
{
PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
}
void ImGui::PopButtonRepeat()
{
PopItemFlag();
}
void ImGui::PushTextWrapPos(float wrap_pos_x)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.TextWrapPos = wrap_pos_x;
window->DC.TextWrapPosStack.push_back(wrap_pos_x);
}
void ImGui::PopTextWrapPos()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.TextWrapPosStack.pop_back();
window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
}
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
{
ImGuiContext& g = *GImGui;
ImGuiColorMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorModifiers.push_back(backup);
g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
}
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
{
ImGuiContext& g = *GImGui;
ImGuiColorMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorModifiers.push_back(backup);
g.Style.Colors[idx] = col;
}
void ImGui::PopStyleColor(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
ImGuiColorMod& backup = g.ColorModifiers.back();
g.Style.Colors[backup.Col] = backup.BackupValue;
g.ColorModifiers.pop_back();
count--;
}
}
struct ImGuiStyleVarInfo
{
ImGuiDataType Type;
ImU32 Count;
ImU32 Offset;
void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
};
static const ImGuiStyleVarInfo GStyleVarInfo[] =
{
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
};
static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
{
IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
return &GStyleVarInfo[idx];
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
{
ImGuiContext& g = *GImGui;
float* pvar = (float*)var_info->GetVarPtr(&g.Style);
g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
{
ImGuiContext& g = *GImGui;
ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
}
void ImGui::PopStyleVar(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
// We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
ImGuiStyleMod& backup = g.StyleModifiers.back();
const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
void* data = info->GetVarPtr(&g.Style);
if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
g.StyleModifiers.pop_back();
count--;
}
}
const char* ImGui::GetStyleColorName(ImGuiCol idx)
{
// Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
switch (idx)
{
case ImGuiCol_Text: return "Text";
case ImGuiCol_TextDisabled: return "TextDisabled";
case ImGuiCol_WindowBg: return "WindowBg";
case ImGuiCol_ChildBg: return "ChildBg";
case ImGuiCol_PopupBg: return "PopupBg";
case ImGuiCol_Border: return "Border";
case ImGuiCol_BorderShadow: return "BorderShadow";
case ImGuiCol_FrameBg: return "FrameBg";
case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
case ImGuiCol_FrameBgActive: return "FrameBgActive";
case ImGuiCol_TitleBg: return "TitleBg";
case ImGuiCol_TitleBgActive: return "TitleBgActive";
case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
case ImGuiCol_MenuBarBg: return "MenuBarBg";
case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
case ImGuiCol_CheckMark: return "CheckMark";
case ImGuiCol_SliderGrab: return "SliderGrab";
case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
case ImGuiCol_Button: return "Button";
case ImGuiCol_ButtonHovered: return "ButtonHovered";
case ImGuiCol_ButtonActive: return "ButtonActive";
case ImGuiCol_Header: return "Header";
case ImGuiCol_HeaderHovered: return "HeaderHovered";
case ImGuiCol_HeaderActive: return "HeaderActive";
case ImGuiCol_Separator: return "Separator";
case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
case ImGuiCol_SeparatorActive: return "SeparatorActive";
case ImGuiCol_ResizeGrip: return "ResizeGrip";
case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
case ImGuiCol_Tab: return "Tab";
case ImGuiCol_TabHovered: return "TabHovered";
case ImGuiCol_TabActive: return "TabActive";
case ImGuiCol_TabUnfocused: return "TabUnfocused";
case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
case ImGuiCol_PlotLines: return "PlotLines";
case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
case ImGuiCol_PlotHistogram: return "PlotHistogram";
case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
case ImGuiCol_DragDropTarget: return "DragDropTarget";
case ImGuiCol_NavHighlight: return "NavHighlight";
case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
}
IM_ASSERT(0);
return "Unknown";
}
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
{
if (window->RootWindow == potential_parent)
return true;
while (window != NULL)
{
if (window == potential_parent)
return true;
window = window->ParentWindow;
}
return false;
}
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
{
IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
ImGuiContext& g = *GImGui;
if (flags & ImGuiHoveredFlags_AnyWindow)
{
if (g.HoveredWindow == NULL)
return false;
}
else
{
switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
{
case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
if (g.HoveredRootWindow != g.CurrentWindow->RootWindow)
return false;
break;
case ImGuiHoveredFlags_RootWindow:
if (g.HoveredWindow != g.CurrentWindow->RootWindow)
return false;
break;
case ImGuiHoveredFlags_ChildWindows:
if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow))
return false;
break;
default:
if (g.HoveredWindow != g.CurrentWindow)
return false;
break;
}
}
if (!IsWindowContentHoverable(g.HoveredWindow, flags))
return false;
if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId)
return false;
return true;
}
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
{
ImGuiContext& g = *GImGui;
if (flags & ImGuiFocusedFlags_AnyWindow)
return g.NavWindow != NULL;
IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
{
case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_RootWindow:
return g.NavWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow);
default:
return g.NavWindow == g.CurrentWindow;
}
}
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmaticaly.
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
{
return window->Active && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
}
float ImGui::GetWindowWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Size.x;
}
float ImGui::GetWindowHeight()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Size.y;
}
ImVec2 ImGui::GetWindowPos()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
return window->Pos;
}
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
return;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
// Set
const ImVec2 old_pos = window->Pos;
window->Pos = ImFloor(pos);
ImVec2 offset = window->Pos - old_pos;
window->DC.CursorPos += offset; // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
window->DC.CursorStartPos += offset;
}
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
{
ImGuiWindow* window = GetCurrentWindowRead();
SetWindowPos(window, pos, cond);
}
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowPos(window, pos, cond);
}
ImVec2 ImGui::GetWindowSize()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Size;
}
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
return;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
if (size.x > 0.0f)
{
window->AutoFitFramesX = 0;
window->SizeFull.x = ImFloor(size.x);
}
else
{
window->AutoFitFramesX = 2;
window->AutoFitOnlyGrows = false;
}
if (size.y > 0.0f)
{
window->AutoFitFramesY = 0;
window->SizeFull.y = ImFloor(size.y);
}
else
{
window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = false;
}
}
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
{
SetWindowSize(GImGui->CurrentWindow, size, cond);
}
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowSize(window, size, cond);
}
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
return;
window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
window->Collapsed = collapsed;
}
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
{
SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
}
bool ImGui::IsWindowCollapsed()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Collapsed;
}
bool ImGui::IsWindowAppearing()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Appearing;
}
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowCollapsed(window, collapsed, cond);
}
void ImGui::SetWindowFocus()
{
FocusWindow(GImGui->CurrentWindow);
}
void ImGui::SetWindowFocus(const char* name)
{
if (name)
{
if (ImGuiWindow* window = FindWindowByName(name))
FocusWindow(window);
}
else
{
FocusWindow(NULL);
}
}
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
g.NextWindowData.PosVal = pos;
g.NextWindowData.PosPivotVal = pivot;
g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
g.NextWindowData.SizeVal = size;
g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
g.NextWindowData.SizeCallback = custom_callback;
g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
}
// Content size = inner scrollable rectangle, padded with WindowPadding.
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
void ImGui::SetNextWindowContentSize(const ImVec2& size)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
g.NextWindowData.ContentSizeVal = size;
}
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
g.NextWindowData.CollapsedVal = collapsed;
g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowFocus()
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
}
void ImGui::SetNextWindowBgAlpha(float alpha)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
g.NextWindowData.BgAlphaVal = alpha;
}
// FIXME: This is in window space (not screen space!). We should try to obsolete all those functions.
ImVec2 ImGui::GetContentRegionMax()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImVec2 mx = window->ContentsRegionRect.Max - window->Pos;
if (window->DC.CurrentColumns)
mx.x = window->WorkRect.Max.x - window->Pos.x;
return mx;
}
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
ImVec2 ImGui::GetContentRegionMaxAbs()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImVec2 mx = window->ContentsRegionRect.Max;
if (window->DC.CurrentColumns)
mx.x = window->WorkRect.Max.x;
return mx;
}
ImVec2 ImGui::GetContentRegionAvail()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return GetContentRegionMaxAbs() - window->DC.CursorPos;
}
// In window space (not screen space!)
ImVec2 ImGui::GetWindowContentRegionMin()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ContentsRegionRect.Min - window->Pos;
}
ImVec2 ImGui::GetWindowContentRegionMax()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ContentsRegionRect.Max - window->Pos;
}
float ImGui::GetWindowContentRegionWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ContentsRegionRect.GetWidth();
}
float ImGui::GetTextLineHeight()
{
ImGuiContext& g = *GImGui;
return g.FontSize;
}
float ImGui::GetTextLineHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.ItemSpacing.y;
}
float ImGui::GetFrameHeight()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.FramePadding.y * 2.0f;
}
float ImGui::GetFrameHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
}
ImDrawList* ImGui::GetWindowDrawList()
{
ImGuiWindow* window = GetCurrentWindow();
return window->DrawList;
}
ImFont* ImGui::GetFont()
{
return GImGui->Font;
}
float ImGui::GetFontSize()
{
return GImGui->FontSize;
}
ImVec2 ImGui::GetFontTexUvWhitePixel()
{
return GImGui->DrawListSharedData.TexUvWhitePixel;
}
void ImGui::SetWindowFontScale(float scale)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->FontWindowScale = scale;
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
ImVec2 ImGui::GetCursorPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos - window->Pos + window->Scroll;
}
float ImGui::GetCursorPosX()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
}
float ImGui::GetCursorPosY()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
}
void ImGui::SetCursorPos(const ImVec2& local_pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
void ImGui::SetCursorPosX(float x)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
}
void ImGui::SetCursorPosY(float y)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
}
ImVec2 ImGui::GetCursorStartPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorStartPos - window->Pos;
}
ImVec2 ImGui::GetCursorScreenPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos;
}
void ImGui::SetCursorScreenPos(const ImVec2& pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos = pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
void ImGui::ActivateItem(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.NavNextActivateId = id;
}
void ImGui::SetKeyboardFocusHere(int offset)
{
IM_ASSERT(offset >= -1); // -1 is allowed but not below
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
g.FocusRequestNextWindow = window;
g.FocusRequestNextCounterAll = window->DC.FocusCounterAll + 1 + offset;
g.FocusRequestNextCounterTab = INT_MAX;
}
void ImGui::SetItemDefaultFocus()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!window->Appearing)
return;
if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent)
{
g.NavInitRequest = false;
g.NavInitResultId = g.NavWindow->DC.LastItemId;
g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos);
NavUpdateAnyRequestFlag();
if (!IsItemVisible())
SetScrollHereY();
}
}
void ImGui::SetStateStorage(ImGuiStorage* tree)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->DC.StateStorage = tree ? tree : &window->StateStorage;
}
ImGuiStorage* ImGui::GetStateStorage()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->DC.StateStorage;
}
void ImGui::PushID(const char* str_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(str_id));
}
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(str_id_begin, str_id_end));
}
void ImGui::PushID(const void* ptr_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id));
}
void ImGui::PushID(int int_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(int_id));
}
// Push a given id value ignoring the ID stack as a seed.
void ImGui::PushOverrideID(ImGuiID id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(id);
}
void ImGui::PopID()
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.pop_back();
}
ImGuiID ImGui::GetID(const char* str_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(str_id);
}
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(str_id_begin, str_id_end);
}
ImGuiID ImGui::GetID(const void* ptr_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(ptr_id);
}
bool ImGui::IsRectVisible(const ImVec2& size)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
}
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
}
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
void ImGui::BeginGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1);
ImGuiGroupData& group_data = window->DC.GroupStack.back();
group_data.BackupCursorPos = window->DC.CursorPos;
group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
group_data.BackupIndent = window->DC.Indent;
group_data.BackupGroupOffset = window->DC.GroupOffset;
group_data.BackupCurrLineSize = window->DC.CurrLineSize;
group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
group_data.EmitItem = true;
window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
window->DC.Indent = window->DC.GroupOffset;
window->DC.CursorMaxPos = window->DC.CursorPos;
window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
if (g.LogEnabled)
g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return
}
void ImGui::EndGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
ImGuiGroupData& group_data = window->DC.GroupStack.back();
ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
window->DC.CursorPos = group_data.BackupCursorPos;
window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
window->DC.Indent = group_data.BackupIndent;
window->DC.GroupOffset = group_data.BackupGroupOffset;
window->DC.CurrLineSize = group_data.BackupCurrLineSize;
window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
if (g.LogEnabled)
g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return
if (!group_data.EmitItem)
{
window->DC.GroupStack.pop_back();
return;
}
window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
ItemSize(group_bb.GetSize(), 0.0f);
ItemAdd(group_bb, 0);
// If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
// It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
// Also if you grep for LastItemId you'll notice it is only used in that context.
// (The tests not symmetrical because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
const bool group_contains_prev_active_id = !group_data.BackupActiveIdPreviousFrameIsAlive && g.ActiveIdPreviousFrameIsAlive;
if (group_contains_curr_active_id)
window->DC.LastItemId = g.ActiveId;
else if (group_contains_prev_active_id)
window->DC.LastItemId = g.ActiveIdPreviousFrame;
window->DC.LastItemRect = group_bb;
// Forward Edited flag
if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
// Forward Deactivated flag
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Deactivated;
window->DC.GroupStack.pop_back();
//window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
}
// Gets back to previous line and continue with horizontal layout
// offset_from_start_x == 0 : follow right after previous item
// offset_from_start_x != 0 : align to specified x position (relative to window/group left)
// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
// spacing_w >= 0 : enforce spacing amount
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
if (offset_from_start_x != 0.0f)
{
if (spacing_w < 0.0f) spacing_w = 0.0f;
window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
else
{
if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
window->DC.CurrLineSize = window->DC.PrevLineSize;
window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
}
void ImGui::Indent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
void ImGui::Unindent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
//-----------------------------------------------------------------------------
// [SECTION] SCROLLING
//-----------------------------------------------------------------------------
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges)
{
ImGuiContext& g = *GImGui;
ImVec2 scroll = window->Scroll;
if (window->ScrollTarget.x < FLT_MAX)
{
float cr_x = window->ScrollTargetCenterRatio.x;
float target_x = window->ScrollTarget.x;
if (snap_on_edges && cr_x <= 0.0f && target_x <= window->WindowPadding.x)
target_x = 0.0f;
else if (snap_on_edges && cr_x >= 1.0f && target_x >= window->ContentSize.x + window->WindowPadding.x + g.Style.ItemSpacing.x)
target_x = window->ContentSize.x + window->WindowPadding.x * 2.0f;
scroll.x = target_x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
}
if (window->ScrollTarget.y < FLT_MAX)
{
// 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding.
float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
float cr_y = window->ScrollTargetCenterRatio.y;
float target_y = window->ScrollTarget.y;
if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y)
target_y = 0.0f;
if (snap_on_edges && cr_y >= 1.0f && target_y >= window->ContentSize.y + window->WindowPadding.y + g.Style.ItemSpacing.y)
target_y = window->ContentSize.y + window->WindowPadding.y * 2.0f;
scroll.y = target_y - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y - decoration_up_height);
}
scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
if (!window->Collapsed && !window->SkipItems)
{
scroll.x = ImMin(scroll.x, window->ScrollMax.x);
scroll.y = ImMin(scroll.y, window->ScrollMax.y);
}
return scroll;
}
// Scroll to keep newly navigated item fully into view
ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect)
{
ImGuiContext& g = *GImGui;
ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
//GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
ImVec2 delta_scroll;
if (!window_rect.Contains(item_rect))
{
if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x)
SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x + g.Style.ItemSpacing.x, 0.0f);
else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x)
SetScrollFromPosX(window, item_rect.Max.x - window->Pos.x + g.Style.ItemSpacing.x, 1.0f);
if (item_rect.Min.y < window_rect.Min.y)
SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y - g.Style.ItemSpacing.y, 0.0f);
else if (item_rect.Max.y >= window_rect.Max.y)
SetScrollFromPosY(window, item_rect.Max.y - window->Pos.y + g.Style.ItemSpacing.y, 1.0f);
ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window, false);
delta_scroll = next_scroll - window->Scroll;
}
// Also scroll parent window to keep us into view if necessary
if (window->Flags & ImGuiWindowFlags_ChildWindow)
delta_scroll += ScrollToBringRectIntoView(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll));
return delta_scroll;
}
float ImGui::GetScrollX()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Scroll.x;
}
float ImGui::GetScrollY()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Scroll.y;
}
float ImGui::GetScrollMaxX()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ScrollMax.x;
}
float ImGui::GetScrollMaxY()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ScrollMax.y;
}
void ImGui::SetScrollX(float scroll_x)
{
ImGuiWindow* window = GetCurrentWindow();
window->ScrollTarget.x = scroll_x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
void ImGui::SetScrollY(float scroll_y)
{
ImGuiWindow* window = GetCurrentWindow();
window->ScrollTarget.y = scroll_y;
window->ScrollTargetCenterRatio.y = 0.0f;
}
void ImGui::SetScrollX(ImGuiWindow* window, float new_scroll_x)
{
window->ScrollTarget.x = new_scroll_x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
void ImGui::SetScrollY(ImGuiWindow* window, float new_scroll_y)
{
window->ScrollTarget.y = new_scroll_y;
window->ScrollTargetCenterRatio.y = 0.0f;
}
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
{
// We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
window->ScrollTarget.x = (float)(int)(local_x + window->Scroll.x);
window->ScrollTargetCenterRatio.x = center_x_ratio;
}
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
{
// We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
local_y -= decoration_up_height;
window->ScrollTarget.y = (float)(int)(local_y + window->Scroll.y);
window->ScrollTargetCenterRatio.y = center_y_ratio;
}
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
{
ImGuiContext& g = *GImGui;
SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
}
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
{
ImGuiContext& g = *GImGui;
SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
}
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
void ImGui::SetScrollHereX(float center_x_ratio)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float target_x = window->DC.LastItemRect.Min.x - window->Pos.x; // Left of last item, in window space
float last_item_width = window->DC.LastItemRect.GetWidth();
target_x += (last_item_width * center_x_ratio) + (g.Style.ItemSpacing.x * (center_x_ratio - 0.5f) * 2.0f); // Precisely aim before, in the middle or after the last item.
SetScrollFromPosX(target_x, center_x_ratio);
}
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
void ImGui::SetScrollHereY(float center_y_ratio)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (g.Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
SetScrollFromPosY(target_y, center_y_ratio);
}
//-----------------------------------------------------------------------------
// [SECTION] TOOLTIPS
//-----------------------------------------------------------------------------
void ImGui::BeginTooltip()
{
ImGuiContext& g = *GImGui;
if (g.DragDropWithinSourceOrTarget)
{
// The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
// In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
// Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
//ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
SetNextWindowPos(tooltip_pos);
SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
//PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
BeginTooltipEx(0, true);
}
else
{
BeginTooltipEx(0, false);
}
}
// Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first.
void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip)
{
ImGuiContext& g = *GImGui;
char window_name[16];
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
if (override_previous_tooltip)
if (ImGuiWindow* window = FindWindowByName(window_name))
if (window->Active)
{
// Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
window->Hidden = true;
window->HiddenFramesCanSkipItems = 1;
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
}
ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
Begin(window_name, NULL, flags | extra_flags);
}
void ImGui::EndTooltip()
{
IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
End();
}
void ImGui::SetTooltipV(const char* fmt, va_list args)
{
ImGuiContext& g = *GImGui;
if (g.DragDropWithinSourceOrTarget)
BeginTooltip();
else
BeginTooltipEx(0, true);
TextV(fmt, args);
EndTooltip();
}
void ImGui::SetTooltip(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
SetTooltipV(fmt, args);
va_end(args);
}
//-----------------------------------------------------------------------------
// [SECTION] POPUPS
//-----------------------------------------------------------------------------
bool ImGui::IsPopupOpen(ImGuiID id)
{
ImGuiContext& g = *GImGui;
return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
}
bool ImGui::IsPopupOpen(const char* str_id)
{
ImGuiContext& g = *GImGui;
return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
}
ImGuiWindow* ImGui::GetTopMostPopupModal()
{
ImGuiContext& g = *GImGui;
for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
if (popup->Flags & ImGuiWindowFlags_Modal)
return popup;
return NULL;
}
void ImGui::OpenPopup(const char* str_id)
{
ImGuiContext& g = *GImGui;
OpenPopupEx(g.CurrentWindow->GetID(str_id));
}
// Mark popup as open (toggle toward open state).
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
void ImGui::OpenPopupEx(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
int current_stack_size = g.BeginPopupStack.Size;
ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
popup_ref.PopupId = id;
popup_ref.Window = NULL;
popup_ref.SourceWindow = g.NavWindow;
popup_ref.OpenFrameCount = g.FrameCount;
popup_ref.OpenParentId = parent_window->IDStack.back();
popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
//IMGUI_DEBUG_LOG("OpenPopupEx(0x%08X)\n", g.FrameCount, id);
if (g.OpenPopupStack.Size < current_stack_size + 1)
{
g.OpenPopupStack.push_back(popup_ref);
}
else
{
// Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
// would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
// situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
{
g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
}
else
{
// Close child popups if any, then flag popup for open/reopen
g.OpenPopupStack.resize(current_stack_size + 1);
g.OpenPopupStack[current_stack_size] = popup_ref;
}
// When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
// This is equivalent to what ClosePopupToLevel() does.
//if (g.OpenPopupStack[current_stack_size].PopupId == id)
// FocusWindow(parent_window);
}
}
bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
{
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
OpenPopupEx(id);
return true;
}
return false;
}
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.empty())
return;
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
// Don't close our own child popup windows.
int popup_count_to_keep = 0;
if (ref_window)
{
// Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
{
ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
if (!popup.Window)
continue;
IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
continue;
// Trim the stack when popups are not direct descendant of the reference window (the reference window is often the NavWindow)
bool popup_or_descendent_is_ref_window = false;
for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_is_ref_window; m++)
if (ImGuiWindow* popup_window = g.OpenPopupStack[m].Window)
if (popup_window->RootWindow == ref_window->RootWindow)
popup_or_descendent_is_ref_window = true;
if (!popup_or_descendent_is_ref_window)
break;
}
}
if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
{
//IMGUI_DEBUG_LOG("ClosePopupsOverWindow(%s) -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep);
ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
}
}
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow;
ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
g.OpenPopupStack.resize(remaining);
if (restore_focus_to_window_under_popup)
{
if (focus_window && !focus_window->WasActive && popup_window)
{
// Fallback
FocusTopMostWindowUnderOne(popup_window, NULL);
}
else
{
if (g.NavLayer == 0 && focus_window)
focus_window = NavRestoreLastChildNavWindow(focus_window);
FocusWindow(focus_window);
}
}
}
// Close the popup we have begin-ed into.
void ImGui::CloseCurrentPopup()
{
ImGuiContext& g = *GImGui;
int popup_idx = g.BeginPopupStack.Size - 1;
if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
return;
// Closing a menu closes its top-most parent popup (unless a modal)
while (popup_idx > 0)
{
ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
bool close_parent = false;
if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
if (parent_popup_window == NULL || !(parent_popup_window->Flags & ImGuiWindowFlags_Modal))
close_parent = true;
if (!close_parent)
break;
popup_idx--;
}
//IMGUI_DEBUG_LOG("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
ClosePopupToLevel(popup_idx, true);
// A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
// To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
// Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
if (ImGuiWindow* window = g.NavWindow)
window->DC.NavHideHighlightOneFrame = true;
}
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
if (!IsPopupOpen(id))
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
char name[20];
if (extra_flags & ImGuiWindowFlags_ChildMenu)
ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth
else
ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup);
if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
EndPopup();
return is_open;
}
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags);
}
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiID id = window->GetID(name);
if (!IsPopupOpen(id))
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
// Center modal windows by default
// FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings;
const bool is_open = Begin(name, p_open, flags);
if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
{
EndPopup();
if (is_open)
ClosePopupToLevel(g.BeginPopupStack.Size, true);
return false;
}
return is_open;
}
void ImGui::EndPopup()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.CurrentWindow->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
IM_ASSERT(g.BeginPopupStack.Size > 0);
// Make all menus and popups wrap around for now, may need to expose that policy.
NavMoveRequestTryWrapping(g.CurrentWindow, ImGuiNavMoveFlags_LoopY);
End();
}
// This is a helper to handle the simplest case of associating one named popup to one given widget.
// You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
// You can pass a NULL str_id to use the identifier of the last item.
bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (window->SkipItems)
return false;
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool also_over_items)
{
if (!str_id)
str_id = "window_context";
ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
if (also_over_items || !IsAnyItemHovered())
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
{
if (!str_id)
str_id = "void_context";
ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
{
ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
//GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
//GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
// Combo Box policy (we want a connecting edge)
if (policy == ImGuiPopupPositionPolicy_ComboBox)
{
const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
continue;
ImVec2 pos;
if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
if (!r_outer.Contains(ImRect(pos, pos + size)))
continue;
*last_dir = dir;
return pos;
}
}
// Default popup policy
const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
continue;
float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
if (avail_w < size.x || avail_h < size.y)
continue;
ImVec2 pos;
pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
*last_dir = dir;
return pos;
}
// Fallback, try to keep within display
*last_dir = ImGuiDir_None;
ImVec2 pos = ref_pos;
pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
return pos;
}
ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow* window)
{
IM_UNUSED(window);
ImVec2 padding = GImGui->Style.DisplaySafeAreaPadding;
ImRect r_screen = GetViewportRect();
r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
return r_screen;
}
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImRect r_outer = GetWindowAllowedExtentRect(window);
if (window->Flags & ImGuiWindowFlags_ChildMenu)
{
// Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
// This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
IM_ASSERT(g.CurrentWindow == window);
ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2];
float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
ImRect r_avoid;
if (parent_window->DC.MenuBarAppending)
r_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight());
else
r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
}
if (window->Flags & ImGuiWindowFlags_Popup)
{
ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1);
return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
}
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Position tooltip (always follows mouse)
float sc = g.Style.MouseCursorScale;
ImVec2 ref_pos = NavCalcPreferredRefPos();
ImRect r_avoid;
if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
else
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
ImVec2 pos = FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
if (window->AutoPosLastDirection == ImGuiDir_None)
pos = ref_pos + ImVec2(2, 2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
return pos;
}
IM_ASSERT(0);
return window->Pos;
}
//-----------------------------------------------------------------------------
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
//-----------------------------------------------------------------------------
ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
{
if (ImFabs(dx) > ImFabs(dy))
return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
}
static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
{
if (a1 < b0)
return a1 - b0;
if (b1 < a0)
return a0 - b1;
return 0.0f;
}
static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
{
if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
{
r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
}
else
{
r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
}
}
// Scoring function for directional navigation. Based on https://gist.github.com/rygorous/6981057
static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavLayer != window->DC.NavLayerCurrent)
return false;
const ImRect& curr = g.NavScoringRectScreen; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
g.NavScoringCount++;
// When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
if (window->ParentWindow == g.NavWindow)
{
IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
if (!window->ClipRect.Overlaps(cand))
return false;
cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
}
// We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
// For example, this ensure that items in one column are not reached when moving vertically from items in another column.
NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
// Compute distance between boxes
// FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
if (dby != 0.0f && dbx != 0.0f)
dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
float dist_box = ImFabs(dbx) + ImFabs(dby);
// Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
// Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
ImGuiDir quadrant;
float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
if (dbx != 0.0f || dby != 0.0f)
{
// For non-overlapping boxes, use distance between boxes
dax = dbx;
day = dby;
dist_axial = dist_box;
quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
}
else if (dcx != 0.0f || dcy != 0.0f)
{
// For overlapping boxes with different centers, use distance between centers
dax = dcx;
day = dcy;
dist_axial = dist_center;
quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
}
else
{
// Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
}
#if IMGUI_DEBUG_NAV_SCORING
char buf[128];
if (ImGui::IsMouseHoveringRect(cand.Min, cand.Max))
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
ImDrawList* draw_list = ImGui::GetForegroundDrawList(window);
draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
draw_list->AddRectFilled(cand.Max-ImVec2(4,4), cand.Max+ImGui::CalcTextSize(buf)+ImVec2(4,4), IM_COL32(40,0,0,150));
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf);
}
else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
{
if (ImGui::IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; }
if (quadrant == g.NavMoveDir)
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
ImDrawList* draw_list = ImGui::GetForegroundDrawList(window);
draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf);
}
}
#endif
// Is it in the quadrant we're interesting in moving to?
bool new_best = false;
if (quadrant == g.NavMoveDir)
{
// Does it beat the current best candidate?
if (dist_box < result->DistBox)
{
result->DistBox = dist_box;
result->DistCenter = dist_center;
return true;
}
if (dist_box == result->DistBox)
{
// Try using distance between center points to break ties
if (dist_center < result->DistCenter)
{
result->DistCenter = dist_center;
new_best = true;
}
else if (dist_center == result->DistCenter)
{
// Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
// (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
// this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
new_best = true;
}
}
}
// Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
// are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
// This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
// 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
// Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
if (g.NavLayer == 1 && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
if ((g.NavMoveDir == ImGuiDir_Left && dax < 0.0f) || (g.NavMoveDir == ImGuiDir_Right && dax > 0.0f) || (g.NavMoveDir == ImGuiDir_Up && day < 0.0f) || (g.NavMoveDir == ImGuiDir_Down && day > 0.0f))
{
result->DistAxial = dist_axial;
new_best = true;
}
return new_best;
}
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id)
{
ImGuiContext& g = *GImGui;
//if (!g.IO.NavActive) // [2017/10/06] Removed this possibly redundant test but I am not sure of all the side-effects yet. Some of the feature here will need to work regardless of using a _NoNavInputs flag.
// return;
const ImGuiItemFlags item_flags = window->DC.ItemFlags;
const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos);
// Process Init Request
if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent)
{
// Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0)
{
g.NavInitResultId = id;
g.NavInitResultRectRel = nav_bb_rel;
}
if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus))
{
g.NavInitRequest = false; // Found a match, clear request
NavUpdateAnyRequestFlag();
}
}
// Process Move Request (scoring for navigation)
// FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy)
if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled|ImGuiItemFlags_NoNav)))
{
ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
#if IMGUI_DEBUG_NAV_SCORING
// [DEBUG] Score all items in NavWindow at all times
if (!g.NavMoveRequest)
g.NavMoveDir = g.NavMoveDirLast;
bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest;
#else
bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb);
#endif
if (new_best)
{
result->ID = id;
result->SelectScopeId = g.MultiSelectScopeId;
result->Window = window;
result->RectRel = nav_bb_rel;
}
const float VISIBLE_RATIO = 0.70f;
if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb))
{
result = &g.NavMoveResultLocalVisibleSet;
result->ID = id;
result->SelectScopeId = g.MultiSelectScopeId;
result->Window = window;
result->RectRel = nav_bb_rel;
}
}
// Update window-relative bounding box of navigated item
if (g.NavId == id)
{
g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
g.NavLayer = window->DC.NavLayerCurrent;
g.NavIdIsAlive = true;
g.NavIdTabCounter = window->DC.FocusCounterTab;
window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position)
}
}
bool ImGui::NavMoveRequestButNoResultYet()
{
ImGuiContext& g = *GImGui;
return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
}
void ImGui::NavMoveRequestCancel()
{
ImGuiContext& g = *GImGui;
g.NavMoveRequest = false;
NavUpdateAnyRequestFlag();
}
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_None);
ImGui::NavMoveRequestCancel();
g.NavMoveDir = move_dir;
g.NavMoveClipDir = clip_dir;
g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
g.NavMoveRequestFlags = move_flags;
g.NavWindow->NavRectRel[g.NavLayer] = bb_rel;
}
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags)
{
ImGuiContext& g = *GImGui;
if (g.NavWindow != window || !NavMoveRequestButNoResultYet() || g.NavMoveRequestForward != ImGuiNavForward_None || g.NavLayer != 0)
return;
IM_ASSERT(move_flags != 0); // No points calling this with no wrapping
ImRect bb_rel = window->NavRectRel[0];
ImGuiDir clip_dir = g.NavMoveDir;
if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
{
bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->ContentSize.x + window->WindowPadding.x * 2.0f) - window->Scroll.x;
if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); clip_dir = ImGuiDir_Up; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
{
bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x;
if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(+bb_rel.GetHeight()); clip_dir = ImGuiDir_Down; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
{
bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->ContentSize.y + window->WindowPadding.y * 2.0f) - window->Scroll.y;
if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); clip_dir = ImGuiDir_Left; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
{
bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y;
if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(+bb_rel.GetWidth()); clip_dir = ImGuiDir_Right; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
}
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
// This way we could find the last focused window among our children. It would be much less confusing this way?
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
{
ImGuiWindow* parent_window = nav_window;
while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
parent_window = parent_window->ParentWindow;
if (parent_window && parent_window != nav_window)
parent_window->NavLastChildNavWindow = nav_window;
}
// Restore the last focused child.
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
{
return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window;
}
static void NavRestoreLayer(ImGuiNavLayer layer)
{
ImGuiContext& g = *GImGui;
g.NavLayer = layer;
if (layer == 0)
g.NavWindow = ImGui::NavRestoreLastChildNavWindow(g.NavWindow);
if (layer == 0 && g.NavWindow->NavLastIds[0] != 0)
ImGui::SetNavIDWithRectRel(g.NavWindow->NavLastIds[0], layer, g.NavWindow->NavRectRel[0]);
else
ImGui::NavInitWindow(g.NavWindow, true);
}
static inline void ImGui::NavUpdateAnyRequestFlag()
{
ImGuiContext& g = *GImGui;
g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
if (g.NavAnyRequest)
IM_ASSERT(g.NavWindow != NULL);
}
// This needs to be called before we submit any widget (aka in or before Begin)
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(window == g.NavWindow);
bool init_for_nav = false;
if (!(window->Flags & ImGuiWindowFlags_NoNavInputs))
if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
init_for_nav = true;
if (init_for_nav)
{
SetNavID(0, g.NavLayer);
g.NavInitRequest = true;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavInitResultRectRel = ImRect();
NavUpdateAnyRequestFlag();
}
else
{
g.NavId = window->NavLastIds[0];
}
}
static ImVec2 ImGui::NavCalcPreferredRefPos()
{
ImGuiContext& g = *GImGui;
if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow)
{
// Mouse (we need a fallback in case the mouse becomes invalid after being used)
if (IsMousePosValid(&g.IO.MousePos))
return g.IO.MousePos;
return g.LastValidMousePos;
}
else
{
// When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item.
const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer];
ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
ImRect visible_rect = GetViewportRect();
return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta.
}
}
float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
{
ImGuiContext& g = *GImGui;
if (mode == ImGuiInputReadMode_Down)
return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user)
const float t = g.IO.NavInputsDownDuration[n];
if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input.
return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f);
if (t < 0.0f)
return 0.0f;
if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input.
return (t == 0.0f) ? 1.0f : 0.0f;
if (mode == ImGuiInputReadMode_Repeat)
return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.80f);
if (mode == ImGuiInputReadMode_RepeatSlow)
return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 1.00f, g.IO.KeyRepeatRate * 2.00f);
if (mode == ImGuiInputReadMode_RepeatFast)
return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.30f);
return 0.0f;
}
ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor)
{
ImVec2 delta(0.0f, 0.0f);
if (dir_sources & ImGuiNavDirSourceFlags_Keyboard)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode));
if (dir_sources & ImGuiNavDirSourceFlags_PadDPad)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode));
if (dir_sources & ImGuiNavDirSourceFlags_PadLStick)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode));
if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow))
delta *= slow_factor;
if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast))
delta *= fast_factor;
return delta;
}
static void ImGui::NavUpdate()
{
ImGuiContext& g = *GImGui;
g.IO.WantSetMousePos = false;
#if 0
if (g.NavScoringCount > 0) IMGUI_DEBUG_LOG("NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
#endif
// Set input source as Gamepad when buttons are pressed before we map Keyboard (some features differs when used with Gamepad vs Keyboard)
bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
if (nav_gamepad_active)
if (g.IO.NavInputs[ImGuiNavInput_Activate] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Input] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Cancel] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Menu] > 0.0f)
g.NavInputSource = ImGuiInputSource_NavGamepad;
// Update Keyboard->Nav inputs mapping
if (nav_keyboard_active)
{
#define NAV_MAP_KEY(_KEY, _NAV_INPUT) do { if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } } while (0)
NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate );
NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input );
NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel );
NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ );
NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ );
NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
NAV_MAP_KEY(ImGuiKey_Tab, ImGuiNavInput_KeyTab_ );
if (g.IO.KeyCtrl)
g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
if (g.IO.KeyShift)
g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
if (g.IO.KeyAlt && !g.IO.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu.
g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
#undef NAV_MAP_KEY
}
memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration));
for (int i = 0; i < IM_ARRAYSIZE(g.IO.NavInputs); i++)
g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f;
// Process navigation init request (select first/default focus)
// In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove) && g.NavWindow)
{
// Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
if (g.NavInitRequestFromMove)
SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, g.NavInitResultRectRel);
else
SetNavID(g.NavInitResultId, g.NavLayer);
g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel;
}
g.NavInitRequest = false;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavJustMovedToId = 0;
// Process navigation move request
if (g.NavMoveRequest)
NavUpdateMoveResult();
// When a forwarded move request failed, we restore the highlight that we disabled during the forward frame
if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive)
{
IM_ASSERT(g.NavMoveRequest);
if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
g.NavDisableHighlight = false;
g.NavMoveRequestForward = ImGuiNavForward_None;
}
// Apply application mouse position movement, after we had a chance to process move request result.
if (g.NavMousePosDirty && g.NavIdIsAlive)
{
// Set mouse position given our knowledge of the navigated item position from last frame
if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (g.IO.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
{
if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
{
g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredRefPos();
g.IO.WantSetMousePos = true;
}
}
g.NavMousePosDirty = false;
}
g.NavIdIsAlive = false;
g.NavJustTabbedId = 0;
IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1);
// Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0
if (g.NavWindow)
NavSaveLastChildNavWindowIntoParent(g.NavWindow);
if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0)
g.NavWindow->NavLastChildNavWindow = NULL;
// Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
NavUpdateWindowing();
// Set output flags for user application
g.IO.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
// Process NavCancel input (to close a popup, get back to parent, clear focus)
if (IsNavInputPressed(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
{
if (g.ActiveId != 0)
{
if (!(g.ActiveIdBlockNavInputFlags & (1 << ImGuiNavInput_Cancel)))
ClearActiveID();
}
else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
{
// Exit child window
ImGuiWindow* child_window = g.NavWindow;
ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
IM_ASSERT(child_window->ChildId != 0);
FocusWindow(parent_window);
SetNavID(child_window->ChildId, 0);
g.NavIdIsAlive = false;
if (g.NavDisableMouseHover)
g.NavMousePosDirty = true;
}
else if (g.OpenPopupStack.Size > 0)
{
// Close open popup/menu
if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
}
else if (g.NavLayer != 0)
{
// Leave the "menu" layer
NavRestoreLayer(ImGuiNavLayer_Main);
}
else
{
// Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
g.NavWindow->NavLastIds[0] = 0;
g.NavId = 0;
}
}
// Process manual activation request
g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0;
if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
bool activate_pressed = activate_down && IsNavInputPressed(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
if (g.ActiveId == 0 && activate_pressed)
g.NavActivateId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
g.NavActivateDownId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
g.NavActivatePressedId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputPressed(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
g.NavInputId = g.NavId;
}
if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
g.NavDisableHighlight = true;
if (g.NavActivateId != 0)
IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
g.NavMoveRequest = false;
// Process programmatic activation request
if (g.NavNextActivateId != 0)
g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId;
g.NavNextActivateId = 0;
// Initiate directional inputs request
const int allowed_dir_flags = (g.ActiveId == 0) ? ~0 : g.ActiveIdAllowNavDirFlags;
if (g.NavMoveRequestForward == ImGuiNavForward_None)
{
g.NavMoveDir = ImGuiDir_None;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_None;
if (g.NavWindow && !g.NavWindowingTarget && allowed_dir_flags && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
if ((allowed_dir_flags & (1<<ImGuiDir_Left)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadLeft, ImGuiNavInput_KeyLeft_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Left;
if ((allowed_dir_flags & (1<<ImGuiDir_Right)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadRight,ImGuiNavInput_KeyRight_,ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Right;
if ((allowed_dir_flags & (1<<ImGuiDir_Up)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadUp, ImGuiNavInput_KeyUp_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Up;
if ((allowed_dir_flags & (1<<ImGuiDir_Down)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadDown, ImGuiNavInput_KeyDown_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Down;
}
g.NavMoveClipDir = g.NavMoveDir;
}
else
{
// Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
// (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function)
IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued);
g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
}
// Update PageUp/PageDown scroll
float nav_scoring_rect_offset_y = 0.0f;
if (nav_keyboard_active)
nav_scoring_rect_offset_y = NavUpdatePageUpPageDown(allowed_dir_flags);
// If we initiate a movement request and have no current NavId, we initiate a InitDefautRequest that will be used as a fallback if the direction fails to find a match
if (g.NavMoveDir != ImGuiDir_None)
{
g.NavMoveRequest = true;
g.NavMoveDirLast = g.NavMoveDir;
}
if (g.NavMoveRequest && g.NavId == 0)
{
g.NavInitRequest = g.NavInitRequestFromMove = true;
g.NavInitResultId = 0;
g.NavDisableHighlight = false;
}
NavUpdateAnyRequestFlag();
// Scrolling
if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
{
// *Fallback* manual-scroll with Nav directional keys when window has no navigable item
ImGuiWindow* window = g.NavWindow;
const float scroll_speed = ImFloor(window->CalcFontSize() * 100 * g.IO.DeltaTime + 0.5f); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest)
{
if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
SetScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down)
SetScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
}
// *Normal* Manual scroll with NavScrollXXX keys
// Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f);
if (scroll_dir.x != 0.0f && window->ScrollbarX)
{
SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
g.NavMoveFromClampedRefRect = true;
}
if (scroll_dir.y != 0.0f)
{
SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
g.NavMoveFromClampedRefRect = true;
}
}
// Reset search results
g.NavMoveResultLocal.Clear();
g.NavMoveResultLocalVisibleSet.Clear();
g.NavMoveResultOther.Clear();
// When we have manually scrolled (without using navigation) and NavId becomes out of bounds, we project its bounding box to the visible area to restart navigation within visible items
if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0)
{
ImGuiWindow* window = g.NavWindow;
ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1,1), window->InnerRect.Max - window->Pos + ImVec2(1,1));
if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
{
float pad = window->CalcFontSize() * 0.5f;
window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item
window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel);
g.NavId = 0;
}
g.NavMoveFromClampedRefRect = false;
}
// For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0);
g.NavScoringRectScreen = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect();
g.NavScoringRectScreen.TranslateY(nav_scoring_rect_offset_y);
g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x);
g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x;
IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().
//GetForegroundDrawList()->AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG]
g.NavScoringCount = 0;
#if IMGUI_DEBUG_NAV_RECTS
if (g.NavWindow)
{
ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
if (1) { for (int layer = 0; layer < 2; layer++) draw_list->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG]
if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
}
#endif
}
// Apply result from previous frame navigation directional move request
static void ImGui::NavUpdateMoveResult()
{
ImGuiContext& g = *GImGui;
if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
{
// In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
if (g.NavId != 0)
{
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
}
return;
}
// Select which result to use
ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
// PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
if (g.NavMoveResultLocalVisibleSet.ID != 0 && g.NavMoveResultLocalVisibleSet.ID != g.NavId)
result = &g.NavMoveResultLocalVisibleSet;
// Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
result = &g.NavMoveResultOther;
IM_ASSERT(g.NavWindow && result->Window);
// Scroll to keep newly navigated item fully into view.
if (g.NavLayer == 0)
{
ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos);
ImVec2 delta_scroll = ScrollToBringRectIntoView(result->Window, rect_abs);
// Offset our result position so mouse position can be applied immediately after in NavUpdate()
result->RectRel.TranslateX(-delta_scroll.x);
result->RectRel.TranslateY(-delta_scroll.y);
}
ClearActiveID();
g.NavWindow = result->Window;
if (g.NavId != result->ID)
{
// Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
g.NavJustMovedToId = result->ID;
g.NavJustMovedToMultiSelectScopeId = result->SelectScopeId;
}
SetNavIDWithRectRel(result->ID, g.NavLayer, result->RectRel);
g.NavMoveFromClampedRefRect = false;
}
static float ImGui::NavUpdatePageUpPageDown(int allowed_dir_flags)
{
ImGuiContext& g = *GImGui;
if (g.NavMoveDir != ImGuiDir_None || g.NavWindow == NULL)
return 0.0f;
if ((g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL || g.NavLayer != 0)
return 0.0f;
ImGuiWindow* window = g.NavWindow;
bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && (allowed_dir_flags & (1 << ImGuiDir_Up));
bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && (allowed_dir_flags & (1 << ImGuiDir_Down));
if (page_up_held != page_down_held) // If either (not both) are pressed
{
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll)
{
// Fallback manual-scroll when window has no navigable item
if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
}
else
{
const ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
float nav_scoring_rect_offset_y = 0.0f;
if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
{
nav_scoring_rect_offset_y = -page_offset_y;
g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item)
g.NavMoveClipDir = ImGuiDir_Up;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
{
nav_scoring_rect_offset_y = +page_offset_y;
g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item)
g.NavMoveClipDir = ImGuiDir_Down;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
return nav_scoring_rect_offset_y;
}
}
return 0.0f;
}
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = g.WindowsFocusOrder.Size-1; i >= 0; i--)
if (g.WindowsFocusOrder[i] == window)
return i;
return -1;
}
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
return g.WindowsFocusOrder[i];
return NULL;
}
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindowingTarget);
if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
return;
const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
if (!window_target)
window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
if (window_target) // Don't reset windowing target if there's a single window in the list
g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
g.NavWindowingToggleLayer = false;
}
// Windowing management mode
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
static void ImGui::NavUpdateWindowing()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* apply_focus_window = NULL;
bool apply_toggle_layer = false;
ImGuiWindow* modal_window = GetTopMostPopupModal();
if (modal_window != NULL)
{
g.NavWindowingTarget = NULL;
return;
}
// Fade out
if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
{
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - g.IO.DeltaTime * 10.0f, 0.0f);
if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
g.NavWindowingTargetAnim = NULL;
}
// Start CTRL-TAB or Square+L/R window selection
bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputPressed(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard);
if (start_windowing_with_gamepad || start_windowing_with_keyboard)
if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
{
g.NavWindowingTarget = g.NavWindowingTargetAnim = window;
g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true;
g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad;
}
// Gamepad update
g.NavWindowingTimer += g.IO.DeltaTime;
if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavGamepad)
{
// Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
// Select window to focus
const int focus_change_dir = (int)IsNavInputPressed(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputPressed(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
if (focus_change_dir != 0)
{
NavUpdateWindowingHighlightWindow(focus_change_dir);
g.NavWindowingHighlightAlpha = 1.0f;
}
// Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
if (!IsNavInputDown(ImGuiNavInput_Menu))
{
g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
if (g.NavWindowingToggleLayer && g.NavWindow)
apply_toggle_layer = true;
else if (!g.NavWindowingToggleLayer)
apply_focus_window = g.NavWindowingTarget;
g.NavWindowingTarget = NULL;
}
}
// Keyboard: Focus
if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavKeyboard)
{
// Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
if (IsKeyPressedMap(ImGuiKey_Tab, true))
NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1);
if (!g.IO.KeyCtrl)
apply_focus_window = g.NavWindowingTarget;
}
// Keyboard: Press and Release ALT to toggle menu layer
// FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB
if (IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed))
g.NavWindowingToggleLayer = true;
if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev))
apply_toggle_layer = true;
// Move window
if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
{
ImVec2 move_delta;
if (g.NavInputSource == ImGuiInputSource_NavKeyboard && !g.IO.KeyShift)
move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_NavGamepad)
move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down);
if (move_delta.x != 0.0f || move_delta.y != 0.0f)
{
const float NAV_MOVE_SPEED = 800.0f;
const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't code variable framerate very well
SetWindowPos(g.NavWindowingTarget->RootWindow, g.NavWindowingTarget->RootWindow->Pos + move_delta * move_speed, ImGuiCond_Always);
g.NavDisableMouseHover = true;
MarkIniSettingsDirty(g.NavWindowingTarget);
}
}
// Apply final focus
if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
{
ClearActiveID();
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
ClosePopupsOverWindow(apply_focus_window, false);
FocusWindow(apply_focus_window);
if (apply_focus_window->NavLastIds[0] == 0)
NavInitWindow(apply_focus_window, false);
// If the window only has a menu layer, select it directly
if (apply_focus_window->DC.NavLayerActiveMask == (1 << ImGuiNavLayer_Menu))
g.NavLayer = ImGuiNavLayer_Menu;
}
if (apply_focus_window)
g.NavWindowingTarget = NULL;
// Apply menu/layer toggle
if (apply_toggle_layer && g.NavWindow)
{
// Move to parent menu if necessary
ImGuiWindow* new_nav_window = g.NavWindow;
while (new_nav_window->ParentWindow
&& (new_nav_window->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
&& (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
&& (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
new_nav_window = new_nav_window->ParentWindow;
if (new_nav_window != g.NavWindow)
{
ImGuiWindow* old_nav_window = g.NavWindow;
FocusWindow(new_nav_window);
new_nav_window->NavLastChildNavWindow = old_nav_window;
}
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
// When entering a regular menu bar with the Alt key, we always reinitialize the navigation ID.
const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
NavRestoreLayer(new_nav_layer);
}
}
// Window has already passed the IsWindowNavFocusable()
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
{
if (window->Flags & ImGuiWindowFlags_Popup)
return "(Popup)";
if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
return "(Main menu bar)";
return "(Untitled)";
}
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
void ImGui::NavUpdateWindowingList()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindowingTarget != NULL);
if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
return;
if (g.NavWindowingList == NULL)
g.NavWindowingList = FindWindowByName("###NavWindowingList");
SetNextWindowSizeConstraints(ImVec2(g.IO.DisplaySize.x * 0.20f, g.IO.DisplaySize.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
{
ImGuiWindow* window = g.WindowsFocusOrder[n];
if (!IsWindowNavFocusable(window))
continue;
const char* label = window->Name;
if (label == FindRenderedTextEnd(label))
label = GetFallbackWindowNameForWindowingList(window);
Selectable(label, g.NavWindowingTarget == window);
}
End();
PopStyleVar();
}
//-----------------------------------------------------------------------------
// [SECTION] DRAG AND DROP
//-----------------------------------------------------------------------------
void ImGui::ClearDragDrop()
{
ImGuiContext& g = *GImGui;
g.DragDropActive = false;
g.DragDropPayload.Clear();
g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropAcceptFrameCount = -1;
g.DragDropPayloadBufHeap.clear();
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
}
// Call when current ID is active.
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
bool source_drag_active = false;
ImGuiID source_id = 0;
ImGuiID source_parent_id = 0;
int mouse_button = 0;
if (!(flags & ImGuiDragDropFlags_SourceExtern))
{
source_id = window->DC.LastItemId;
if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case
return false;
if (g.IO.MouseDown[mouse_button] == false)
return false;
if (source_id == 0)
{
// If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
// A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride.
if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
{
IM_ASSERT(0);
return false;
}
// Early out
if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
return false;
// Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image()
// We build a throwaway ID based on current ID stack + relative AABB of items in window.
// THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
// We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
bool is_hovered = ItemHoverable(window->DC.LastItemRect, source_id);
if (is_hovered && g.IO.MouseClicked[mouse_button])
{
SetActiveID(source_id, window);
FocusWindow(window);
}
if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
g.ActiveIdAllowOverlap = is_hovered;
}
else
{
g.ActiveIdAllowOverlap = false;
}
if (g.ActiveId != source_id)
return false;
source_parent_id = window->IDStack.back();
source_drag_active = IsMouseDragging(mouse_button);
}
else
{
window = NULL;
source_id = ImHashStr("#SourceExtern");
source_drag_active = true;
}
if (source_drag_active)
{
if (!g.DragDropActive)
{
IM_ASSERT(source_id != 0);
ClearDragDrop();
ImGuiPayload& payload = g.DragDropPayload;
payload.SourceId = source_id;
payload.SourceParentId = source_parent_id;
g.DragDropActive = true;
g.DragDropSourceFlags = flags;
g.DragDropMouseButton = mouse_button;
}
g.DragDropSourceFrameCount = g.FrameCount;
g.DragDropWithinSourceOrTarget = true;
if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
{
// Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
// We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
BeginTooltip();
if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
{
ImGuiWindow* tooltip_window = g.CurrentWindow;
tooltip_window->SkipItems = true;
tooltip_window->HiddenFramesCanSkipItems = 1;
}
}
if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
return true;
}
return false;
}
void ImGui::EndDragDropSource()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.DragDropActive);
IM_ASSERT(g.DragDropWithinSourceOrTarget && "Not after a BeginDragDropSource()?");
if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
EndTooltip();
// Discard the drag if have not called SetDragDropPayload()
if (g.DragDropPayload.DataFrameCount == -1)
ClearDragDrop();
g.DragDropWithinSourceOrTarget = false;
}
// Use 'cond' to choose to submit payload on drag start or every frame
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
ImGuiPayload& payload = g.DragDropPayload;
if (cond == 0)
cond = ImGuiCond_Always;
IM_ASSERT(type != NULL);
IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
{
// Copy payload
ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
g.DragDropPayloadBufHeap.resize(0);
if (data_size > sizeof(g.DragDropPayloadBufLocal))
{
// Store in heap
g.DragDropPayloadBufHeap.resize((int)data_size);
payload.Data = g.DragDropPayloadBufHeap.Data;
memcpy(payload.Data, data, data_size);
}
else if (data_size > 0)
{
// Store locally
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
payload.Data = g.DragDropPayloadBufLocal;
memcpy(payload.Data, data, data_size);
}
else
{
payload.Data = NULL;
}
payload.DataSize = (int)data_size;
}
payload.DataFrameCount = g.FrameCount;
return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
}
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (!g.DragDropActive)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
return false;
IM_ASSERT(id != 0);
if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
return false;
if (window->SkipItems)
return false;
IM_ASSERT(g.DragDropWithinSourceOrTarget == false);
g.DragDropTargetRect = bb;
g.DragDropTargetId = id;
g.DragDropWithinSourceOrTarget = true;
return true;
}
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
// 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
bool ImGui::BeginDragDropTarget()
{
ImGuiContext& g = *GImGui;
if (!g.DragDropActive)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
return false;
const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect;
ImGuiID id = window->DC.LastItemId;
if (id == 0)
id = window->GetIDFromRectangle(display_rect);
if (g.DragDropPayload.SourceId == id)
return false;
IM_ASSERT(g.DragDropWithinSourceOrTarget == false);
g.DragDropTargetRect = display_rect;
g.DragDropTargetId = id;
g.DragDropWithinSourceOrTarget = true;
return true;
}
bool ImGui::IsDragDropPayloadBeingAccepted()
{
ImGuiContext& g = *GImGui;
return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
}
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiPayload& payload = g.DragDropPayload;
IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
if (type != NULL && !payload.IsDataType(type))
return NULL;
// Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
// NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
ImRect r = g.DragDropTargetRect;
float r_surface = r.GetWidth() * r.GetHeight();
if (r_surface < g.DragDropAcceptIdCurrRectSurface)
{
g.DragDropAcceptFlags = flags;
g.DragDropAcceptIdCurr = g.DragDropTargetId;
g.DragDropAcceptIdCurrRectSurface = r_surface;
}
// Render default drop visuals
payload.Preview = was_accepted_previously;
flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)
if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
{
// FIXME-DRAG: Settle on a proper default visuals for drop target.
r.Expand(3.5f);
bool push_clip_rect = !window->ClipRect.Contains(r);
if (push_clip_rect) window->DrawList->PushClipRect(r.Min-ImVec2(1,1), r.Max+ImVec2(1,1));
window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f);
if (push_clip_rect) window->DrawList->PopClipRect();
}
g.DragDropAcceptFrameCount = g.FrameCount;
payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
return NULL;
return &payload;
}
const ImGuiPayload* ImGui::GetDragDropPayload()
{
ImGuiContext& g = *GImGui;
return g.DragDropActive ? &g.DragDropPayload : NULL;
}
// We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
void ImGui::EndDragDropTarget()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.DragDropActive);
IM_ASSERT(g.DragDropWithinSourceOrTarget);
g.DragDropWithinSourceOrTarget = false;
}
//-----------------------------------------------------------------------------
// [SECTION] LOGGING/CAPTURING
//-----------------------------------------------------------------------------
// All text output from the interface can be captured into tty/file/clipboard.
// By default, tree nodes are automatically opened during logging.
//-----------------------------------------------------------------------------
// Pass text data straight to log (without being displayed)
void ImGui::LogText(const char* fmt, ...)
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
va_list args;
va_start(args, fmt);
if (g.LogFile)
vfprintf(g.LogFile, fmt, args);
else
g.LogBuffer.appendfv(fmt, args);
va_end(args);
}
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
// We split text into individual lines to add current tree level padding
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = FindRenderedTextEnd(text, text_end);
const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + 1);
if (ref_pos)
g.LogLinePosY = ref_pos->y;
if (log_new_line)
g.LogLineFirstItem = true;
const char* text_remaining = text;
if (g.LogDepthRef > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
g.LogDepthRef = window->DC.TreeDepth;
const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
for (;;)
{
// Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
// We don't add a trailing \n to allow a subsequent item on the same line to be captured.
const char* line_start = text_remaining;
const char* line_end = ImStreolRange(line_start, text_end);
const bool is_first_line = (line_start == text);
const bool is_last_line = (line_end == text_end);
if (!is_last_line || (line_start != line_end))
{
const int char_count = (int)(line_end - line_start);
if (log_new_line || !is_first_line)
LogText(IM_NEWLINE "%*s%.*s", tree_depth * 4, "", char_count, line_start);
else if (g.LogLineFirstItem)
LogText("%*s%.*s", tree_depth * 4, "", char_count, line_start);
else
LogText(" %.*s", char_count, line_start);
g.LogLineFirstItem = false;
}
else if (log_new_line)
{
// An empty "" string at a different Y position should output a carriage return.
LogText(IM_NEWLINE);
break;
}
if (is_last_line)
break;
text_remaining = line_end + 1;
}
}
// Start logging/capturing text output
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.LogEnabled == false);
IM_ASSERT(g.LogFile == NULL);
IM_ASSERT(g.LogBuffer.empty());
g.LogEnabled = true;
g.LogType = type;
g.LogDepthRef = window->DC.TreeDepth;
g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
g.LogLinePosY = FLT_MAX;
g.LogLineFirstItem = true;
}
void ImGui::LogToTTY(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
LogBegin(ImGuiLogType_TTY, auto_open_depth);
g.LogFile = stdout;
}
// Start logging/capturing text output to given file
void ImGui::LogToFile(int auto_open_depth, const char* filename)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
// FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
// be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
// By opening the file in binary mode "ab" we have consistent output everywhere.
if (!filename)
filename = g.IO.LogFilename;
if (!filename || !filename[0])
return;
FILE* f = ImFileOpen(filename, "ab");
if (f == NULL)
{
IM_ASSERT(0);
return;
}
LogBegin(ImGuiLogType_File, auto_open_depth);
g.LogFile = f;
}
// Start logging/capturing text output to clipboard
void ImGui::LogToClipboard(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
}
void ImGui::LogToBuffer(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
LogBegin(ImGuiLogType_Buffer, auto_open_depth);
}
void ImGui::LogFinish()
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
LogText(IM_NEWLINE);
switch (g.LogType)
{
case ImGuiLogType_TTY:
fflush(g.LogFile);
break;
case ImGuiLogType_File:
fclose(g.LogFile);
break;
case ImGuiLogType_Buffer:
break;
case ImGuiLogType_Clipboard:
if (!g.LogBuffer.empty())
SetClipboardText(g.LogBuffer.begin());
break;
case ImGuiLogType_None:
IM_ASSERT(0);
break;
}
g.LogEnabled = false;
g.LogType = ImGuiLogType_None;
g.LogFile = NULL;
g.LogBuffer.clear();
}
// Helper to display logging buttons
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
void ImGui::LogButtons()
{
ImGuiContext& g = *GImGui;
PushID("LogButtons");
const bool log_to_tty = Button("Log To TTY"); SameLine();
const bool log_to_file = Button("Log To File"); SameLine();
const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
PushAllowKeyboardFocus(false);
SetNextItemWidth(80.0f);
SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
PopAllowKeyboardFocus();
PopID();
// Start logging at the end of the function so that the buttons don't appear in the log
if (log_to_tty)
LogToTTY();
if (log_to_file)
LogToFile();
if (log_to_clipboard)
LogToClipboard();
}
//-----------------------------------------------------------------------------
// [SECTION] SETTINGS
//-----------------------------------------------------------------------------
void ImGui::MarkIniSettingsDirty()
{
ImGuiContext& g = *GImGui;
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
{
ImGuiContext& g = *GImGui;
g.SettingsWindows.push_back(ImGuiWindowSettings());
ImGuiWindowSettings* settings = &g.SettingsWindows.back();
#if !IMGUI_DEBUG_INI_SETTINGS
// Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
// Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
if (const char* p = strstr(name, "###"))
name = p;
#endif
settings->Name = ImStrdup(name);
settings->ID = ImHashStr(name);
return settings;
}
ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
{
ImGuiContext& g = *GImGui;
for (int i = 0; i != g.SettingsWindows.Size; i++)
if (g.SettingsWindows[i].ID == id)
return &g.SettingsWindows[i];
return NULL;
}
ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
{
if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))
return settings;
return CreateNewWindowSettings(name);
}
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
{
size_t file_data_size = 0;
char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
if (!file_data)
return;
LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
IM_FREE(file_data);
}
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
{
ImGuiContext& g = *GImGui;
const ImGuiID type_hash = ImHashStr(type_name);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
return &g.SettingsHandlers[handler_n];
return NULL;
}
// Zero-tolerance, no error reporting, cheap .ini parsing
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
// For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
// For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
if (ini_size == 0)
ini_size = strlen(ini_data);
char* buf = (char*)IM_ALLOC(ini_size + 1);
char* buf_end = buf + ini_size;
memcpy(buf, ini_data, ini_size);
buf[ini_size] = 0;
void* entry_data = NULL;
ImGuiSettingsHandler* entry_handler = NULL;
char* line_end = NULL;
for (char* line = buf; line < buf_end; line = line_end + 1)
{
// Skip new lines markers, then find end of the line
while (*line == '\n' || *line == '\r')
line++;
line_end = line;
while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
line_end++;
line_end[0] = 0;
if (line[0] == ';')
continue;
if (line[0] == '[' && line_end > line && line_end[-1] == ']')
{
// Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
line_end[-1] = 0;
const char* name_end = line_end - 1;
const char* type_start = line + 1;
char* type_end = (char*)(intptr_t)ImStrchrRange(type_start, name_end, ']');
const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
if (!type_end || !name_start)
{
name_start = type_start; // Import legacy entries that have no type
type_start = "Window";
}
else
{
*type_end = 0; // Overwrite first ']'
name_start++; // Skip second '['
}
entry_handler = FindSettingsHandler(type_start);
entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
}
else if (entry_handler != NULL && entry_data != NULL)
{
// Let type handler parse the line
entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
}
}
IM_FREE(buf);
g.SettingsLoaded = true;
}
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
if (!ini_filename)
return;
size_t ini_data_size = 0;
const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
FILE* f = ImFileOpen(ini_filename, "wt");
if (!f)
return;
fwrite(ini_data, sizeof(char), ini_data_size, f);
fclose(f);
}
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
g.SettingsIniData.Buf.resize(0);
g.SettingsIniData.Buf.push_back(0);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
{
ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
handler->WriteAllFn(&g, handler, &g.SettingsIniData);
}
if (out_size)
*out_size = (size_t)g.SettingsIniData.size();
return g.SettingsIniData.c_str();
}
static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
{
ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name));
if (!settings)
settings = ImGui::CreateNewWindowSettings(name);
return (void*)settings;
}
static void SettingsHandlerWindow_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void* entry, const char* line)
{
ImGuiContext& g = *ctx;
ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
float x, y;
int i;
if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y);
else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize);
else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0);
}
static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
// Gather data from windows that were active during this session
// (if a window wasn't opened in this session we preserve its settings)
ImGuiContext& g = *ctx;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
continue;
ImGuiWindowSettings* settings = (window->SettingsIdx != -1) ? &g.SettingsWindows[window->SettingsIdx] : ImGui::FindWindowSettings(window->ID);
if (!settings)
{
settings = ImGui::CreateNewWindowSettings(window->Name);
window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings);
}
IM_ASSERT(settings->ID == window->ID);
settings->Pos = window->Pos;
settings->Size = window->SizeFull;
settings->Collapsed = window->Collapsed;
}
// Write to text buffer
buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve
for (int i = 0; i != g.SettingsWindows.Size; i++)
{
const ImGuiWindowSettings* settings = &g.SettingsWindows[i];
if (settings->Pos.x == FLT_MAX)
continue;
buf->appendf("[%s][%s]\n", handler->TypeName, settings->Name);
buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
buf->appendf("Collapsed=%d\n", settings->Collapsed);
buf->appendf("\n");
}
}
//-----------------------------------------------------------------------------
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
//-----------------------------------------------------------------------------
// (this section is filled in the 'docking' branch)
//-----------------------------------------------------------------------------
// [SECTION] DOCKING
//-----------------------------------------------------------------------------
// (this section is filled in the 'docking' branch)
//-----------------------------------------------------------------------------
// [SECTION] PLATFORM DEPENDENT HELPERS
//-----------------------------------------------------------------------------
#if defined(_WIN32) && !defined(_WINDOWS_) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS))
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef __MINGW32__
#include <Windows.h>
#else
#include <windows.h>
#endif
#elif defined(__APPLE__)
#include <TargetConditionals.h>
#endif
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
#ifdef _MSC_VER
#pragma comment(lib, "user32")
#endif
// Win32 clipboard implementation
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
static ImVector<char> buf_local;
buf_local.clear();
if (!::OpenClipboard(NULL))
return NULL;
HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
if (wbuf_handle == NULL)
{
::CloseClipboard();
return NULL;
}
if (ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle))
{
int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1;
buf_local.resize(buf_len);
ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL);
}
::GlobalUnlock(wbuf_handle);
::CloseClipboard();
return buf_local.Data;
}
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
if (!::OpenClipboard(NULL))
return;
const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1;
HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar));
if (wbuf_handle == NULL)
{
::CloseClipboard();
return;
}
ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle);
ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL);
::GlobalUnlock(wbuf_handle);
::EmptyClipboard();
if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
::GlobalFree(wbuf_handle);
::CloseClipboard();
}
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
#include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
static PasteboardRef main_clipboard = 0;
// OSX clipboard implementation
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
if (!main_clipboard)
PasteboardCreate(kPasteboardClipboard, &main_clipboard);
PasteboardClear(main_clipboard);
CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
if (cf_data)
{
PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
CFRelease(cf_data);
}
}
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
if (!main_clipboard)
PasteboardCreate(kPasteboardClipboard, &main_clipboard);
PasteboardSynchronize(main_clipboard);
ItemCount item_count = 0;
PasteboardGetItemCount(main_clipboard, &item_count);
for (int i = 0; i < item_count; i++)
{
PasteboardItemID item_id = 0;
PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
CFArrayRef flavor_type_array = 0;
PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
{
CFDataRef cf_data;
if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
{
static ImVector<char> clipboard_text;
int length = (int)CFDataGetLength(cf_data);
clipboard_text.resize(length + 1);
CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)clipboard_text.Data);
clipboard_text[length] = 0;
CFRelease(cf_data);
return clipboard_text.Data;
}
}
}
return NULL;
}
#else
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
ImGuiContext& g = *GImGui;
return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin();
}
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
ImGuiContext& g = *GImGui;
g.PrivateClipboard.clear();
const char* text_end = text + strlen(text);
g.PrivateClipboard.resize((int)(text_end - text) + 1);
memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text));
g.PrivateClipboard[(int)(text_end - text)] = 0;
}
#endif
// Win32 API IME support (for Asian languages, etc.)
#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
#include <imm.h>
#ifdef _MSC_VER
#pragma comment(lib, "imm32")
#endif
static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y)
{
// Notify OS Input Method Editor of text input position
ImGuiIO& io = ImGui::GetIO();
if (HWND hwnd = (HWND)io.ImeWindowHandle)
if (HIMC himc = ::ImmGetContext(hwnd))
{
COMPOSITIONFORM cf;
cf.ptCurrentPos.x = x;
cf.ptCurrentPos.y = y;
cf.dwStyle = CFS_FORCE_POSITION;
::ImmSetCompositionWindow(himc, &cf);
::ImmReleaseContext(hwnd, himc);
}
}
#else
static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
#endif
//-----------------------------------------------------------------------------
// [SECTION] METRICS/DEBUG WINDOW
//-----------------------------------------------------------------------------
#ifndef IMGUI_DISABLE_METRICS_WINDOW
void ImGui::ShowMetricsWindow(bool* p_open)
{
if (!ImGui::Begin("Dear ImGui Metrics", p_open))
{
ImGui::End();
return;
}
// State
enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Contents, WRT_ContentsRegionRect, WRT_Count }; // Windows Rect Type
const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Contents", "ContentsRegionRect" };
static bool show_windows_rects = false;
static int show_windows_rect_type = WRT_WorkRect;
static bool show_windows_begin_order = false;
static bool show_drawcmd_clip_rects = true;
// Basic info
ImGuiContext& g = *GImGui;
ImGuiIO& io = ImGui::GetIO();
ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
ImGui::Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows);
ImGui::Text("%d active allocations", io.MetricsActiveAllocations);
ImGui::Separator();
// Helper functions to display common structures:
// - NodeDrawList
// - NodeColumns
// - NodeWindow
// - NodeWindows
// - NodeTabBar
struct Funcs
{
static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
{
if (rect_type == WRT_OuterRect) { return window->Rect(); }
else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
else if (rect_type == WRT_Contents) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
else if (rect_type == WRT_ContentsRegionRect) { return window->ContentsRegionRect; }
IM_ASSERT(0);
return ImRect();
}
static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label)
{
bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size);
if (draw_list == ImGui::GetWindowDrawList())
{
ImGui::SameLine();
ImGui::TextColored(ImVec4(1.0f,0.4f,0.4f,1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
if (node_open) ImGui::TreePop();
return;
}
ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
if (window && IsItemHovered())
fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
if (!node_open)
return;
if (window && !window->WasActive)
ImGui::Text("(Note: owning Window is inactive: DrawList is not being rendered!)");
int elem_offset = 0;
for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
{
if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0)
continue;
if (pcmd->UserCallback)
{
ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
continue;
}
ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
char buf[300];
ImFormatString(buf, IM_ARRAYSIZE(buf), "Draw %4d triangles, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
pcmd->ElemCount/3, (void*)(intptr_t)pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
if (show_drawcmd_clip_rects && fg_draw_list && ImGui::IsItemHovered())
{
ImRect clip_rect = pcmd->ClipRect;
ImRect vtxs_rect;
for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
clip_rect.Floor(); fg_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,0,255,255));
vtxs_rect.Floor(); fg_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,255,0,255));
}
if (!pcmd_node_open)
continue;
// Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
ImGui::Text("ElemCount: %d, ElemCount/3: %d, VtxOffset: +%d, IdxOffset: +%d", pcmd->ElemCount, pcmd->ElemCount/3, pcmd->VtxOffset, pcmd->IdxOffset);
ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
while (clipper.Step())
for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
{
char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf);
ImVec2 triangles_pos[3];
for (int n = 0; n < 3; n++, idx_i++)
{
int vtx_i = idx_buffer ? idx_buffer[idx_i] : idx_i;
ImDrawVert& v = draw_list->VtxBuffer[vtx_i];
triangles_pos[n] = v.pos;
buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
(n == 0) ? "elem" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
}
ImGui::Selectable(buf, false);
if (fg_draw_list && ImGui::IsItemHovered())
{
ImDrawListFlags backup_flags = fg_draw_list->Flags;
fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles.
fg_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f);
fg_draw_list->Flags = backup_flags;
}
}
ImGui::TreePop();
}
ImGui::TreePop();
}
static void NodeColumns(const ImGuiColumns* columns)
{
if (!ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
return;
ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
ImGui::TreePop();
}
static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label)
{
if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
return;
for (int i = 0; i < windows.Size; i++)
Funcs::NodeWindow(windows[i], "Window");
ImGui::TreePop();
}
static void NodeWindow(ImGuiWindow* window, const char* label)
{
if (window == NULL)
{
ImGui::BulletText("%s: NULL", label);
return;
}
if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, (window->Active || window->WasActive), window))
return;
ImGuiWindowFlags flags = window->Flags;
NodeDrawList(window, window->DrawList, "DrawList");
ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y);
ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
(flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
(flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
(flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y);
ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
ImGui::BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask);
ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
if (!window->NavRectRel[0].IsInverted())
ImGui::BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y);
else
ImGui::BulletText("NavRectRel[0]: <None>");
if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
if (window->ParentWindow != NULL) NodeWindow(window->ParentWindow, "ParentWindow");
if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
{
for (int n = 0; n < window->ColumnsStorage.Size; n++)
NodeColumns(&window->ColumnsStorage[n]);
ImGui::TreePop();
}
ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.size_in_bytes());
ImGui::TreePop();
}
static void NodeTabBar(ImGuiTabBar* tab_bar)
{
// Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
char buf[256];
char* p = buf;
const char* buf_end = buf + IM_ARRAYSIZE(buf);
ImFormatString(p, buf_end - p, "TabBar (%d tabs)%s", tab_bar->Tabs.Size, (tab_bar->PrevFrameVisible < ImGui::GetFrameCount() - 2) ? " *Inactive*" : "");
if (ImGui::TreeNode(tab_bar, "%s", buf))
{
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
ImGui::PushID(tab);
if (ImGui::SmallButton("<")) { TabBarQueueChangeTabOrder(tab_bar, tab, -1); } ImGui::SameLine(0, 2);
if (ImGui::SmallButton(">")) { TabBarQueueChangeTabOrder(tab_bar, tab, +1); } ImGui::SameLine();
ImGui::Text("%02d%c Tab 0x%08X", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID);
ImGui::PopID();
}
ImGui::TreePop();
}
}
};
Funcs::NodeWindows(g.Windows, "Windows");
if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size))
{
for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++)
Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList");
ImGui::TreePop();
}
if (ImGui::TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
{
for (int i = 0; i < g.OpenPopupStack.Size; i++)
{
ImGuiWindow* window = g.OpenPopupStack[i].Window;
ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
}
ImGui::TreePop();
}
if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.Data.Size))
{
for (int n = 0; n < g.TabBars.Data.Size; n++)
Funcs::NodeTabBar(g.TabBars.GetByIndex(n));
ImGui::TreePop();
}
#if 0
if (ImGui::TreeNode("Docking"))
{
ImGui::TreePop();
}
#endif
#if 0
if (ImGui::TreeNode("Tables", "Tables (%d)", g.Tables.Data.Size))
{
ImGui::TreePop();
}
#endif
if (ImGui::TreeNode("Internal state"))
{
const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]);
ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]);
ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId);
ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
ImGui::Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
ImGui::TreePop();
}
if (ImGui::TreeNode("Tools"))
{
// The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
if (ImGui::Button("Item Picker.."))
ImGui::DebugStartItemPicker();
ImGui::Checkbox("Show windows begin order", &show_windows_begin_order);
ImGui::Checkbox("Show windows rectangles", &show_windows_rects);
ImGui::SameLine();
ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12);
show_windows_rects |= ImGui::Combo("##show_windows_rect_type", &show_windows_rect_type, wrt_rects_names, WRT_Count);
if (show_windows_rects && g.NavWindow)
{
ImGui::BulletText("'%s':", g.NavWindow->Name);
ImGui::Indent();
for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
{
ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
ImGui::Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
}
ImGui::Unindent();
}
ImGui::Checkbox("Show clipping rectangle when hovering ImDrawCmd node", &show_drawcmd_clip_rects);
ImGui::TreePop();
}
// Tool: Display windows Rectangles and Begin Order
if (show_windows_rects || show_windows_begin_order)
{
for (int n = 0; n < g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
if (!window->WasActive)
continue;
ImDrawList* draw_list = GetForegroundDrawList(window);
if (show_windows_rects)
{
ImRect r = Funcs::GetWindowRect(window, show_windows_rect_type);
draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
}
if (show_windows_begin_order && !(window->Flags & ImGuiWindowFlags_ChildWindow))
{
char buf[32];
ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
float font_size = ImGui::GetFontSize();
draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
}
}
}
ImGui::End();
}
#else
void ImGui::ShowMetricsWindow(bool*) { }
#endif
//-----------------------------------------------------------------------------
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
#include "imgui_user.inl"
#endif
//-----------------------------------------------------------------------------
|
NVIDIA-Omniverse/PhysX/flow/external/imgui/imconfig.h | //-----------------------------------------------------------------------------
// 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/branch with your modifications to imconfig.h)
// B) or add configuration directives in your own file and compile with #define IMGUI_USER_CONFIG "myfilename.h"
// If you do so 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().
//#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.
//#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport )
//---- Don't define obsolete functions/enums names. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names.
//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
//---- Don't implement demo windows functionality (ShowDemoWindow()/ShowStyleEditor()/ShowUserGuide() methods will be empty)
// It is very strongly recommended to NOT disable the demo windows during development. Please read the comments in imgui_demo.cpp.
//#define IMGUI_DISABLE_DEMO_WINDOWS
//#define IMGUI_DISABLE_METRICS_WINDOW
//---- 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.
//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] Don't implement default IME handler. Won't use and link with ImmGetContext/ImmSetCompositionWindow.
//#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').
//#define IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself if you don't want to link with vsnprintf.
//#define IMGUI_DISABLE_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 wrapper so you can implement them yourself. Declare your prototypes in imconfig.h.
//#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().
//---- 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
//---- 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 imgui cpp 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
//---- 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); }
*/
//---- Using 32-bits vertex indices (default is 16-bits) is one way to allow large meshes with more than 64K vertices.
// Your renderer back-end will need to support it (most example renderer back-ends support both 16/32-bits indices).
// Another way to allow large meshes while keeping 16-bits 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 back-ends 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
// 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()
// Have the Item Picker break in the ItemAdd() function instead of ItemHoverable() - which is 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
//---- 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);
}
*/
|
NVIDIA-Omniverse/PhysX/flow/external/imgui/imgui_internal.h | // dear imgui, v1.72b
// (internal structures/api)
// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility!
// Set:
// #define IMGUI_DEFINE_MATH_OPERATORS
// To implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators)
/*
Index of this file:
// Header mess
// Forward declarations
// STB libraries includes
// Context pointer
// Generic helpers
// Misc data structures
// Main imgui context
// Tab bar, tab item
// Internal API
*/
#pragma once
//-----------------------------------------------------------------------------
// Header mess
//-----------------------------------------------------------------------------
#ifndef IMGUI_VERSION
#error Must include imgui.h before imgui_internal.h
#endif
#include <stdio.h> // FILE*
#include <stdlib.h> // NULL, malloc, free, qsort, atoi, atof
#include <math.h> // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf
#include <limits.h> // INT_MIN, INT_MAX
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable: 4251) // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport)
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h
#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h
#pragma clang diagnostic ignored "-Wold-style-cast"
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
#endif
#if __has_warning("-Wdouble-promotion")
#pragma clang diagnostic ignored "-Wdouble-promotion"
#endif
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
struct ImRect; // An axis-aligned rectangle (2 points)
struct ImDrawDataBuilder; // Helper to build a ImDrawData instance
struct ImDrawListSharedData; // Data shared between all ImDrawList instances
struct ImGuiColorMod; // Stacked color modifier, backup of modified data so we can restore it
struct ImGuiColumnData; // Storage data for a single column
struct ImGuiColumns; // Storage data for a columns set
struct ImGuiContext; // Main Dear ImGui context
struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum
struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup()
struct ImGuiInputTextState; // Internal state of the currently focused/edited text input box
struct ImGuiItemHoveredDataBackup; // Backup and restore IsItemHovered() internal data
struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only
struct ImGuiNavMoveResult; // Result of a directional navigation move query result
struct ImGuiNextWindowData; // Storage for SetNextWindow** functions
struct ImGuiNextItemData; // Storage for SetNextItem** functions
struct ImGuiPopupData; // Storage for current popup stack
struct ImGuiSettingsHandler; // Storage for one type registered in the .ini file
struct ImGuiStyleMod; // Stacked style modifier, backup of modified data so we can restore it
struct ImGuiTabBar; // Storage for a tab bar
struct ImGuiTabItem; // Storage for a tab item (within a tab bar)
struct ImGuiWindow; // Storage for one window
struct ImGuiWindowTempData; // Temporary storage for one window (that's the data which in theory we could ditch at the end of the frame)
struct ImGuiWindowSettings; // Storage for window settings stored in .ini file (we keep one of those even if the actual window wasn't instanced during this session)
// Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists.
typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical
typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for ButtonEx(), ButtonBehavior()
typedef int ImGuiColumnsFlags; // -> enum ImGuiColumnsFlags_ // Flags: BeginColumns()
typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: for DragBehavior()
typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag()
typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for DC.LastItemStatusFlags
typedef int ImGuiNavHighlightFlags; // -> enum ImGuiNavHighlightFlags_ // Flags: for RenderNavHighlight()
typedef int ImGuiNavDirSourceFlags; // -> enum ImGuiNavDirSourceFlags_ // Flags: for GetNavInputAmount2d()
typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // Flags: for navigation requests
typedef int ImGuiNextItemDataFlags; // -> enum ImGuiNextItemDataFlags_ // Flags: for SetNextItemXXX() functions
typedef int ImGuiNextWindowDataFlags; // -> enum ImGuiNextWindowDataFlags_// Flags: for SetNextWindowXXX() functions
typedef int ImGuiSeparatorFlags; // -> enum ImGuiSeparatorFlags_ // Flags: for SeparatorEx()
typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for SliderBehavior()
typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx()
//-------------------------------------------------------------------------
// STB libraries includes
//-------------------------------------------------------------------------
namespace ImStb
{
#undef STB_TEXTEDIT_STRING
#undef STB_TEXTEDIT_CHARTYPE
#define STB_TEXTEDIT_STRING ImGuiInputTextState
#define STB_TEXTEDIT_CHARTYPE ImWchar
#define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.0f
#define STB_TEXTEDIT_UNDOSTATECOUNT 99
#define STB_TEXTEDIT_UNDOCHARCOUNT 999
#include "imstb_textedit.h"
} // namespace ImStb
//-----------------------------------------------------------------------------
// Context pointer
//-----------------------------------------------------------------------------
#ifndef GImGui
extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer
#endif
//-----------------------------------------------------------------------------
// Generic helpers
//-----------------------------------------------------------------------------
#define IM_PI 3.14159265358979323846f
#ifdef _WIN32
#define IM_NEWLINE "\r\n" // Play it nice with Windows users (2018/05 news: Microsoft announced that Notepad will finally display Unix-style carriage returns!)
#else
#define IM_NEWLINE "\n"
#endif
#define IM_TABSIZE (4)
#define IM_STATIC_ASSERT(_COND) typedef char static_assertion_##__line__[(_COND)?1:-1]
#define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose
#define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255
// Debug Logging
#ifndef IMGUI_DEBUG_LOG
#define IMGUI_DEBUG_LOG(_FMT,...) printf("[%05d] " _FMT, GImGui->FrameCount, __VA_ARGS__)
#endif
// Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall
#ifdef _MSC_VER
#define IMGUI_CDECL __cdecl
#else
#define IMGUI_CDECL
#endif
// Helpers: UTF-8 <> wchar
IMGUI_API int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count
IMGUI_API int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // read one character. return input UTF-8 bytes count
IMGUI_API int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count
IMGUI_API int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count)
IMGUI_API int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end); // return number of bytes to express one char in UTF-8
IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string in UTF-8
// Helpers: Misc
IMGUI_API ImU32 ImHashData(const void* data, size_t data_size, ImU32 seed = 0);
IMGUI_API ImU32 ImHashStr(const char* data, size_t data_size = 0, ImU32 seed = 0);
IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size = NULL, int padding_bytes = 0);
IMGUI_API FILE* ImFileOpen(const char* filename, const char* file_open_mode);
static inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; }
static inline bool ImCharIsBlankW(unsigned int c) { return c == ' ' || c == '\t' || c == 0x3000; }
static inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; }
static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; }
#define ImQsort qsort
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
static inline ImU32 ImHash(const void* data, int size, ImU32 seed = 0) { return size ? ImHashData(data, (size_t)size, seed) : ImHashStr((const char*)data, 0, seed); } // [moved to ImHashStr/ImHashData in 1.68]
#endif
// Helpers: Geometry
IMGUI_API ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p);
IMGUI_API bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p);
IMGUI_API ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p);
IMGUI_API void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w);
IMGUI_API ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy);
// Helpers: String
IMGUI_API int ImStricmp(const char* str1, const char* str2);
IMGUI_API int ImStrnicmp(const char* str1, const char* str2, size_t count);
IMGUI_API void ImStrncpy(char* dst, const char* src, size_t count);
IMGUI_API char* ImStrdup(const char* str);
IMGUI_API char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* str);
IMGUI_API const char* ImStrchrRange(const char* str_begin, const char* str_end, char c);
IMGUI_API int ImStrlenW(const ImWchar* str);
IMGUI_API const char* ImStreolRange(const char* str, const char* str_end); // End end-of-line
IMGUI_API const ImWchar*ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin); // Find beginning-of-line
IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end);
IMGUI_API void ImStrTrimBlanks(char* str);
IMGUI_API int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) IM_FMTARGS(3);
IMGUI_API int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) IM_FMTLIST(3);
IMGUI_API const char* ImParseFormatFindStart(const char* format);
IMGUI_API const char* ImParseFormatFindEnd(const char* format);
IMGUI_API const char* ImParseFormatTrimDecorations(const char* format, char* buf, size_t buf_size);
IMGUI_API int ImParseFormatPrecision(const char* format, int default_value);
// Helpers: ImVec2/ImVec4 operators
// We are keeping those disabled by default so they don't leak in user space, to allow user enabling implicit cast operators between ImVec2 and their own types (using IM_VEC2_CLASS_EXTRA etc.)
// We unfortunately don't have a unary- operator for ImVec2 because this would needs to be defined inside the class itself.
#ifdef IMGUI_DEFINE_MATH_OPERATORS
static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); }
static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); }
static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); }
static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); }
static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); }
static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); }
static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; }
static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; }
static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; }
static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; }
static inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x+rhs.x, lhs.y+rhs.y, lhs.z+rhs.z, lhs.w+rhs.w); }
static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x-rhs.x, lhs.y-rhs.y, lhs.z-rhs.z, lhs.w-rhs.w); }
static inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x*rhs.x, lhs.y*rhs.y, lhs.z*rhs.z, lhs.w*rhs.w); }
#endif
// Helpers: Maths
// - Wrapper for standard libs functions. (Note that imgui_demo.cpp does _not_ use them to keep the code easy to copy)
#ifndef IMGUI_DISABLE_MATH_FUNCTIONS
static inline float ImFabs(float x) { return fabsf(x); }
static inline float ImSqrt(float x) { return sqrtf(x); }
static inline float ImPow(float x, float y) { return powf(x, y); }
static inline double ImPow(double x, double y) { return pow(x, y); }
static inline float ImFmod(float x, float y) { return fmodf(x, y); }
static inline double ImFmod(double x, double y) { return fmod(x, y); }
static inline float ImCos(float x) { return cosf(x); }
static inline float ImSin(float x) { return sinf(x); }
static inline float ImAcos(float x) { return acosf(x); }
static inline float ImAtan2(float y, float x) { return atan2f(y, x); }
static inline double ImAtof(const char* s) { return atof(s); }
static inline float ImFloorStd(float x) { return floorf(x); } // we already uses our own ImFloor() { return (float)(int)v } internally so the standard one wrapper is named differently (it's used by stb_truetype)
static inline float ImCeil(float x) { return ceilf(x); }
#endif
// - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support for variety of types: signed/unsigned int/long long float/double
// (Exceptionally using templates here but we could also redefine them for variety of types)
template<typename T> static inline T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; }
template<typename T> static inline T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; }
template<typename T> static inline T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
template<typename T> static inline T ImLerp(T a, T b, float t) { return (T)(a + (b - a) * t); }
template<typename T> static inline void ImSwap(T& a, T& b) { T tmp = a; a = b; b = tmp; }
template<typename T> static inline T ImAddClampOverflow(T a, T b, T mn, T mx) { if (b < 0 && (a < mn - b)) return mn; if (b > 0 && (a > mx - b)) return mx; return a + b; }
template<typename T> static inline T ImSubClampOverflow(T a, T b, T mn, T mx) { if (b > 0 && (a < mn + b)) return mn; if (b < 0 && (a > mx + b)) return mx; return a - b; }
// - Misc maths helpers
static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y); }
static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x >= rhs.x ? lhs.x : rhs.x, lhs.y >= rhs.y ? lhs.y : rhs.y); }
static inline ImVec2 ImClamp(const ImVec2& v, const ImVec2& mn, ImVec2 mx) { return ImVec2((v.x < mn.x) ? mn.x : (v.x > mx.x) ? mx.x : v.x, (v.y < mn.y) ? mn.y : (v.y > mx.y) ? mx.y : v.y); }
static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t) { return ImVec2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); }
static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); }
static inline ImVec4 ImLerp(const ImVec4& a, const ImVec4& b, float t) { return ImVec4(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w + (b.w - a.w) * t); }
static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; }
static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; }
static inline float ImLengthSqr(const ImVec4& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z + lhs.w*lhs.w; }
static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = lhs.x*lhs.x + lhs.y*lhs.y; if (d > 0.0f) return 1.0f / ImSqrt(d); return fail_value; }
static inline float ImFloor(float f) { return (float)(int)f; }
static inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2((float)(int)v.x, (float)(int)v.y); }
static inline int ImModPositive(int a, int b) { return (a + b) % b; }
static inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; }
static inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); }
static inline float ImLinearSweep(float current, float target, float speed) { if (current < target) return ImMin(current + speed, target); if (current > target) return ImMax(current - speed, target); return current; }
static inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); }
// Helper: ImBoolVector. Store 1-bit per value.
// Note that Resize() currently clears the whole vector.
struct ImBoolVector
{
ImVector<int> Storage;
ImBoolVector() { }
void Resize(int sz) { Storage.resize((sz + 31) >> 5); memset(Storage.Data, 0, (size_t)Storage.Size * sizeof(Storage.Data[0])); }
void Clear() { Storage.clear(); }
bool GetBit(int n) const { int off = (n >> 5); int mask = 1 << (n & 31); return (Storage[off] & mask) != 0; }
void SetBit(int n, bool v) { int off = (n >> 5); int mask = 1 << (n & 31); if (v) Storage[off] |= mask; else Storage[off] &= ~mask; }
};
// Helper: ImPool<>. Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer,
// Honor constructor/destructor. Add/remove invalidate all pointers. Indexes have the same lifetime as the associated object.
typedef int ImPoolIdx;
template<typename T>
struct IMGUI_API ImPool
{
ImVector<T> Data; // Contiguous data
ImGuiStorage Map; // ID->Index
ImPoolIdx FreeIdx; // Next free idx to use
ImPool() { FreeIdx = 0; }
~ImPool() { Clear(); }
T* GetByKey(ImGuiID key) { int idx = Map.GetInt(key, -1); return (idx != -1) ? &Data[idx] : NULL; }
T* GetByIndex(ImPoolIdx n) { return &Data[n]; }
ImPoolIdx GetIndex(const T* p) const { IM_ASSERT(p >= Data.Data && p < Data.Data + Data.Size); return (ImPoolIdx)(p - Data.Data); }
T* GetOrAddByKey(ImGuiID key) { int* p_idx = Map.GetIntRef(key, -1); if (*p_idx != -1) return &Data[*p_idx]; *p_idx = FreeIdx; return Add(); }
bool Contains(const T* p) const { return (p >= Data.Data && p < Data.Data + Data.Size); }
void Clear() { for (int n = 0; n < Map.Data.Size; n++) { int idx = Map.Data[n].val_i; if (idx != -1) Data[idx].~T(); } Map.Clear(); Data.clear(); FreeIdx = 0; }
T* Add() { int idx = FreeIdx; if (idx == Data.Size) { Data.resize(Data.Size + 1); FreeIdx++; } else { FreeIdx = *(int*)&Data[idx]; } IM_PLACEMENT_NEW(&Data[idx]) T(); return &Data[idx]; }
void Remove(ImGuiID key, const T* p) { Remove(key, GetIndex(p)); }
void Remove(ImGuiID key, ImPoolIdx idx) { Data[idx].~T(); *(int*)&Data[idx] = FreeIdx; FreeIdx = idx; Map.SetInt(key, -1); }
void Reserve(int capacity) { Data.reserve(capacity); Map.Data.reserve(capacity); }
int GetSize() const { return Data.Size; }
};
//-----------------------------------------------------------------------------
// Misc data structures
//-----------------------------------------------------------------------------
enum ImGuiButtonFlags_
{
ImGuiButtonFlags_None = 0,
ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat
ImGuiButtonFlags_PressedOnClickRelease = 1 << 1, // [Default] return true on click + release on same item
ImGuiButtonFlags_PressedOnClick = 1 << 2, // return true on click (default requires click+release)
ImGuiButtonFlags_PressedOnRelease = 1 << 3, // return true on release (default requires click+release)
ImGuiButtonFlags_PressedOnDoubleClick = 1 << 4, // return true on double-click (default requires click+release)
ImGuiButtonFlags_FlattenChildren = 1 << 5, // allow interactions even if a child window is overlapping
ImGuiButtonFlags_AllowItemOverlap = 1 << 6, // require previous frame HoveredId to either match id or be null before being usable, use along with SetItemAllowOverlap()
ImGuiButtonFlags_DontClosePopups = 1 << 7, // disable automatically closing parent popup on press // [UNUSED]
ImGuiButtonFlags_Disabled = 1 << 8, // disable interactions
ImGuiButtonFlags_AlignTextBaseLine = 1 << 9, // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine
ImGuiButtonFlags_NoKeyModifiers = 1 << 10, // disable interaction if a key modifier is held
ImGuiButtonFlags_NoHoldingActiveID = 1 << 11, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only)
ImGuiButtonFlags_PressedOnDragDropHold = 1 << 12, // press when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers)
ImGuiButtonFlags_NoNavFocus = 1 << 13, // don't override navigation focus when activated
ImGuiButtonFlags_NoHoveredOnNav = 1 << 14 // don't report as hovered when navigated on
};
enum ImGuiSliderFlags_
{
ImGuiSliderFlags_None = 0,
ImGuiSliderFlags_Vertical = 1 << 0
};
enum ImGuiDragFlags_
{
ImGuiDragFlags_None = 0,
ImGuiDragFlags_Vertical = 1 << 0
};
enum ImGuiColumnsFlags_
{
// Default: 0
ImGuiColumnsFlags_None = 0,
ImGuiColumnsFlags_NoBorder = 1 << 0, // Disable column dividers
ImGuiColumnsFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers
ImGuiColumnsFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns
ImGuiColumnsFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window
ImGuiColumnsFlags_GrowParentContentsSize= 1 << 4 // (WIP) Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove.
};
// Extend ImGuiSelectableFlags_
enum ImGuiSelectableFlagsPrivate_
{
// NB: need to be in sync with last value of ImGuiSelectableFlags_
ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20,
ImGuiSelectableFlags_PressedOnClick = 1 << 21,
ImGuiSelectableFlags_PressedOnRelease = 1 << 22,
ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 23, // FIXME: We may be able to remove this (added in 6251d379 for menus)
ImGuiSelectableFlags_AllowItemOverlap = 1 << 24,
ImGuiSelectableFlags_DrawHoveredWhenHeld= 1 << 25, // Always show active when held, even is not hovered. This concept could probably be renamed/formalized somehow.
ImGuiSelectableFlags_SetNavIdOnHover = 1 << 26
};
// Extend ImGuiTreeNodeFlags_
enum ImGuiTreeNodeFlagsPrivate_
{
ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 20
};
enum ImGuiSeparatorFlags_
{
ImGuiSeparatorFlags_None = 0,
ImGuiSeparatorFlags_Horizontal = 1 << 0, // Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar
ImGuiSeparatorFlags_Vertical = 1 << 1,
ImGuiSeparatorFlags_SpanAllColumns = 1 << 2
};
// Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first Begin().
// This is going to be exposed in imgui.h when stabilized enough.
enum ImGuiItemFlags_
{
ImGuiItemFlags_NoTabStop = 1 << 0, // false
ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings.
ImGuiItemFlags_Disabled = 1 << 2, // false // [BETA] Disable interactions but doesn't affect visuals yet. See github.com/ocornut/imgui/issues/211
ImGuiItemFlags_NoNav = 1 << 3, // false
ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false
ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window
ImGuiItemFlags_MixedValue = 1 << 6, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets)
ImGuiItemFlags_Default_ = 0
};
// Storage for LastItem data
enum ImGuiItemStatusFlags_
{
ImGuiItemStatusFlags_None = 0,
ImGuiItemStatusFlags_HoveredRect = 1 << 0,
ImGuiItemStatusFlags_HasDisplayRect = 1 << 1,
ImGuiItemStatusFlags_Edited = 1 << 2, // Value exposed by item was edited in the current frame (should match the bool return value of most widgets)
ImGuiItemStatusFlags_ToggledSelection = 1 << 3, // Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected" because reporting the change allows us to handle clipping with less issues.
ImGuiItemStatusFlags_HasDeactivated = 1 << 4, // Set if the widget/group is able to provide data for the ImGuiItemStatusFlags_Deactivated flag.
ImGuiItemStatusFlags_Deactivated = 1 << 5 // Only valid if ImGuiItemStatusFlags_HasDeactivated is set.
#ifdef IMGUI_ENABLE_TEST_ENGINE
, // [imgui_tests only]
ImGuiItemStatusFlags_Openable = 1 << 10, //
ImGuiItemStatusFlags_Opened = 1 << 11, //
ImGuiItemStatusFlags_Checkable = 1 << 12, //
ImGuiItemStatusFlags_Checked = 1 << 13 //
#endif
};
enum ImGuiTextFlags_
{
ImGuiTextFlags_None = 0,
ImGuiTextFlags_NoWidthForLargeClippedText = 1 << 0
};
// FIXME: this is in development, not exposed/functional as a generic feature yet.
// Horizontal/Vertical enums are fixed to 0/1 so they may be used to index ImVec2
enum ImGuiLayoutType_
{
ImGuiLayoutType_Horizontal = 0,
ImGuiLayoutType_Vertical = 1
};
enum ImGuiLogType
{
ImGuiLogType_None = 0,
ImGuiLogType_TTY,
ImGuiLogType_File,
ImGuiLogType_Buffer,
ImGuiLogType_Clipboard
};
// X/Y enums are fixed to 0/1 so they may be used to index ImVec2
enum ImGuiAxis
{
ImGuiAxis_None = -1,
ImGuiAxis_X = 0,
ImGuiAxis_Y = 1
};
enum ImGuiPlotType
{
ImGuiPlotType_Lines,
ImGuiPlotType_Histogram
};
enum ImGuiInputSource
{
ImGuiInputSource_None = 0,
ImGuiInputSource_Mouse,
ImGuiInputSource_Nav,
ImGuiInputSource_NavKeyboard, // Only used occasionally for storage, not tested/handled by most code
ImGuiInputSource_NavGamepad, // "
ImGuiInputSource_COUNT
};
// FIXME-NAV: Clarify/expose various repeat delay/rate
enum ImGuiInputReadMode
{
ImGuiInputReadMode_Down,
ImGuiInputReadMode_Pressed,
ImGuiInputReadMode_Released,
ImGuiInputReadMode_Repeat,
ImGuiInputReadMode_RepeatSlow,
ImGuiInputReadMode_RepeatFast
};
enum ImGuiNavHighlightFlags_
{
ImGuiNavHighlightFlags_None = 0,
ImGuiNavHighlightFlags_TypeDefault = 1 << 0,
ImGuiNavHighlightFlags_TypeThin = 1 << 1,
ImGuiNavHighlightFlags_AlwaysDraw = 1 << 2, // Draw rectangular highlight if (g.NavId == id) _even_ when using the mouse.
ImGuiNavHighlightFlags_NoRounding = 1 << 3
};
enum ImGuiNavDirSourceFlags_
{
ImGuiNavDirSourceFlags_None = 0,
ImGuiNavDirSourceFlags_Keyboard = 1 << 0,
ImGuiNavDirSourceFlags_PadDPad = 1 << 1,
ImGuiNavDirSourceFlags_PadLStick = 1 << 2
};
enum ImGuiNavMoveFlags_
{
ImGuiNavMoveFlags_None = 0,
ImGuiNavMoveFlags_LoopX = 1 << 0, // On failed request, restart from opposite side
ImGuiNavMoveFlags_LoopY = 1 << 1,
ImGuiNavMoveFlags_WrapX = 1 << 2, // On failed request, request from opposite side one line down (when NavDir==right) or one line up (when NavDir==left)
ImGuiNavMoveFlags_WrapY = 1 << 3, // This is not super useful for provided for completeness
ImGuiNavMoveFlags_AllowCurrentNavId = 1 << 4, // Allow scoring and considering the current NavId as a move target candidate. This is used when the move source is offset (e.g. pressing PageDown actually needs to send a Up move request, if we are pressing PageDown from the bottom-most item we need to stay in place)
ImGuiNavMoveFlags_AlsoScoreVisibleSet = 1 << 5 // Store alternate result in NavMoveResultLocalVisibleSet that only comprise elements that are already fully visible.
};
enum ImGuiNavForward
{
ImGuiNavForward_None,
ImGuiNavForward_ForwardQueued,
ImGuiNavForward_ForwardActive
};
enum ImGuiNavLayer
{
ImGuiNavLayer_Main = 0, // Main scrolling layer
ImGuiNavLayer_Menu = 1, // Menu layer (access with Alt/ImGuiNavInput_Menu)
ImGuiNavLayer_COUNT
};
enum ImGuiPopupPositionPolicy
{
ImGuiPopupPositionPolicy_Default,
ImGuiPopupPositionPolicy_ComboBox
};
// 1D vector (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches)
struct ImVec1
{
float x;
ImVec1() { x = 0.0f; }
ImVec1(float _x) { x = _x; }
};
// 2D axis aligned bounding-box
// NB: we can't rely on ImVec2 math operators being available here
struct IMGUI_API ImRect
{
ImVec2 Min; // Upper-left
ImVec2 Max; // Lower-right
ImRect() : Min(FLT_MAX,FLT_MAX), Max(-FLT_MAX,-FLT_MAX) {}
ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {}
ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {}
ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {}
ImVec2 GetCenter() const { return ImVec2((Min.x + Max.x) * 0.5f, (Min.y + Max.y) * 0.5f); }
ImVec2 GetSize() const { return ImVec2(Max.x - Min.x, Max.y - Min.y); }
float GetWidth() const { return Max.x - Min.x; }
float GetHeight() const { return Max.y - Min.y; }
ImVec2 GetTL() const { return Min; } // Top-left
ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right
ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left
ImVec2 GetBR() const { return Max; } // Bottom-right
bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; }
bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x <= Max.x && r.Max.y <= Max.y; }
bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; }
void Add(const ImVec2& p) { if (Min.x > p.x) Min.x = p.x; if (Min.y > p.y) Min.y = p.y; if (Max.x < p.x) Max.x = p.x; if (Max.y < p.y) Max.y = p.y; }
void Add(const ImRect& r) { if (Min.x > r.Min.x) Min.x = r.Min.x; if (Min.y > r.Min.y) Min.y = r.Min.y; if (Max.x < r.Max.x) Max.x = r.Max.x; if (Max.y < r.Max.y) Max.y = r.Max.y; }
void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; }
void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; }
void Translate(const ImVec2& d) { Min.x += d.x; Min.y += d.y; Max.x += d.x; Max.y += d.y; }
void TranslateX(float dx) { Min.x += dx; Max.x += dx; }
void TranslateY(float dy) { Min.y += dy; Max.y += dy; }
void ClipWith(const ImRect& r) { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display.
void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped.
void Floor() { Min.x = (float)(int)Min.x; Min.y = (float)(int)Min.y; Max.x = (float)(int)Max.x; Max.y = (float)(int)Max.y; }
bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; }
};
// Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo().
struct ImGuiDataTypeInfo
{
size_t Size; // Size in byte
const char* PrintFmt; // Default printf format for the type
const char* ScanFmt; // Default scanf format for the type
};
// Stacked color modifier, backup of modified data so we can restore it
struct ImGuiColorMod
{
ImGuiCol Col;
ImVec4 BackupValue;
};
// Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable.
struct ImGuiStyleMod
{
ImGuiStyleVar VarIdx;
union { int BackupInt[2]; float BackupFloat[2]; };
ImGuiStyleMod(ImGuiStyleVar idx, int v) { VarIdx = idx; BackupInt[0] = v; }
ImGuiStyleMod(ImGuiStyleVar idx, float v) { VarIdx = idx; BackupFloat[0] = v; }
ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; }
};
// Stacked storage data for BeginGroup()/EndGroup()
struct ImGuiGroupData
{
ImVec2 BackupCursorPos;
ImVec2 BackupCursorMaxPos;
ImVec1 BackupIndent;
ImVec1 BackupGroupOffset;
ImVec2 BackupCurrLineSize;
float BackupCurrLineTextBaseOffset;
ImGuiID BackupActiveIdIsAlive;
bool BackupActiveIdPreviousFrameIsAlive;
bool EmitItem;
};
// Simple column measurement, currently used for MenuItem() only.. This is very short-sighted/throw-away code and NOT a generic helper.
struct IMGUI_API ImGuiMenuColumns
{
float Spacing;
float Width, NextWidth;
float Pos[3], NextWidths[3];
ImGuiMenuColumns();
void Update(int count, float spacing, bool clear);
float DeclColumns(float w0, float w1, float w2);
float CalcExtraSpace(float avail_w);
};
// Internal state of the currently focused/edited text input box
struct IMGUI_API ImGuiInputTextState
{
ImGuiID ID; // widget id owning the text state
int CurLenW, CurLenA; // we need to maintain our buffer length in both UTF-8 and wchar format. UTF-8 len is valid even if TextA is not.
ImVector<ImWchar> TextW; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer.
ImVector<char> TextA; // temporary UTF8 buffer for callbacks and other operations. this is not updated in every code-path! size=capacity.
ImVector<char> InitialTextA; // backup of end-user buffer at the time of focus (in UTF-8, unaltered)
bool TextAIsValid; // temporary UTF8 buffer is not initially valid before we make the widget active (until then we pull the data from user argument)
int BufCapacityA; // end-user buffer capacity
float ScrollX; // horizontal scrolling/offset
ImStb::STB_TexteditState Stb; // state for stb_textedit.h
float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately
bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!)
bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection
ImGuiInputTextFlags UserFlags; // Temporarily set while we call user's callback
ImGuiInputTextCallback UserCallback; // "
void* UserCallbackData; // "
ImGuiInputTextState() { memset(this, 0, sizeof(*this)); }
void ClearText() { CurLenW = CurLenA = 0; TextW[0] = 0; TextA[0] = 0; CursorClamp(); }
void ClearFreeMemory() { TextW.clear(); TextA.clear(); InitialTextA.clear(); }
int GetUndoAvailCount() const { return Stb.undostate.undo_point; }
int GetRedoAvailCount() const { return STB_TEXTEDIT_UNDOSTATECOUNT - Stb.undostate.redo_point; }
void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation
// Cursor & Selection
void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking
void CursorClamp() { Stb.cursor = ImMin(Stb.cursor, CurLenW); Stb.select_start = ImMin(Stb.select_start, CurLenW); Stb.select_end = ImMin(Stb.select_end, CurLenW); }
bool HasSelection() const { return Stb.select_start != Stb.select_end; }
void ClearSelection() { Stb.select_start = Stb.select_end = Stb.cursor; }
void SelectAll() { Stb.select_start = 0; Stb.cursor = Stb.select_end = CurLenW; Stb.has_preferred_x = 0; }
};
// Windows data saved in imgui.ini file
struct ImGuiWindowSettings
{
char* Name;
ImGuiID ID;
ImVec2 Pos;
ImVec2 Size;
bool Collapsed;
ImGuiWindowSettings() { Name = NULL; ID = 0; Pos = Size = ImVec2(0,0); Collapsed = false; }
};
struct ImGuiSettingsHandler
{
const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']'
ImGuiID TypeHash; // == ImHashStr(TypeName)
void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]"
void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry
void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf'
void* UserData;
ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); }
};
// Storage for current popup stack
struct ImGuiPopupData
{
ImGuiID PopupId; // Set on OpenPopup()
ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup()
ImGuiWindow* SourceWindow; // Set on OpenPopup() copy of NavWindow at the time of opening the popup
int OpenFrameCount; // Set on OpenPopup()
ImGuiID OpenParentId; // Set on OpenPopup(), we need this to differentiate multiple menu sets from each others (e.g. inside menu bar vs loose menu items)
ImVec2 OpenPopupPos; // Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse)
ImVec2 OpenMousePos; // Set on OpenPopup(), copy of mouse position at the time of opening popup
ImGuiPopupData() { PopupId = 0; Window = SourceWindow = NULL; OpenFrameCount = -1; OpenParentId = 0; }
};
struct ImGuiColumnData
{
float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right)
float OffsetNormBeforeResize;
ImGuiColumnsFlags Flags; // Not exposed
ImRect ClipRect;
ImGuiColumnData() { OffsetNorm = OffsetNormBeforeResize = 0.0f; Flags = ImGuiColumnsFlags_None; }
};
struct ImGuiColumns
{
ImGuiID ID;
ImGuiColumnsFlags Flags;
bool IsFirstFrame;
bool IsBeingResized;
int Current;
int Count;
float OffMinX, OffMaxX; // Offsets from HostWorkRect.Min.x
float LineMinY, LineMaxY;
float HostCursorPosY; // Backup of CursorPos at the time of BeginColumns()
float HostCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns()
ImRect HostClipRect; // Backup of ClipRect at the time of BeginColumns()
ImRect HostWorkRect; // Backup of WorkRect at the time of BeginColumns()
ImVector<ImGuiColumnData> Columns;
ImGuiColumns() { Clear(); }
void Clear()
{
ID = 0;
Flags = ImGuiColumnsFlags_None;
IsFirstFrame = false;
IsBeingResized = false;
Current = 0;
Count = 1;
OffMinX = OffMaxX = 0.0f;
LineMinY = LineMaxY = 0.0f;
HostCursorPosY = 0.0f;
HostCursorMaxPosX = 0.0f;
Columns.clear();
}
};
// Data shared between all ImDrawList instances
struct IMGUI_API ImDrawListSharedData
{
ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas
ImFont* Font; // Current/default font (optional, for simplified AddText overload)
float FontSize; // Current/default font size (optional, for simplified AddText overload)
float CurveTessellationTol;
ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen()
ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards)
// Const data
// FIXME: Bake rounded corners fill/borders in atlas
ImVec2 CircleVtx12[12];
ImDrawListSharedData();
};
struct ImDrawDataBuilder
{
ImVector<ImDrawList*> Layers[2]; // Global layers for: regular, tooltip
void Clear() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].resize(0); }
void ClearFreeMemory() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].clear(); }
IMGUI_API void FlattenIntoSingleLayer();
};
struct ImGuiNavMoveResult
{
ImGuiID ID; // Best candidate
ImGuiID SelectScopeId;// Best candidate window current selectable group ID
ImGuiWindow* Window; // Best candidate window
float DistBox; // Best candidate box distance to current NavId
float DistCenter; // Best candidate center distance to current NavId
float DistAxial;
ImRect RectRel; // Best candidate bounding box in window relative space
ImGuiNavMoveResult() { Clear(); }
void Clear() { ID = SelectScopeId = 0; Window = NULL; DistBox = DistCenter = DistAxial = FLT_MAX; RectRel = ImRect(); }
};
enum ImGuiNextWindowDataFlags_
{
ImGuiNextWindowDataFlags_None = 0,
ImGuiNextWindowDataFlags_HasPos = 1 << 0,
ImGuiNextWindowDataFlags_HasSize = 1 << 1,
ImGuiNextWindowDataFlags_HasContentSize = 1 << 2,
ImGuiNextWindowDataFlags_HasCollapsed = 1 << 3,
ImGuiNextWindowDataFlags_HasSizeConstraint = 1 << 4,
ImGuiNextWindowDataFlags_HasFocus = 1 << 5,
ImGuiNextWindowDataFlags_HasBgAlpha = 1 << 6
};
// Storage for SetNexWindow** functions
struct ImGuiNextWindowData
{
ImGuiNextWindowDataFlags Flags;
ImGuiCond PosCond;
ImGuiCond SizeCond;
ImGuiCond CollapsedCond;
ImVec2 PosVal;
ImVec2 PosPivotVal;
ImVec2 SizeVal;
ImVec2 ContentSizeVal;
bool CollapsedVal;
ImRect SizeConstraintRect;
ImGuiSizeCallback SizeCallback;
void* SizeCallbackUserData;
float BgAlphaVal;
ImVec2 MenuBarOffsetMinVal; // *Always on* This is not exposed publicly, so we don't clear it.
ImGuiNextWindowData() { memset(this, 0, sizeof(*this)); }
inline void ClearFlags() { Flags = ImGuiNextWindowDataFlags_None; }
};
enum ImGuiNextItemDataFlags_
{
ImGuiNextItemDataFlags_None = 0,
ImGuiNextItemDataFlags_HasWidth = 1 << 0,
ImGuiNextItemDataFlags_HasOpen = 1 << 1
};
struct ImGuiNextItemData
{
ImGuiNextItemDataFlags Flags;
float Width; // Set by SetNextItemWidth().
bool OpenVal; // Set by SetNextItemOpen() function.
ImGuiCond OpenCond;
ImGuiNextItemData() { memset(this, 0, sizeof(*this)); }
inline void ClearFlags() { Flags = ImGuiNextItemDataFlags_None; }
};
//-----------------------------------------------------------------------------
// Tabs
//-----------------------------------------------------------------------------
struct ImGuiShrinkWidthItem
{
int Index;
float Width;
};
struct ImGuiPtrOrIndex
{
void* Ptr; // Either field can be set, not both. e.g. Dock node tab bars are loose while BeginTabBar() ones are in a pool.
int Index; // Usually index in a main pool.
ImGuiPtrOrIndex(void* ptr) { Ptr = ptr; Index = -1; }
ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; }
};
//-----------------------------------------------------------------------------
// Main imgui context
//-----------------------------------------------------------------------------
struct ImGuiContext
{
bool Initialized;
bool FrameScopeActive; // Set by NewFrame(), cleared by EndFrame()
bool FrameScopePushedImplicitWindow; // Set by NewFrame(), cleared by EndFrame()
bool FontAtlasOwnedByContext; // Io.Fonts-> is owned by the ImGuiContext and will be destructed along with it.
ImGuiIO IO;
ImGuiStyle Style;
ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back()
float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window.
float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height.
ImDrawListSharedData DrawListSharedData;
double Time;
int FrameCount;
int FrameCountEnded;
int FrameCountRendered;
// Windows state
ImVector<ImGuiWindow*> Windows; // Windows, sorted in display order, back to front
ImVector<ImGuiWindow*> WindowsFocusOrder; // Windows, sorted in focus order, back to front
ImVector<ImGuiWindow*> WindowsSortBuffer;
ImVector<ImGuiWindow*> CurrentWindowStack;
ImGuiStorage WindowsById;
int WindowsActiveCount;
ImGuiWindow* CurrentWindow; // Being drawn into
ImGuiWindow* HoveredWindow; // Will catch mouse inputs
ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only)
ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actually window that is moved is generally MovingWindow->RootWindow.
ImGuiWindow* WheelingWindow;
ImVec2 WheelingWindowRefMousePos;
float WheelingWindowTimer;
// Item/widgets state and tracking information
ImGuiID HoveredId; // Hovered widget
bool HoveredIdAllowOverlap;
ImGuiID HoveredIdPreviousFrame;
float HoveredIdTimer; // Measure contiguous hovering time
float HoveredIdNotActiveTimer; // Measure contiguous hovering time where the item has not been active
ImGuiID ActiveId; // Active widget
ImGuiID ActiveIdIsAlive; // Active widget has been seen this frame (we can't use a bool as the ActiveId may change within the frame)
float ActiveIdTimer;
bool ActiveIdIsJustActivated; // Set at the time of activation for one frame
bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always)
bool ActiveIdHasBeenPressedBefore; // Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch.
bool ActiveIdHasBeenEditedBefore; // Was the value associated to the widget Edited over the course of the Active state.
bool ActiveIdHasBeenEditedThisFrame;
int ActiveIdAllowNavDirFlags; // Active widget allows using directional navigation (e.g. can activate a button and move away from it)
int ActiveIdBlockNavInputFlags;
ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior)
ImGuiWindow* ActiveIdWindow;
ImGuiInputSource ActiveIdSource; // Activating with mouse or nav (gamepad/keyboard)
ImGuiID ActiveIdPreviousFrame;
bool ActiveIdPreviousFrameIsAlive;
bool ActiveIdPreviousFrameHasBeenEditedBefore;
ImGuiWindow* ActiveIdPreviousFrameWindow;
ImGuiID LastActiveId; // Store the last non-zero ActiveId, useful for animation.
float LastActiveIdTimer; // Store the last non-zero ActiveId timer since the beginning of activation, useful for animation.
// Next window/item data
ImGuiNextWindowData NextWindowData; // Storage for SetNextWindow** functions
ImGuiNextItemData NextItemData; // Storage for SetNextItem** functions
// Shared stacks
ImVector<ImGuiColorMod> ColorModifiers; // Stack for PushStyleColor()/PopStyleColor()
ImVector<ImGuiStyleMod> StyleModifiers; // Stack for PushStyleVar()/PopStyleVar()
ImVector<ImFont*> FontStack; // Stack for PushFont()/PopFont()
ImVector<ImGuiPopupData>OpenPopupStack; // Which popups are open (persistent)
ImVector<ImGuiPopupData>BeginPopupStack; // Which level of BeginPopup() we are in (reset every frame)
// Navigation data (for gamepad/keyboard)
ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusWindow'
ImGuiID NavId; // Focused item for navigation
ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0, also set when calling ActivateItem()
ImGuiID NavActivateDownId; // ~~ IsNavInputDown(ImGuiNavInput_Activate) ? NavId : 0
ImGuiID NavActivatePressedId; // ~~ IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0
ImGuiID NavInputId; // ~~ IsNavInputPressed(ImGuiNavInput_Input) ? NavId : 0
ImGuiID NavJustTabbedId; // Just tabbed to this id.
ImGuiID NavJustMovedToId; // Just navigated to this id (result of a successfully MoveRequest).
ImGuiID NavJustMovedToMultiSelectScopeId; // Just navigated to this select scope id (result of a successfully MoveRequest).
ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame.
ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS WILL ONLY BE None or NavGamepad or NavKeyboard.
ImRect NavScoringRectScreen; // Rectangle used for scoring, in screen space. Based of window->DC.NavRefRectRel[], modified for directional navigation scoring.
int NavScoringCount; // Metrics for debugging
ImGuiWindow* NavWindowingTarget; // When selecting a window (holding Menu+FocusPrev/Next, or equivalent of CTRL-TAB) this window is temporarily displayed top-most.
ImGuiWindow* NavWindowingTargetAnim; // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f
ImGuiWindow* NavWindowingList;
float NavWindowingTimer;
float NavWindowingHighlightAlpha;
bool NavWindowingToggleLayer;
ImGuiNavLayer NavLayer; // Layer we are navigating on. For now the system is hard-coded for 0=main contents and 1=menu/title bar, may expose layers later.
int NavIdTabCounter; // == NavWindow->DC.FocusIdxTabCounter at time of NavId processing
bool NavIdIsAlive; // Nav widget has been seen this frame ~~ NavRefRectRel is valid
bool NavMousePosDirty; // When set we will update mouse position if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) if set (NB: this not enabled by default)
bool NavDisableHighlight; // When user starts using mouse, we hide gamepad/keyboard highlight (NB: but they are still available, which is why NavDisableHighlight isn't always != NavDisableMouseHover)
bool NavDisableMouseHover; // When user starts using gamepad/keyboard, we hide mouse hovering highlight until mouse is touched again.
bool NavAnyRequest; // ~~ NavMoveRequest || NavInitRequest
bool NavInitRequest; // Init request for appearing window to select first item
bool NavInitRequestFromMove;
ImGuiID NavInitResultId;
ImRect NavInitResultRectRel;
bool NavMoveFromClampedRefRect; // Set by manual scrolling, if we scroll to a point where NavId isn't visible we reset navigation from visible items
bool NavMoveRequest; // Move request for this frame
ImGuiNavMoveFlags NavMoveRequestFlags;
ImGuiNavForward NavMoveRequestForward; // None / ForwardQueued / ForwardActive (this is used to navigate sibling parent menus from a child menu)
ImGuiDir NavMoveDir, NavMoveDirLast; // Direction of the move request (left/right/up/down), direction of the previous move request
ImGuiDir NavMoveClipDir;
ImGuiNavMoveResult NavMoveResultLocal; // Best move request candidate within NavWindow
ImGuiNavMoveResult NavMoveResultLocalVisibleSet; // Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags_AlsoScoreVisibleSet flag)
ImGuiNavMoveResult NavMoveResultOther; // Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags_NavFlattened flag)
// Tabbing system (older than Nav, active even if Nav is disabled. FIXME-NAV: This needs a redesign!)
ImGuiWindow* FocusRequestCurrWindow; //
ImGuiWindow* FocusRequestNextWindow; //
int FocusRequestCurrCounterAll; // Any item being requested for focus, stored as an index (we on layout to be stable between the frame pressing TAB and the next frame, semi-ouch)
int FocusRequestCurrCounterTab; // Tab item being requested for focus, stored as an index
int FocusRequestNextCounterAll; // Stored for next frame
int FocusRequestNextCounterTab; // "
bool FocusTabPressed; //
// Render
ImDrawData DrawData; // Main ImDrawData instance to pass render information to the user
ImDrawDataBuilder DrawDataBuilder;
float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list)
ImDrawList BackgroundDrawList; // First draw list to be rendered.
ImDrawList ForegroundDrawList; // Last draw list to be rendered. This is where we the render software mouse cursor (if io.MouseDrawCursor is set) and most debug overlays.
ImGuiMouseCursor MouseCursor;
// Drag and Drop
bool DragDropActive;
bool DragDropWithinSourceOrTarget;
ImGuiDragDropFlags DragDropSourceFlags;
int DragDropSourceFrameCount;
int DragDropMouseButton;
ImGuiPayload DragDropPayload;
ImRect DragDropTargetRect;
ImGuiID DragDropTargetId;
ImGuiDragDropFlags DragDropAcceptFlags;
float DragDropAcceptIdCurrRectSurface; // Target item surface (we resolve overlapping targets by prioritizing the smaller surface)
ImGuiID DragDropAcceptIdCurr; // Target item id (set at the time of accepting the payload)
ImGuiID DragDropAcceptIdPrev; // Target item id from previous frame (we need to store this to allow for overlapping drag and drop targets)
int DragDropAcceptFrameCount; // Last time a target expressed a desire to accept the source
ImVector<unsigned char> DragDropPayloadBufHeap; // We don't expose the ImVector<> directly
unsigned char DragDropPayloadBufLocal[8]; // Local buffer for small payloads
// Tab bars
ImGuiTabBar* CurrentTabBar;
ImPool<ImGuiTabBar> TabBars;
ImVector<ImGuiPtrOrIndex> CurrentTabBarStack;
ImVector<ImGuiShrinkWidthItem> ShrinkWidthBuffer;
// Widget state
ImVec2 LastValidMousePos;
ImGuiInputTextState InputTextState;
ImFont InputTextPasswordFont;
ImGuiID TempInputTextId; // Temporary text input when CTRL+clicking on a slider, etc.
ImGuiColorEditFlags ColorEditOptions; // Store user options for color edit widgets
ImVec4 ColorPickerRef;
bool DragCurrentAccumDirty;
float DragCurrentAccum; // Accumulator for dragging modification. Always high-precision, not rounded by end-user precision settings
float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio
float ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage?
int TooltipOverrideCount;
ImVector<char> PrivateClipboard; // If no custom clipboard handler is defined
// Range-Select/Multi-Select
// [This is unused in this branch, but left here to facilitate merging/syncing multiple branches]
ImGuiID MultiSelectScopeId;
// Platform support
ImVec2 PlatformImePos; // Cursor position request & last passed to the OS Input Method Editor
ImVec2 PlatformImeLastPos;
// Settings
bool SettingsLoaded;
float SettingsDirtyTimer; // Save .ini Settings to memory when time reaches zero
ImGuiTextBuffer SettingsIniData; // In memory .ini settings
ImVector<ImGuiSettingsHandler> SettingsHandlers; // List of .ini settings handlers
ImVector<ImGuiWindowSettings> SettingsWindows; // ImGuiWindow .ini settings entries (parsed from the last loaded .ini file and maintained on saving)
// Logging
bool LogEnabled;
ImGuiLogType LogType;
FILE* LogFile; // If != NULL log to stdout/ file
ImGuiTextBuffer LogBuffer; // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators.
float LogLinePosY;
bool LogLineFirstItem;
int LogDepthRef;
int LogDepthToExpand;
int LogDepthToExpandDefault; // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call.
// Debug Tools
bool DebugItemPickerActive;
ImGuiID DebugItemPickerBreakID; // Will call IM_DEBUG_BREAK() when encountering this id
// Misc
float FramerateSecPerFrame[120]; // Calculate estimate of framerate for user over the last 2 seconds.
int FramerateSecPerFrameIdx;
float FramerateSecPerFrameAccum;
int WantCaptureMouseNextFrame; // Explicit capture via CaptureKeyboardFromApp()/CaptureMouseFromApp() sets those flags
int WantCaptureKeyboardNextFrame;
int WantTextInputNextFrame;
char TempBuffer[1024*3+1]; // Temporary text buffer
ImGuiContext(ImFontAtlas* shared_font_atlas) : BackgroundDrawList(&DrawListSharedData), ForegroundDrawList(&DrawListSharedData)
{
Initialized = false;
FrameScopeActive = FrameScopePushedImplicitWindow = false;
Font = NULL;
FontSize = FontBaseSize = 0.0f;
FontAtlasOwnedByContext = shared_font_atlas ? false : true;
IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)();
Time = 0.0f;
FrameCount = 0;
FrameCountEnded = FrameCountRendered = -1;
WindowsActiveCount = 0;
CurrentWindow = NULL;
HoveredWindow = NULL;
HoveredRootWindow = NULL;
MovingWindow = NULL;
WheelingWindow = NULL;
WheelingWindowTimer = 0.0f;
HoveredId = 0;
HoveredIdAllowOverlap = false;
HoveredIdPreviousFrame = 0;
HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f;
ActiveId = 0;
ActiveIdIsAlive = 0;
ActiveIdTimer = 0.0f;
ActiveIdIsJustActivated = false;
ActiveIdAllowOverlap = false;
ActiveIdHasBeenPressedBefore = false;
ActiveIdHasBeenEditedBefore = false;
ActiveIdHasBeenEditedThisFrame = false;
ActiveIdAllowNavDirFlags = 0x00;
ActiveIdBlockNavInputFlags = 0x00;
ActiveIdClickOffset = ImVec2(-1,-1);
ActiveIdWindow = NULL;
ActiveIdSource = ImGuiInputSource_None;
ActiveIdPreviousFrame = 0;
ActiveIdPreviousFrameIsAlive = false;
ActiveIdPreviousFrameHasBeenEditedBefore = false;
ActiveIdPreviousFrameWindow = NULL;
LastActiveId = 0;
LastActiveIdTimer = 0.0f;
NavWindow = NULL;
NavId = NavActivateId = NavActivateDownId = NavActivatePressedId = NavInputId = 0;
NavJustTabbedId = NavJustMovedToId = NavJustMovedToMultiSelectScopeId = NavNextActivateId = 0;
NavInputSource = ImGuiInputSource_None;
NavScoringRectScreen = ImRect();
NavScoringCount = 0;
NavWindowingTarget = NavWindowingTargetAnim = NavWindowingList = NULL;
NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f;
NavWindowingToggleLayer = false;
NavLayer = ImGuiNavLayer_Main;
NavIdTabCounter = INT_MAX;
NavIdIsAlive = false;
NavMousePosDirty = false;
NavDisableHighlight = true;
NavDisableMouseHover = false;
NavAnyRequest = false;
NavInitRequest = false;
NavInitRequestFromMove = false;
NavInitResultId = 0;
NavMoveFromClampedRefRect = false;
NavMoveRequest = false;
NavMoveRequestFlags = 0;
NavMoveRequestForward = ImGuiNavForward_None;
NavMoveDir = NavMoveDirLast = NavMoveClipDir = ImGuiDir_None;
FocusRequestCurrWindow = FocusRequestNextWindow = NULL;
FocusRequestCurrCounterAll = FocusRequestCurrCounterTab = INT_MAX;
FocusRequestNextCounterAll = FocusRequestNextCounterTab = INT_MAX;
FocusTabPressed = false;
DimBgRatio = 0.0f;
BackgroundDrawList._OwnerName = "##Background"; // Give it a name for debugging
ForegroundDrawList._OwnerName = "##Foreground"; // Give it a name for debugging
MouseCursor = ImGuiMouseCursor_Arrow;
DragDropActive = DragDropWithinSourceOrTarget = false;
DragDropSourceFlags = 0;
DragDropSourceFrameCount = -1;
DragDropMouseButton = -1;
DragDropTargetId = 0;
DragDropAcceptFlags = 0;
DragDropAcceptIdCurrRectSurface = 0.0f;
DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0;
DragDropAcceptFrameCount = -1;
memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal));
CurrentTabBar = NULL;
LastValidMousePos = ImVec2(0.0f, 0.0f);
TempInputTextId = 0;
ColorEditOptions = ImGuiColorEditFlags__OptionsDefault;
DragCurrentAccumDirty = false;
DragCurrentAccum = 0.0f;
DragSpeedDefaultRatio = 1.0f / 100.0f;
ScrollbarClickDeltaToGrabCenter = 0.0f;
TooltipOverrideCount = 0;
MultiSelectScopeId = 0;
PlatformImePos = PlatformImeLastPos = ImVec2(FLT_MAX, FLT_MAX);
SettingsLoaded = false;
SettingsDirtyTimer = 0.0f;
LogEnabled = false;
LogType = ImGuiLogType_None;
LogFile = NULL;
LogLinePosY = FLT_MAX;
LogLineFirstItem = false;
LogDepthRef = 0;
LogDepthToExpand = LogDepthToExpandDefault = 2;
DebugItemPickerActive = false;
DebugItemPickerBreakID = 0;
memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame));
FramerateSecPerFrameIdx = 0;
FramerateSecPerFrameAccum = 0.0f;
WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1;
memset(TempBuffer, 0, sizeof(TempBuffer));
}
};
//-----------------------------------------------------------------------------
// ImGuiWindow
//-----------------------------------------------------------------------------
// Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow.
// FIXME: That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered.
struct IMGUI_API ImGuiWindowTempData
{
ImVec2 CursorPos;
ImVec2 CursorPosPrevLine;
ImVec2 CursorStartPos; // Initial position in client area with padding
ImVec2 CursorMaxPos; // Used to implicitly calculate the size of our contents, always growing during the frame. Used to calculate window->ContentSize at the beginning of next frame
ImVec2 CurrLineSize;
ImVec2 PrevLineSize;
float CurrLineTextBaseOffset;
float PrevLineTextBaseOffset;
int TreeDepth;
ImU32 TreeStoreMayJumpToParentOnPop; // Store a copy of !g.NavIdIsAlive for TreeDepth 0..31.. Could be turned into a ImU64 if necessary.
ImGuiID LastItemId;
ImGuiItemStatusFlags LastItemStatusFlags;
ImRect LastItemRect; // Interaction rect
ImRect LastItemDisplayRect; // End-user display rect (only valid if LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect)
ImGuiNavLayer NavLayerCurrent; // Current layer, 0..31 (we currently only use 0..1)
int NavLayerCurrentMask; // = (1 << NavLayerCurrent) used by ItemAdd prior to clipping.
int NavLayerActiveMask; // Which layer have been written to (result from previous frame)
int NavLayerActiveMaskNext; // Which layer have been written to (buffer for current frame)
bool NavHideHighlightOneFrame;
bool NavHasScroll; // Set when scrolling can be used (ScrollMax > 0.0f)
bool MenuBarAppending; // FIXME: Remove this
ImVec2 MenuBarOffset; // MenuBarOffset.x is sort of equivalent of a per-layer CursorPos.x, saved/restored as we switch to the menu bar. The only situation when MenuBarOffset.y is > 0 if when (SafeAreaPadding.y > FramePadding.y), often used on TVs.
ImVector<ImGuiWindow*> ChildWindows;
ImGuiStorage* StateStorage;
ImGuiLayoutType LayoutType;
ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin()
int FocusCounterAll; // Counter for focus/tabbing system. Start at -1 and increase as assigned via FocusableItemRegister() (FIXME-NAV: Needs redesign)
int FocusCounterTab; // (same, but only count widgets which you can Tab through)
// We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings.
ImGuiItemFlags ItemFlags; // == ItemFlagsStack.back() [empty == ImGuiItemFlags_Default]
float ItemWidth; // == ItemWidthStack.back(). 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window
float TextWrapPos; // == TextWrapPosStack.back() [empty == -1.0f]
ImVector<ImGuiItemFlags>ItemFlagsStack;
ImVector<float> ItemWidthStack;
ImVector<float> TextWrapPosStack;
ImVector<ImGuiGroupData>GroupStack;
short StackSizesBackup[6]; // Store size of various stacks for asserting
ImVec1 Indent; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.)
ImVec1 GroupOffset;
ImVec1 ColumnsOffset; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API.
ImGuiColumns* CurrentColumns; // Current columns set
ImGuiWindowTempData()
{
CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f);
CurrLineSize = PrevLineSize = ImVec2(0.0f, 0.0f);
CurrLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f;
TreeDepth = 0;
TreeStoreMayJumpToParentOnPop = 0x00;
LastItemId = 0;
LastItemStatusFlags = 0;
LastItemRect = LastItemDisplayRect = ImRect();
NavLayerActiveMask = NavLayerActiveMaskNext = 0x00;
NavLayerCurrent = ImGuiNavLayer_Main;
NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
NavHideHighlightOneFrame = false;
NavHasScroll = false;
MenuBarAppending = false;
MenuBarOffset = ImVec2(0.0f, 0.0f);
StateStorage = NULL;
LayoutType = ParentLayoutType = ImGuiLayoutType_Vertical;
FocusCounterAll = FocusCounterTab = -1;
ItemFlags = ImGuiItemFlags_Default_;
ItemWidth = 0.0f;
TextWrapPos = -1.0f;
memset(StackSizesBackup, 0, sizeof(StackSizesBackup));
Indent = ImVec1(0.0f);
GroupOffset = ImVec1(0.0f);
ColumnsOffset = ImVec1(0.0f);
CurrentColumns = NULL;
}
};
// Storage for one window
struct IMGUI_API ImGuiWindow
{
char* Name;
ImGuiID ID; // == ImHash(Name)
ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_
ImVec2 Pos; // Position (always rounded-up to nearest pixel)
ImVec2 Size; // Current size (==SizeFull or collapsed title bar size)
ImVec2 SizeFull; // Size when non collapsed
ImVec2 ContentSize; // Size of contents/scrollable client area (calculated from the extents reach of the cursor) from previous frame. Does not include window decoration or window padding.
ImVec2 ContentSizeExplicit; // Size of contents/scrollable client area explicitly request by the user via SetNextWindowContentSize().
ImVec2 WindowPadding; // Window padding at the time of begin.
float WindowRounding; // Window rounding at the time of begin.
float WindowBorderSize; // Window border size at the time of begin.
int NameBufLen; // Size of buffer storing Name. May be larger than strlen(Name)!
ImGuiID MoveId; // == window->GetID("#MOVE")
ImGuiID ChildId; // ID of corresponding item in parent window (for navigation to return from child window to parent window)
ImVec2 Scroll;
ImVec2 ScrollMax;
ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change)
ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered
ImVec2 ScrollbarSizes; // Size taken by scrollbars on each axis
bool ScrollbarX, ScrollbarY;
bool Active; // Set to true on Begin(), unless Collapsed
bool WasActive;
bool WriteAccessed; // Set to true when any widget access the current window
bool Collapsed; // Set when collapsing window to become only title-bar
bool WantCollapseToggle;
bool SkipItems; // Set when items can safely be all clipped (e.g. window not visible or collapsed)
bool Appearing; // Set during the frame where the window is appearing (or re-appearing)
bool Hidden; // Do not display (== (HiddenFrames*** > 0))
bool HasCloseButton; // Set when the window has a close button (p_open != NULL)
signed char ResizeBorderHeld; // Current border being held for resize (-1: none, otherwise 0-3)
short BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs)
short BeginOrderWithinParent; // Order within immediate parent window, if we are a child window. Otherwise 0.
short BeginOrderWithinContext; // Order within entire imgui context. This is mostly used for debugging submission order related issues.
ImGuiID PopupId; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling)
int AutoFitFramesX, AutoFitFramesY;
bool AutoFitOnlyGrows;
int AutoFitChildAxises;
ImGuiDir AutoPosLastDirection;
int HiddenFramesCanSkipItems; // Hide the window for N frames
int HiddenFramesCannotSkipItems; // Hide the window for N frames while allowing items to be submitted so we can measure their size
ImGuiCond SetWindowPosAllowFlags; // store acceptable condition flags for SetNextWindowPos() use.
ImGuiCond SetWindowSizeAllowFlags; // store acceptable condition flags for SetNextWindowSize() use.
ImGuiCond SetWindowCollapsedAllowFlags; // store acceptable condition flags for SetNextWindowCollapsed() use.
ImVec2 SetWindowPosVal; // store window position when using a non-zero Pivot (position set needs to be processed when we know the window size)
ImVec2 SetWindowPosPivot; // store window pivot for positioning. ImVec2(0,0) when positioning from top-left corner; ImVec2(0.5f,0.5f) for centering; ImVec2(1,1) for bottom right.
ImGuiWindowTempData DC; // Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name.
ImVector<ImGuiID> IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack
// The best way to understand what those rectangles are is to use the 'Metrics -> Tools -> Show windows rectangles' viewer.
// The main 'OuterRect', omitted as a field, is window->Rect().
ImRect OuterRectClipped; // == Window->Rect() just after setup in Begin(). == window->Rect() for root window.
ImRect InnerRect; // Inner rectangle (omit title bar, menu bar, scroll bar)
ImRect InnerClipRect; // == InnerRect shrunk by WindowPadding*0.5f on each side, clipped within viewport or parent clip rect.
ImRect WorkRect; // Cover the whole scrolling region, shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentsRegionRect over time (from 1.71+ onward).
ImRect ClipRect; // Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList->clip_rect_stack.back().
ImRect ContentsRegionRect; // FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on.
int LastFrameActive; // Last frame number the window was Active.
float ItemWidthDefault;
ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items
ImGuiStorage StateStorage;
ImVector<ImGuiColumns> ColumnsStorage;
float FontWindowScale; // User scale multiplier per-window, via SetWindowFontScale()
int SettingsIdx; // Index into SettingsWindow[] (indices are always valid as we only grow the array from the back)
ImDrawList* DrawList; // == &DrawListInst (for backward compatibility reason with code using imgui_internal.h we keep this a pointer)
ImDrawList DrawListInst;
ImGuiWindow* ParentWindow; // If we are a child _or_ popup window, this is pointing to our parent. Otherwise NULL.
ImGuiWindow* RootWindow; // Point to ourself or first ancestor that is not a child window.
ImGuiWindow* RootWindowForTitleBarHighlight; // Point to ourself or first ancestor which will display TitleBgActive color when this window is active.
ImGuiWindow* RootWindowForNav; // Point to ourself or first ancestor which doesn't have the NavFlattened flag.
ImGuiWindow* NavLastChildNavWindow; // When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.)
ImGuiID NavLastIds[ImGuiNavLayer_COUNT]; // Last known NavId for this window, per layer (0/1)
ImRect NavRectRel[ImGuiNavLayer_COUNT]; // Reference rectangle, in window relative space
public:
ImGuiWindow(ImGuiContext* context, const char* name);
~ImGuiWindow();
ImGuiID GetID(const char* str, const char* str_end = NULL);
ImGuiID GetID(const void* ptr);
ImGuiID GetID(int n);
ImGuiID GetIDNoKeepAlive(const char* str, const char* str_end = NULL);
ImGuiID GetIDNoKeepAlive(const void* ptr);
ImGuiID GetIDNoKeepAlive(int n);
ImGuiID GetIDFromRectangle(const ImRect& r_abs);
// We don't use g.FontSize because the window may be != g.CurrentWidow.
ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); }
float CalcFontSize() const { ImGuiContext& g = *GImGui; float scale = g.FontBaseSize * FontWindowScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; }
float TitleBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + g.Style.FramePadding.y * 2.0f; }
ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); }
float MenuBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_MenuBar) ? DC.MenuBarOffset.y + CalcFontSize() + g.Style.FramePadding.y * 2.0f : 0.0f; }
ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); }
};
// Backup and restore just enough data to be able to use IsItemHovered() on item A after another B in the same window has overwritten the data.
struct ImGuiItemHoveredDataBackup
{
ImGuiID LastItemId;
ImGuiItemStatusFlags LastItemStatusFlags;
ImRect LastItemRect;
ImRect LastItemDisplayRect;
ImGuiItemHoveredDataBackup() { Backup(); }
void Backup() { ImGuiWindow* window = GImGui->CurrentWindow; LastItemId = window->DC.LastItemId; LastItemStatusFlags = window->DC.LastItemStatusFlags; LastItemRect = window->DC.LastItemRect; LastItemDisplayRect = window->DC.LastItemDisplayRect; }
void Restore() const { ImGuiWindow* window = GImGui->CurrentWindow; window->DC.LastItemId = LastItemId; window->DC.LastItemStatusFlags = LastItemStatusFlags; window->DC.LastItemRect = LastItemRect; window->DC.LastItemDisplayRect = LastItemDisplayRect; }
};
//-----------------------------------------------------------------------------
// Tab bar, tab item
//-----------------------------------------------------------------------------
// Extend ImGuiTabBarFlags_
enum ImGuiTabBarFlagsPrivate_
{
ImGuiTabBarFlags_DockNode = 1 << 20, // Part of a dock node [we don't use this in the master branch but it facilitate branch syncing to keep this around]
ImGuiTabBarFlags_IsFocused = 1 << 21,
ImGuiTabBarFlags_SaveSettings = 1 << 22 // FIXME: Settings are handled by the docking system, this only request the tab bar to mark settings dirty when reordering tabs
};
// Extend ImGuiTabItemFlags_
enum ImGuiTabItemFlagsPrivate_
{
ImGuiTabItemFlags_NoCloseButton = 1 << 20 // Store whether p_open is set or not, which we need to recompute WidthContents during layout.
};
// Storage for one active tab item (sizeof() 26~32 bytes)
struct ImGuiTabItem
{
ImGuiID ID;
ImGuiTabItemFlags Flags;
int LastFrameVisible;
int LastFrameSelected; // This allows us to infer an ordered list of the last activated tabs with little maintenance
int NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames
float Offset; // Position relative to beginning of tab
float Width; // Width currently displayed
float WidthContents; // Width of actual contents, stored during BeginTabItem() call
ImGuiTabItem() { ID = Flags = 0; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = WidthContents = 0.0f; }
};
// Storage for a tab bar (sizeof() 92~96 bytes)
struct ImGuiTabBar
{
ImVector<ImGuiTabItem> Tabs;
ImGuiID ID; // Zero for tab-bars used by docking
ImGuiID SelectedTabId; // Selected tab
ImGuiID NextSelectedTabId;
ImGuiID VisibleTabId; // Can occasionally be != SelectedTabId (e.g. when previewing contents for CTRL+TAB preview)
int CurrFrameVisible;
int PrevFrameVisible;
ImRect BarRect;
float ContentsHeight;
float OffsetMax; // Distance from BarRect.Min.x, locked during layout
float OffsetNextTab; // Distance from BarRect.Min.x, incremented with each BeginTabItem() call, not used if ImGuiTabBarFlags_Reorderable if set.
float ScrollingAnim;
float ScrollingTarget;
float ScrollingTargetDistToVisibility;
float ScrollingSpeed;
ImGuiTabBarFlags Flags;
ImGuiID ReorderRequestTabId;
ImS8 ReorderRequestDir;
bool WantLayout;
bool VisibleTabWasSubmitted;
short LastTabItemIdx; // For BeginTabItem()/EndTabItem()
ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar()
ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer.
ImGuiTabBar();
int GetTabOrder(const ImGuiTabItem* tab) const { return Tabs.index_from_ptr(tab); }
const char* GetTabName(const ImGuiTabItem* tab) const
{
IM_ASSERT(tab->NameOffset != -1 && tab->NameOffset < TabsNames.Buf.Size);
return TabsNames.Buf.Data + tab->NameOffset;
}
};
//-----------------------------------------------------------------------------
// Internal API
// No guarantee of forward compatibility here.
//-----------------------------------------------------------------------------
namespace ImGui
{
// We should always have a CurrentWindow in the stack (there is an implicit "Debug" window)
// If this ever crash because g.CurrentWindow is NULL it means that either
// - ImGui::NewFrame() has never been called, which is illegal.
// - You are calling ImGui functions after ImGui::EndFrame()/ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal.
inline ImGuiWindow* GetCurrentWindowRead() { ImGuiContext& g = *GImGui; return g.CurrentWindow; }
inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->WriteAccessed = true; return g.CurrentWindow; }
IMGUI_API ImGuiWindow* FindWindowByID(ImGuiID id);
IMGUI_API ImGuiWindow* FindWindowByName(const char* name);
IMGUI_API void FocusWindow(ImGuiWindow* window);
IMGUI_API void FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window);
IMGUI_API void BringWindowToFocusFront(ImGuiWindow* window);
IMGUI_API void BringWindowToDisplayFront(ImGuiWindow* window);
IMGUI_API void BringWindowToDisplayBack(ImGuiWindow* window);
IMGUI_API void UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window);
IMGUI_API ImVec2 CalcWindowExpectedSize(ImGuiWindow* window);
IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent);
IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window);
IMGUI_API ImRect GetWindowAllowedExtentRect(ImGuiWindow* window);
IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0);
IMGUI_API void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond = 0);
IMGUI_API void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond = 0);
IMGUI_API void SetCurrentFont(ImFont* font);
inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; }
// Init
IMGUI_API void Initialize(ImGuiContext* context);
IMGUI_API void Shutdown(ImGuiContext* context); // Since 1.60 this is a _private_ function. You can call DestroyContext() to destroy the context created by CreateContext().
// NewFrame
IMGUI_API void UpdateHoveredWindowAndCaptureFlags();
IMGUI_API void StartMouseMovingWindow(ImGuiWindow* window);
IMGUI_API void UpdateMouseMovingWindowNewFrame();
IMGUI_API void UpdateMouseMovingWindowEndFrame();
// Settings
IMGUI_API void MarkIniSettingsDirty();
IMGUI_API void MarkIniSettingsDirty(ImGuiWindow* window);
IMGUI_API ImGuiWindowSettings* CreateNewWindowSettings(const char* name);
IMGUI_API ImGuiWindowSettings* FindWindowSettings(ImGuiID id);
IMGUI_API ImGuiWindowSettings* FindOrCreateWindowSettings(const char* name);
IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(const char* type_name);
// Scrolling
IMGUI_API void SetScrollX(ImGuiWindow* window, float new_scroll_x);
IMGUI_API void SetScrollY(ImGuiWindow* window, float new_scroll_y);
IMGUI_API void SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio = 0.5f);
IMGUI_API void SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio = 0.5f);
IMGUI_API ImVec2 ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect);
// Basic Accessors
inline ImGuiID GetItemID() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemId; }
inline ImGuiID GetActiveID() { ImGuiContext& g = *GImGui; return g.ActiveId; }
inline ImGuiID GetFocusID() { ImGuiContext& g = *GImGui; return g.NavId; }
IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window);
IMGUI_API void SetFocusID(ImGuiID id, ImGuiWindow* window);
IMGUI_API void ClearActiveID();
IMGUI_API ImGuiID GetHoveredID();
IMGUI_API void SetHoveredID(ImGuiID id);
IMGUI_API void KeepAliveID(ImGuiID id);
IMGUI_API void MarkItemEdited(ImGuiID id);
IMGUI_API void PushOverrideID(ImGuiID id);
// Basic Helpers for widget code
IMGUI_API void ItemSize(const ImVec2& size, float text_offset_y = 0.0f);
IMGUI_API void ItemSize(const ImRect& bb, float text_offset_y = 0.0f);
IMGUI_API bool ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb = NULL);
IMGUI_API bool ItemHoverable(const ImRect& bb, ImGuiID id);
IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged);
IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id); // Return true if focus is requested
IMGUI_API void FocusableItemUnregister(ImGuiWindow* window);
IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h);
IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x);
IMGUI_API void PushMultiItemsWidths(int components, float width_full);
IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled);
IMGUI_API void PopItemFlag();
IMGUI_API bool IsItemToggledSelection(); // Was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly)
IMGUI_API ImVec2 GetContentRegionMaxAbs();
IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess);
// Logging/Capture
IMGUI_API void LogBegin(ImGuiLogType type, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name.
IMGUI_API void LogToBuffer(int auto_open_depth = -1); // Start logging/capturing to internal buffer
// Popups, Modals, Tooltips
IMGUI_API void OpenPopupEx(ImGuiID id);
IMGUI_API void ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup);
IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup);
IMGUI_API bool IsPopupOpen(ImGuiID id); // Test for id within current popup stack level (currently begin-ed into); this doesn't scan the whole popup stack!
IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags);
IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip = true);
IMGUI_API ImGuiWindow* GetTopMostPopupModal();
IMGUI_API ImVec2 FindBestWindowPosForPopup(ImGuiWindow* window);
IMGUI_API ImVec2 FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy = ImGuiPopupPositionPolicy_Default);
// Navigation
IMGUI_API void NavInitWindow(ImGuiWindow* window, bool force_reinit);
IMGUI_API bool NavMoveRequestButNoResultYet();
IMGUI_API void NavMoveRequestCancel();
IMGUI_API void NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags);
IMGUI_API void NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags);
IMGUI_API float GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode);
IMGUI_API ImVec2 GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor = 0.0f, float fast_factor = 0.0f);
IMGUI_API int CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate);
IMGUI_API void ActivateItem(ImGuiID id); // Remotely activate a button, checkbox, tree node etc. given its unique ID. activation is queued and processed on the next frame when the item is encountered again.
IMGUI_API void SetNavID(ImGuiID id, int nav_layer);
IMGUI_API void SetNavIDWithRectRel(ImGuiID id, int nav_layer, const ImRect& rect_rel);
// Inputs
inline bool IsMouseDragPastThreshold(int button, float lock_threshold = -1.0f);
inline bool IsKeyPressedMap(ImGuiKey key, bool repeat = true) { const int key_index = GImGui->IO.KeyMap[key]; return (key_index >= 0) ? IsKeyPressed(key_index, repeat) : false; }
inline bool IsNavInputDown(ImGuiNavInput n) { return GImGui->IO.NavInputs[n] > 0.0f; }
inline bool IsNavInputPressed(ImGuiNavInput n, ImGuiInputReadMode mode) { return GetNavInputAmount(n, mode) > 0.0f; }
inline bool IsNavInputPressedAnyOfTwo(ImGuiNavInput n1, ImGuiNavInput n2, ImGuiInputReadMode mode) { return (GetNavInputAmount(n1, mode) + GetNavInputAmount(n2, mode)) > 0.0f; }
// Drag and Drop
IMGUI_API bool BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id);
IMGUI_API void ClearDragDrop();
IMGUI_API bool IsDragDropPayloadBeingAccepted();
// New Columns API (FIXME-WIP)
IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiColumnsFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns().
IMGUI_API void EndColumns(); // close columns
IMGUI_API void PushColumnClipRect(int column_index);
IMGUI_API void PushColumnsBackground();
IMGUI_API void PopColumnsBackground();
IMGUI_API ImGuiID GetColumnsID(const char* str_id, int count);
IMGUI_API ImGuiColumns* FindOrCreateColumns(ImGuiWindow* window, ImGuiID id);
IMGUI_API float GetColumnOffsetFromNorm(const ImGuiColumns* columns, float offset_norm);
IMGUI_API float GetColumnNormFromOffset(const ImGuiColumns* columns, float offset);
// Tab Bars
IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags);
IMGUI_API ImGuiTabItem* TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id);
IMGUI_API void TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id);
IMGUI_API void TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab);
IMGUI_API void TabBarQueueChangeTabOrder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int dir);
IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags);
IMGUI_API ImVec2 TabItemCalcSize(const char* label, bool has_close_button);
IMGUI_API void TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col);
IMGUI_API bool TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id);
// Render helpers
// AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT.
// NB: All position are in absolute pixels coordinates (we are never using window coordinates internally)
IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true);
IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width);
IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0,0), const ImRect* clip_rect = NULL);
IMGUI_API void RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL);
IMGUI_API void RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end, const ImVec2* text_size_if_known);
IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f);
IMGUI_API void RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f);
IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, int rounding_corners_flags = ~0);
IMGUI_API void RenderCheckMark(ImVec2 pos, ImU32 col, float sz);
IMGUI_API void RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags = ImGuiNavHighlightFlags_TypeDefault); // Navigation highlight
IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text.
IMGUI_API void LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL);
// Render helpers (those functions don't access any ImGui state!)
IMGUI_API void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale = 1.0f);
IMGUI_API void RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col);
IMGUI_API void RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor = ImGuiMouseCursor_Arrow);
IMGUI_API void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col);
IMGUI_API void RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding);
IMGUI_API void RenderPixelEllipsis(ImDrawList* draw_list, ImVec2 pos, ImU32 col, int count);
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
// 2019/06/07: Updating prototypes of some of the internal functions. Leaving those for reference for a short while.
inline void RenderArrow(ImVec2 pos, ImGuiDir dir, float scale=1.0f) { ImGuiWindow* window = GetCurrentWindow(); RenderArrow(window->DrawList, pos, GetColorU32(ImGuiCol_Text), dir, scale); }
inline void RenderBullet(ImVec2 pos) { ImGuiWindow* window = GetCurrentWindow(); RenderBullet(window->DrawList, pos, GetColorU32(ImGuiCol_Text)); }
#endif
// Widgets
IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0);
IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0,0), ImGuiButtonFlags flags = 0);
IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos);
IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos);
IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags);
IMGUI_API void Scrollbar(ImGuiAxis axis);
IMGUI_API bool ScrollbarEx(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* p_scroll_v, float avail_v, float contents_v, ImDrawCornerFlags rounding_corners);
IMGUI_API ImGuiID GetScrollbarID(ImGuiWindow* window, ImGuiAxis axis);
IMGUI_API void SeparatorEx(ImGuiSeparatorFlags flags);
// Widgets low-level behaviors
IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0);
IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* v, float v_speed, const void* v_min, const void* v_max, const char* format, float power, ImGuiDragFlags flags);
IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb);
IMGUI_API bool SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f);
IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL);
IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextItemOpen() data, if any. May return true when logging
IMGUI_API void TreePushOverrideID(ImGuiID id);
// Template functions are instantiated in imgui_widgets.cpp for a finite number of types.
// To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036).
// e.g. " extern template IMGUI_API float RoundScalarWithFormatT<float, float>(const char* format, ImGuiDataType data_type, float v); "
template<typename T, typename SIGNED_T, typename FLOAT_T> IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, float power, ImGuiDragFlags flags);
template<typename T, typename SIGNED_T, typename FLOAT_T> IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb);
template<typename T, typename FLOAT_T> IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float power, float linear_zero_pos);
template<typename T, typename SIGNED_T> IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v);
// Data type helpers
IMGUI_API const ImGuiDataTypeInfo* DataTypeGetInfo(ImGuiDataType data_type);
IMGUI_API int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* data_ptr, const char* format);
IMGUI_API void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg_1, const void* arg_2);
IMGUI_API bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* format);
// InputText
IMGUI_API bool InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool TempInputTextScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* data_ptr, const char* format);
inline bool TempInputTextIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputTextId == id); }
// Color
IMGUI_API void ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags);
IMGUI_API void ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags);
IMGUI_API void ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags);
// Plot
IMGUI_API void PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 frame_size);
// Shade functions (write over already created vertices)
IMGUI_API void ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1);
IMGUI_API void ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp);
// Debug Tools
inline void DebugStartItemPicker() { GImGui->DebugItemPickerActive = true; }
} // namespace ImGui
// ImFontAtlas internals
IMGUI_API bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas);
IMGUI_API void ImFontAtlasBuildRegisterDefaultCustomRects(ImFontAtlas* atlas);
IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent);
IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque);
IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas);
IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_multiply_factor);
IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride);
// Debug Tools
// Use 'Metrics->Tools->Item Picker' to break into the call-stack of a specific item.
#ifndef IM_DEBUG_BREAK
#if defined(__clang__)
#define IM_DEBUG_BREAK() __builtin_debugtrap()
#elif defined (_MSC_VER)
#define IM_DEBUG_BREAK() __debugbreak()
#else
#define IM_DEBUG_BREAK() IM_ASSERT(0) // It is expected that you define IM_DEBUG_BREAK() into something that will break nicely in a debugger!
#endif
#endif // #ifndef IM_DEBUG_BREAK
// Test Engine Hooks (imgui_tests)
//#define IMGUI_ENABLE_TEST_ENGINE
#ifdef IMGUI_ENABLE_TEST_ENGINE
extern void ImGuiTestEngineHook_PreNewFrame(ImGuiContext* ctx);
extern void ImGuiTestEngineHook_PostNewFrame(ImGuiContext* ctx);
extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, const ImRect& bb, ImGuiID id);
extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, const char* label, ImGuiItemStatusFlags flags);
extern void ImGuiTestEngineHook_Log(ImGuiContext* ctx, const char* fmt, ...);
#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) ImGuiTestEngineHook_ItemAdd(&g, _BB, _ID) // Register item bounding box
#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register item label and status flags (optional)
#define IMGUI_TEST_ENGINE_LOG(_FMT, ...) ImGuiTestEngineHook_Log(&g, _FMT, __VA_ARGS__) // Custom log entry from user land into test log
#else
#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) do { } while (0)
#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) do { } while (0)
#define IMGUI_TEST_ENGINE_LOG(_FMT, ...) do { } while (0)
#endif
#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#ifdef _MSC_VER
#pragma warning (pop)
#endif
|
NVIDIA-Omniverse/PhysX/flow/external/imgui/imgui_widgets.cpp | // dear imgui, v1.72b
// (widgets code)
/*
Index of this file:
// [SECTION] Forward Declarations
// [SECTION] Widgets: Text, etc.
// [SECTION] Widgets: Main (Button, Image, Checkbox, RadioButton, ProgressBar, Bullet, etc.)
// [SECTION] Widgets: Low-level Layout helpers (Spacing, Dummy, NewLine, Separator, etc.)
// [SECTION] Widgets: ComboBox
// [SECTION] Data Type and Data Formatting Helpers
// [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc.
// [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc.
// [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc.
// [SECTION] Widgets: InputText, InputTextMultiline
// [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc.
// [SECTION] Widgets: TreeNode, CollapsingHeader, etc.
// [SECTION] Widgets: Selectable
// [SECTION] Widgets: ListBox
// [SECTION] Widgets: PlotLines, PlotHistogram
// [SECTION] Widgets: Value helpers
// [SECTION] Widgets: MenuItem, BeginMenu, EndMenu, etc.
// [SECTION] Widgets: BeginTabBar, EndTabBar, etc.
// [SECTION] Widgets: BeginTabItem, EndTabItem, etc.
// [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc.
*/
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
#include <ctype.h> // toupper
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
#endif
#if __has_warning("-Wdouble-promotion")
#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
#endif
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
//-------------------------------------------------------------------------
// Data
//-------------------------------------------------------------------------
// Those MIN/MAX values are not define because we need to point to them
static const signed char IM_S8_MIN = -128;
static const signed char IM_S8_MAX = 127;
static const unsigned char IM_U8_MIN = 0;
static const unsigned char IM_U8_MAX = 0xFF;
static const signed short IM_S16_MIN = -32768;
static const signed short IM_S16_MAX = 32767;
static const unsigned short IM_U16_MIN = 0;
static const unsigned short IM_U16_MAX = 0xFFFF;
static const ImS32 IM_S32_MIN = INT_MIN; // (-2147483647 - 1), (0x80000000);
static const ImS32 IM_S32_MAX = INT_MAX; // (2147483647), (0x7FFFFFFF)
static const ImU32 IM_U32_MIN = 0;
static const ImU32 IM_U32_MAX = UINT_MAX; // (0xFFFFFFFF)
#ifdef LLONG_MIN
static const ImS64 IM_S64_MIN = LLONG_MIN; // (-9223372036854775807ll - 1ll);
static const ImS64 IM_S64_MAX = LLONG_MAX; // (9223372036854775807ll);
#else
static const ImS64 IM_S64_MIN = -9223372036854775807LL - 1;
static const ImS64 IM_S64_MAX = 9223372036854775807LL;
#endif
static const ImU64 IM_U64_MIN = 0;
#ifdef ULLONG_MAX
static const ImU64 IM_U64_MAX = ULLONG_MAX; // (0xFFFFFFFFFFFFFFFFull);
#else
static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1);
#endif
//-------------------------------------------------------------------------
// [SECTION] Forward Declarations
//-------------------------------------------------------------------------
// For InputTextEx()
static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data);
static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end);
static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false);
//-------------------------------------------------------------------------
// [SECTION] Widgets: Text, etc.
//-------------------------------------------------------------------------
// - TextUnformatted()
// - Text()
// - TextV()
// - TextColored()
// - TextColoredV()
// - TextDisabled()
// - TextDisabledV()
// - TextWrapped()
// - TextWrappedV()
// - LabelText()
// - LabelTextV()
// - BulletText()
// - BulletTextV()
//-------------------------------------------------------------------------
void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
IM_ASSERT(text != NULL);
const char* text_begin = text;
if (text_end == NULL)
text_end = text + strlen(text); // FIXME-OPT
const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
const float wrap_pos_x = window->DC.TextWrapPos;
const bool wrap_enabled = (wrap_pos_x >= 0.0f);
if (text_end - text > 2000 && !wrap_enabled)
{
// Long text!
// Perform manual coarse clipping to optimize for long multi-line text
// - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled.
// - We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line.
// - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop.
const char* line = text;
const float line_height = GetTextLineHeight();
ImVec2 text_size(0,0);
// Lines to skip (can't skip when logging text)
ImVec2 pos = text_pos;
if (!g.LogEnabled)
{
int lines_skippable = (int)((window->ClipRect.Min.y - text_pos.y) / line_height);
if (lines_skippable > 0)
{
int lines_skipped = 0;
while (line < text_end && lines_skipped < lines_skippable)
{
const char* line_end = (const char*)memchr(line, '\n', text_end - line);
if (!line_end)
line_end = text_end;
if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
line = line_end + 1;
lines_skipped++;
}
pos.y += lines_skipped * line_height;
}
}
// Lines to render
if (line < text_end)
{
ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height));
while (line < text_end)
{
if (IsClippedEx(line_rect, 0, false))
break;
const char* line_end = (const char*)memchr(line, '\n', text_end - line);
if (!line_end)
line_end = text_end;
text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
RenderText(pos, line, line_end, false);
line = line_end + 1;
line_rect.Min.y += line_height;
line_rect.Max.y += line_height;
pos.y += line_height;
}
// Count remaining lines
int lines_skipped = 0;
while (line < text_end)
{
const char* line_end = (const char*)memchr(line, '\n', text_end - line);
if (!line_end)
line_end = text_end;
if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
line = line_end + 1;
lines_skipped++;
}
pos.y += lines_skipped * line_height;
}
text_size.y = (pos - text_pos).y;
ImRect bb(text_pos, text_pos + text_size);
ItemSize(text_size);
ItemAdd(bb, 0);
}
else
{
const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f;
const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width);
ImRect bb(text_pos, text_pos + text_size);
ItemSize(text_size);
if (!ItemAdd(bb, 0))
return;
// Render (we don't hide text after ## in this end-user function)
RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width);
}
}
void ImGui::TextUnformatted(const char* text, const char* text_end)
{
TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText);
}
void ImGui::Text(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextV(fmt, args);
va_end(args);
}
void ImGui::TextV(const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
TextEx(g.TempBuffer, text_end, ImGuiTextFlags_NoWidthForLargeClippedText);
}
void ImGui::TextColored(const ImVec4& col, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextColoredV(col, fmt, args);
va_end(args);
}
void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args)
{
PushStyleColor(ImGuiCol_Text, col);
TextV(fmt, args);
PopStyleColor();
}
void ImGui::TextDisabled(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextDisabledV(fmt, args);
va_end(args);
}
void ImGui::TextDisabledV(const char* fmt, va_list args)
{
PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]);
TextV(fmt, args);
PopStyleColor();
}
void ImGui::TextWrapped(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextWrappedV(fmt, args);
va_end(args);
}
void ImGui::TextWrappedV(const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
bool need_backup = (window->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set
if (need_backup)
PushTextWrapPos(0.0f);
TextV(fmt, args);
if (need_backup)
PopTextWrapPos();
}
void ImGui::LabelText(const char* label, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
LabelTextV(label, fmt, args);
va_end(args);
}
// Add a label+text combo aligned to other label+value widgets
void ImGui::LabelTextV(const char* label, const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const float w = CalcItemWidth();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2));
const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size);
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, 0))
return;
// Render
const char* value_text_begin = &g.TempBuffer[0];
const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f));
if (label_size.x > 0.0f)
RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label);
}
void ImGui::BulletText(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
BulletTextV(fmt, args);
va_end(args);
}
// Text with a little bullet aligned to the typical tree node.
void ImGui::BulletTextV(const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const char* text_begin = g.TempBuffer;
const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
const ImVec2 label_size = CalcTextSize(text_begin, text_end, false);
const float text_base_offset_y = ImMax(0.0f, window->DC.CurrLineTextBaseOffset); // Latch before ItemSize changes it
const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x*2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding
ItemSize(bb);
if (!ItemAdd(bb, 0))
return;
// Render
ImU32 text_col = GetColorU32(ImGuiCol_Text);
RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f), text_col);
RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end, false);
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: Main
//-------------------------------------------------------------------------
// - ButtonBehavior() [Internal]
// - Button()
// - SmallButton()
// - InvisibleButton()
// - ArrowButton()
// - CloseButton() [Internal]
// - CollapseButton() [Internal]
// - ScrollbarEx() [Internal]
// - Scrollbar() [Internal]
// - Image()
// - ImageButton()
// - Checkbox()
// - CheckboxFlags()
// - RadioButton()
// - ProgressBar()
// - Bullet()
//-------------------------------------------------------------------------
// The ButtonBehavior() function is key to many interactions and used by many/most widgets.
// Because we handle so many cases (keyboard/gamepad navigation, drag and drop) and many specific behavior (via ImGuiButtonFlags_),
// this code is a little complex.
// By far the most common path is interacting with the Mouse using the default ImGuiButtonFlags_PressedOnClickRelease button behavior.
// See the series of events below and the corresponding state reported by dear imgui:
//------------------------------------------------------------------------------------------------------------------------------------------------
// with PressedOnClickRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
// Frame N+0 (mouse is outside bb) - - - - - -
// Frame N+1 (mouse moves inside bb) - true - - - -
// Frame N+2 (mouse button is down) - true true true - true
// Frame N+3 (mouse button is down) - true true - - -
// Frame N+4 (mouse moves outside bb) - - true - - -
// Frame N+5 (mouse moves inside bb) - true true - - -
// Frame N+6 (mouse button is released) true true - - true -
// Frame N+7 (mouse button is released) - true - - - -
// Frame N+8 (mouse moves outside bb) - - - - - -
//------------------------------------------------------------------------------------------------------------------------------------------------
// with PressedOnClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
// Frame N+2 (mouse button is down) true true true true - true
// Frame N+3 (mouse button is down) - true true - - -
// Frame N+6 (mouse button is released) - true - - true -
// Frame N+7 (mouse button is released) - true - - - -
//------------------------------------------------------------------------------------------------------------------------------------------------
// with PressedOnRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
// Frame N+2 (mouse button is down) - true - - - true
// Frame N+3 (mouse button is down) - true - - - -
// Frame N+6 (mouse button is released) true true - - - -
// Frame N+7 (mouse button is released) - true - - - -
//------------------------------------------------------------------------------------------------------------------------------------------------
// with PressedOnDoubleClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
// Frame N+0 (mouse button is down) - true - - - true
// Frame N+1 (mouse button is down) - true - - - -
// Frame N+2 (mouse button is released) - true - - - -
// Frame N+3 (mouse button is released) - true - - - -
// Frame N+4 (mouse button is down) true true true true - true
// Frame N+5 (mouse button is down) - true true - - -
// Frame N+6 (mouse button is released) - true - - true -
// Frame N+7 (mouse button is released) - true - - - -
//------------------------------------------------------------------------------------------------------------------------------------------------
// Note that some combinations are supported,
// - PressedOnDragDropHold can generally be associated with any flag.
// - PressedOnDoubleClick can be associated by PressedOnClickRelease/PressedOnRelease, in which case the second release event won't be reported.
//------------------------------------------------------------------------------------------------------------------------------------------------
// The behavior of the return-value changes when ImGuiButtonFlags_Repeat is set:
// Repeat+ Repeat+ Repeat+ Repeat+
// PressedOnClickRelease PressedOnClick PressedOnRelease PressedOnDoubleClick
//-------------------------------------------------------------------------------------------------------------------------------------------------
// Frame N+0 (mouse button is down) - true - true
// ... - - - -
// Frame N + RepeatDelay true true - true
// ... - - - -
// Frame N + RepeatDelay + RepeatRate*N true true - true
//-------------------------------------------------------------------------------------------------------------------------------------------------
bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
if (flags & ImGuiButtonFlags_Disabled)
{
if (out_hovered) *out_hovered = false;
if (out_held) *out_held = false;
if (g.ActiveId == id) ClearActiveID();
return false;
}
// Default behavior requires click+release on same spot
if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0)
flags |= ImGuiButtonFlags_PressedOnClickRelease;
ImGuiWindow* backup_hovered_window = g.HoveredWindow;
const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window;
if (flatten_hovered_children)
g.HoveredWindow = window;
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (id != 0 && window->DC.LastItemId != id)
ImGuiTestEngineHook_ItemAdd(&g, bb, id);
#endif
bool pressed = false;
bool hovered = ItemHoverable(bb, id);
// Drag source doesn't report as hovered
if (hovered && g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
hovered = false;
// Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button
if (g.DragDropActive && (flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers))
if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
{
hovered = true;
SetHoveredID(id);
if (CalcTypematicPressedRepeatAmount(g.HoveredIdTimer + 0.0001f, g.HoveredIdTimer + 0.0001f - g.IO.DeltaTime, 0.01f, 0.70f)) // FIXME: Our formula for CalcTypematicPressedRepeatAmount() is fishy
{
pressed = true;
FocusWindow(window);
}
}
if (flatten_hovered_children)
g.HoveredWindow = backup_hovered_window;
// AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one.
if (hovered && (flags & ImGuiButtonFlags_AllowItemOverlap) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0))
hovered = false;
// Mouse
if (hovered)
{
if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
{
if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0])
{
SetActiveID(id, window);
if (!(flags & ImGuiButtonFlags_NoNavFocus))
SetFocusID(id, window);
FocusWindow(window);
}
if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0]))
{
pressed = true;
if (flags & ImGuiButtonFlags_NoHoldingActiveID)
ClearActiveID();
else
SetActiveID(id, window); // Hold on ID
FocusWindow(window);
}
if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0])
{
if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
pressed = true;
ClearActiveID();
}
// 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
// Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true))
pressed = true;
}
if (pressed)
g.NavDisableHighlight = true;
}
// Gamepad/Keyboard navigation
// We report navigated item as hovered but we don't set g.HoveredId to not interfere with mouse.
if (g.NavId == id && !g.NavDisableHighlight && g.NavDisableMouseHover && (g.ActiveId == 0 || g.ActiveId == id || g.ActiveId == window->MoveId))
if (!(flags & ImGuiButtonFlags_NoHoveredOnNav))
hovered = true;
if (g.NavActivateDownId == id)
{
bool nav_activated_by_code = (g.NavActivateId == id);
bool nav_activated_by_inputs = IsNavInputPressed(ImGuiNavInput_Activate, (flags & ImGuiButtonFlags_Repeat) ? ImGuiInputReadMode_Repeat : ImGuiInputReadMode_Pressed);
if (nav_activated_by_code || nav_activated_by_inputs)
pressed = true;
if (nav_activated_by_code || nav_activated_by_inputs || g.ActiveId == id)
{
// Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button.
g.NavActivateId = id; // This is so SetActiveId assign a Nav source
SetActiveID(id, window);
if ((nav_activated_by_code || nav_activated_by_inputs) && !(flags & ImGuiButtonFlags_NoNavFocus))
SetFocusID(id, window);
g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right) | (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
}
}
bool held = false;
if (g.ActiveId == id)
{
if (pressed)
g.ActiveIdHasBeenPressedBefore = true;
if (g.ActiveIdSource == ImGuiInputSource_Mouse)
{
if (g.ActiveIdIsJustActivated)
g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
if (g.IO.MouseDown[0])
{
held = true;
}
else
{
if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) && !g.DragDropActive)
{
bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDownWasDoubleClick[0];
bool is_repeating_already = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay; // Repeat mode trumps <on release>
if (!is_double_click_release && !is_repeating_already)
pressed = true;
}
ClearActiveID();
}
if (!(flags & ImGuiButtonFlags_NoNavFocus))
g.NavDisableHighlight = true;
}
else if (g.ActiveIdSource == ImGuiInputSource_Nav)
{
if (g.NavActivateDownId != id)
ClearActiveID();
}
}
if (out_hovered) *out_hovered = hovered;
if (out_held) *out_held = held;
return pressed;
}
bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 pos = window->DC.CursorPos;
if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag)
pos.y += window->DC.CurrLineTextBaseOffset - style.FramePadding.y;
ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);
const ImRect bb(pos, pos + size);
ItemSize(size, style.FramePadding.y);
if (!ItemAdd(bb, id))
return false;
if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat)
flags |= ImGuiButtonFlags_Repeat;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb);
// Automatically close popups
//if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// CloseCurrentPopup();
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
return pressed;
}
bool ImGui::Button(const char* label, const ImVec2& size_arg)
{
return ButtonEx(label, size_arg, 0);
}
// Small buttons fits within text without additional vertical spacing.
bool ImGui::SmallButton(const char* label)
{
ImGuiContext& g = *GImGui;
float backup_padding_y = g.Style.FramePadding.y;
g.Style.FramePadding.y = 0.0f;
bool pressed = ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags_AlignTextBaseLine);
g.Style.FramePadding.y = backup_padding_y;
return pressed;
}
// Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack.
// Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id)
bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
// Cannot use zero-size for InvisibleButton(). Unlike Button() there is not way to fallback using the label size.
IM_ASSERT(size_arg.x != 0.0f && size_arg.y != 0.0f);
const ImGuiID id = window->GetID(str_id);
ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
ItemSize(size);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
return pressed;
}
bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiButtonFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiID id = window->GetID(str_id);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
const float default_size = GetFrameHeight();
ItemSize(size, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f);
if (!ItemAdd(bb, id))
return false;
if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat)
flags |= ImGuiButtonFlags_Repeat;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
// Render
const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
const ImU32 text_col = GetColorU32(ImGuiCol_Text);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, bg_col, true, g.Style.FrameRounding);
RenderArrow(window->DrawList, bb.Min + ImVec2(ImMax(0.0f, (size.x - g.FontSize) * 0.5f), ImMax(0.0f, (size.y - g.FontSize) * 0.5f)), text_col, dir);
return pressed;
}
bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir)
{
float sz = GetFrameHeight();
return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), 0);
}
// Button to close a window
bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos)//, float size)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// We intentionally allow interaction when clipped so that a mechanical Alt,Right,Validate sequence close a window.
// (this isn't the regular behavior of buttons, but it doesn't affect the user much because navigation tends to keep items visible).
const ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize) + g.Style.FramePadding * 2.0f);
bool is_clipped = !ItemAdd(bb, id);
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
if (is_clipped)
return pressed;
// Render
ImU32 col = GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered);
ImVec2 center = bb.GetCenter();
if (hovered)
window->DrawList->AddCircleFilled(center, ImMax(2.0f, g.FontSize * 0.5f + 1.0f), col, 12);
float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f;
ImU32 cross_col = GetColorU32(ImGuiCol_Text);
center -= ImVec2(0.5f, 0.5f);
window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), cross_col, 1.0f);
window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), cross_col, 1.0f);
return pressed;
}
bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize) + g.Style.FramePadding * 2.0f);
ItemAdd(bb, id);
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None);
// Render
ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
ImU32 text_col = GetColorU32(ImGuiCol_Text);
ImVec2 center = bb.GetCenter();
if (hovered || held)
window->DrawList->AddCircleFilled(center/*+ ImVec2(0.0f, -0.5f)*/, g.FontSize * 0.5f + 1.0f, bg_col, 12);
RenderArrow(window->DrawList, bb.Min + g.Style.FramePadding, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);
// Switch to moving the window after mouse is moved beyond the initial drag threshold
if (IsItemActive() && IsMouseDragging())
StartMouseMovingWindow(window);
return pressed;
}
ImGuiID ImGui::GetScrollbarID(ImGuiWindow* window, ImGuiAxis axis)
{
return window->GetIDNoKeepAlive(axis == ImGuiAxis_X ? "#SCROLLX" : "#SCROLLY");
}
// Vertical/Horizontal scrollbar
// The entire piece of code below is rather confusing because:
// - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)
// - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
// - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
// Still, the code should probably be made simpler..
bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, float* p_scroll_v, float size_avail_v, float size_contents_v, ImDrawCornerFlags rounding_corners)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return false;
const float bb_frame_width = bb_frame.GetWidth();
const float bb_frame_height = bb_frame.GetHeight();
if (bb_frame_width <= 0.0f || bb_frame_height <= 0.0f)
return false;
// When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the resize grab)
float alpha = 1.0f;
if ((axis == ImGuiAxis_Y) && bb_frame_height < g.FontSize + g.Style.FramePadding.y * 2.0f)
alpha = ImSaturate((bb_frame_height - g.FontSize) / (g.Style.FramePadding.y * 2.0f));
if (alpha <= 0.0f)
return false;
const ImGuiStyle& style = g.Style;
const bool allow_interaction = (alpha >= 1.0f);
const bool horizontal = (axis == ImGuiAxis_X);
ImRect bb = bb_frame;
bb.Expand(ImVec2(-ImClamp((float)(int)((bb_frame_width - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp((float)(int)((bb_frame_height - 2.0f) * 0.5f), 0.0f, 3.0f)));
// V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)
const float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight();
// Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount)
// But we maintain a minimum size in pixel to allow for the user to still aim inside.
IM_ASSERT(ImMax(size_contents_v, size_avail_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers.
const float win_size_v = ImMax(ImMax(size_contents_v, size_avail_v), 1.0f);
const float grab_h_pixels = ImClamp(scrollbar_size_v * (size_avail_v / win_size_v), style.GrabMinSize, scrollbar_size_v);
const float grab_h_norm = grab_h_pixels / scrollbar_size_v;
// Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().
bool held = false;
bool hovered = false;
ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus);
float scroll_max = ImMax(1.0f, size_contents_v - size_avail_v);
float scroll_ratio = ImSaturate(*p_scroll_v / scroll_max);
float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
if (held && allow_interaction && grab_h_norm < 1.0f)
{
float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y;
float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
// Click position in scrollbar normalized space (0.0f->1.0f)
const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v);
SetHoveredID(id);
bool seek_absolute = false;
if (g.ActiveIdIsJustActivated)
{
// On initial click calculate the distance between mouse and the center of the grab
seek_absolute = (clicked_v_norm < grab_v_norm || clicked_v_norm > grab_v_norm + grab_h_norm);
if (seek_absolute)
g.ScrollbarClickDeltaToGrabCenter = 0.0f;
else
g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f;
}
// Apply scroll
// It is ok to modify Scroll here because we are being called in Begin() after the calculation of ContentSize and before setting up our starting position
const float scroll_v_norm = ImSaturate((clicked_v_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm * 0.5f) / (1.0f - grab_h_norm));
*p_scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v));
// Update values for rendering
scroll_ratio = ImSaturate(*p_scroll_v / scroll_max);
grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
// Update distance to grab now that we have seeked and saturated
if (seek_absolute)
g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f;
}
// Render
window->DrawList->AddRectFilled(bb_frame.Min, bb_frame.Max, GetColorU32(ImGuiCol_ScrollbarBg), window->WindowRounding, rounding_corners);
const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha);
ImRect grab_rect;
if (horizontal)
grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y);
else
grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels);
window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding);
return held;
}
void ImGui::Scrollbar(ImGuiAxis axis)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiID id = GetScrollbarID(window, axis);
KeepAliveID(id);
// Calculate scrollbar bounding box
const ImRect outer_rect = window->Rect();
const ImRect inner_rect = window->InnerRect;
const float border_size = window->WindowBorderSize;
const float scrollbar_size = window->ScrollbarSizes[axis ^ 1];
IM_ASSERT(scrollbar_size > 0.0f);
const float other_scrollbar_size = window->ScrollbarSizes[axis];
ImDrawCornerFlags rounding_corners = (other_scrollbar_size <= 0.0f) ? ImDrawCornerFlags_BotRight : 0;
ImRect bb;
if (axis == ImGuiAxis_X)
{
bb.Min = ImVec2(inner_rect.Min.x, ImMax(outer_rect.Min.y, outer_rect.Max.y - border_size - scrollbar_size));
bb.Max = ImVec2(inner_rect.Max.x, outer_rect.Max.y);
rounding_corners |= ImDrawCornerFlags_BotLeft;
}
else
{
bb.Min = ImVec2(ImMax(outer_rect.Min.x, outer_rect.Max.x - border_size - scrollbar_size), inner_rect.Min.y);
bb.Max = ImVec2(outer_rect.Max.x, window->InnerRect.Max.y);
rounding_corners |= ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0;
}
ScrollbarEx(bb, id, axis, &window->Scroll[axis], inner_rect.Max[axis] - inner_rect.Min[axis], window->ContentSize[axis] + window->WindowPadding[axis] * 2.0f, rounding_corners);
}
void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
if (border_col.w > 0.0f)
bb.Max += ImVec2(2, 2);
ItemSize(bb);
if (!ItemAdd(bb, 0))
return;
if (border_col.w > 0.0f)
{
window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f);
window->DrawList->AddImage(user_texture_id, bb.Min + ImVec2(1, 1), bb.Max - ImVec2(1, 1), uv0, uv1, GetColorU32(tint_col));
}
else
{
window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col));
}
}
// frame_padding < 0: uses FramePadding from style (default)
// frame_padding = 0: no framing
// frame_padding > 0: set framing size
// The color used are the button colors.
bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
// Default to using texture ID as ID. User can still push string/integer prefixes.
// We could hash the size/uv to create a unique ID but that would prevent the user from animating UV.
PushID((void*)(intptr_t)user_texture_id);
const ImGuiID id = window->GetID("#image");
PopID();
const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding * 2);
const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size);
ItemSize(bb);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding));
if (bg_col.w > 0.0f)
window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col));
window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col));
return pressed;
}
bool ImGui::Checkbox(const char* label, bool* v)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const float square_sz = GetFrameHeight();
const ImVec2 pos = window->DC.CursorPos;
const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
if (pressed)
{
*v = !(*v);
MarkItemEdited(id);
}
const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz));
RenderNavHighlight(total_bb, id);
RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);
ImU32 check_col = GetColorU32(ImGuiCol_CheckMark);
if (window->DC.ItemFlags & ImGuiItemFlags_MixedValue)
{
// Undocumented tristate/mixed/indeterminate checkbox (#2644)
ImVec2 pad(ImMax(1.0f, (float)(int)(square_sz / 3.6f)), ImMax(1.0f, (float)(int)(square_sz / 3.6f)));
window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding);
}
else if (*v)
{
const float pad = ImMax(1.0f, (float)(int)(square_sz / 6.0f));
RenderCheckMark(check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad*2.0f);
}
if (g.LogEnabled)
LogRenderedText(&total_bb.Min, *v ? "[x]" : "[ ]");
if (label_size.x > 0.0f)
RenderText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), label);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0));
return pressed;
}
bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value)
{
bool v = ((*flags & flags_value) == flags_value);
bool pressed = Checkbox(label, &v);
if (pressed)
{
if (v)
*flags |= flags_value;
else
*flags &= ~flags_value;
}
return pressed;
}
bool ImGui::RadioButton(const char* label, bool active)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const float square_sz = GetFrameHeight();
const ImVec2 pos = window->DC.CursorPos;
const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz));
const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id))
return false;
ImVec2 center = check_bb.GetCenter();
center.x = (float)(int)center.x + 0.5f;
center.y = (float)(int)center.y + 0.5f;
const float radius = (square_sz - 1.0f) * 0.5f;
bool hovered, held;
bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
if (pressed)
MarkItemEdited(id);
RenderNavHighlight(total_bb, id);
window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16);
if (active)
{
const float pad = ImMax(1.0f, (float)(int)(square_sz / 6.0f));
window->DrawList->AddCircleFilled(center, radius - pad, GetColorU32(ImGuiCol_CheckMark), 16);
}
if (style.FrameBorderSize > 0.0f)
{
window->DrawList->AddCircle(center + ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize);
window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16, style.FrameBorderSize);
}
if (g.LogEnabled)
LogRenderedText(&total_bb.Min, active ? "(x)" : "( )");
if (label_size.x > 0.0f)
RenderText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), label);
return pressed;
}
// FIXME: This would work nicely if it was a public template, e.g. 'template<T> RadioButton(const char* label, T* v, T v_button)', but I'm not sure how we would expose it..
bool ImGui::RadioButton(const char* label, int* v, int v_button)
{
const bool pressed = RadioButton(label, *v == v_button);
if (pressed)
*v = v_button;
return pressed;
}
// size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size
void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
ImVec2 pos = window->DC.CursorPos;
ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f);
ImRect bb(pos, pos + size);
ItemSize(size, style.FramePadding.y);
if (!ItemAdd(bb, 0))
return;
// Render
fraction = ImSaturate(fraction);
RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize));
const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y);
RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), 0.0f, fraction, style.FrameRounding);
// Default displaying the fraction as percentage string, but user can override it
char overlay_buf[32];
if (!overlay)
{
ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f);
overlay = overlay_buf;
}
ImVec2 overlay_size = CalcTextSize(overlay, NULL);
if (overlay_size.x > 0.0f)
RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb);
}
void ImGui::Bullet()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height));
ItemSize(bb);
if (!ItemAdd(bb, 0))
{
SameLine(0, style.FramePadding.x*2);
return;
}
// Render and stay on same line
ImU32 text_col = GetColorU32(ImGuiCol_Text);
RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f), text_col);
SameLine(0, style.FramePadding.x * 2.0f);
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: Low-level Layout helpers
//-------------------------------------------------------------------------
// - Spacing()
// - Dummy()
// - NewLine()
// - AlignTextToFramePadding()
// - SeparatorEx() [Internal]
// - Separator()
// - SplitterBehavior() [Internal]
// - ShrinkWidths() [Internal]
//-------------------------------------------------------------------------
void ImGui::Spacing()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ItemSize(ImVec2(0,0));
}
void ImGui::Dummy(const ImVec2& size)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
ItemSize(size);
ItemAdd(bb, 0);
}
void ImGui::NewLine()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiLayoutType backup_layout_type = window->DC.LayoutType;
window->DC.LayoutType = ImGuiLayoutType_Vertical;
if (window->DC.CurrLineSize.y > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height.
ItemSize(ImVec2(0,0));
else
ItemSize(ImVec2(0.0f, g.FontSize));
window->DC.LayoutType = backup_layout_type;
}
void ImGui::AlignTextToFramePadding()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
window->DC.CurrLineSize.y = ImMax(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y * 2);
window->DC.CurrLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, g.Style.FramePadding.y);
}
// Horizontal/vertical separating line
void ImGui::SeparatorEx(ImGuiSeparatorFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
IM_ASSERT(ImIsPowerOfTwo(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical))); // Check that only 1 option is selected
float thickness_draw = 1.0f;
float thickness_layout = 0.0f;
if (flags & ImGuiSeparatorFlags_Vertical)
{
// Vertical separator, for menu bars (use current line height). Not exposed because it is misleading and it doesn't have an effect on regular layout.
float y1 = window->DC.CursorPos.y;
float y2 = window->DC.CursorPos.y + window->DC.CurrLineSize.y;
const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + thickness_draw, y2));
ItemSize(ImVec2(thickness_layout, 0.0f));
if (!ItemAdd(bb, 0))
return;
// Draw
window->DrawList->AddLine(ImVec2(bb.Min.x, bb.Min.y), ImVec2(bb.Min.x, bb.Max.y), GetColorU32(ImGuiCol_Separator));
if (g.LogEnabled)
LogText(" |");
}
else if (flags & ImGuiSeparatorFlags_Horizontal)
{
// Horizontal Separator
float x1 = window->Pos.x;
float x2 = window->Pos.x + window->Size.x;
if (!window->DC.GroupStack.empty())
x1 += window->DC.Indent.x;
ImGuiColumns* columns = (flags & ImGuiSeparatorFlags_SpanAllColumns) ? window->DC.CurrentColumns : NULL;
if (columns)
PushColumnsBackground();
// We don't provide our width to the layout so that it doesn't get feed back into AutoFit
const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y + thickness_draw));
ItemSize(ImVec2(0.0f, thickness_layout));
if (!ItemAdd(bb, 0))
{
if (columns)
PopColumnsBackground();
return;
}
// Draw
window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x, bb.Min.y), GetColorU32(ImGuiCol_Separator));
if (g.LogEnabled)
LogRenderedText(&bb.Min, "--------------------------------");
if (columns)
{
PopColumnsBackground();
columns->LineMinY = window->DC.CursorPos.y;
}
}
}
void ImGui::Separator()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
// Those flags should eventually be overridable by the user
ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal;
flags |= ImGuiSeparatorFlags_SpanAllColumns;
SeparatorEx(flags);
}
// Using 'hover_visibility_delay' allows us to hide the highlight and mouse cursor for a short time, which can be convenient to reduce visual noise.
bool ImGui::SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend, float hover_visibility_delay)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
window->DC.ItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus;
bool item_add = ItemAdd(bb, id);
window->DC.ItemFlags = item_flags_backup;
if (!item_add)
return false;
bool hovered, held;
ImRect bb_interact = bb;
bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f));
ButtonBehavior(bb_interact, id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap);
if (g.ActiveId != id)
SetItemAllowOverlap();
if (held || (g.HoveredId == id && g.HoveredIdPreviousFrame == id && g.HoveredIdTimer >= hover_visibility_delay))
SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW);
ImRect bb_render = bb;
if (held)
{
ImVec2 mouse_delta_2d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min;
float mouse_delta = (axis == ImGuiAxis_Y) ? mouse_delta_2d.y : mouse_delta_2d.x;
// Minimum pane size
float size_1_maximum_delta = ImMax(0.0f, *size1 - min_size1);
float size_2_maximum_delta = ImMax(0.0f, *size2 - min_size2);
if (mouse_delta < -size_1_maximum_delta)
mouse_delta = -size_1_maximum_delta;
if (mouse_delta > size_2_maximum_delta)
mouse_delta = size_2_maximum_delta;
// Apply resize
if (mouse_delta != 0.0f)
{
if (mouse_delta < 0.0f)
IM_ASSERT(*size1 + mouse_delta >= min_size1);
if (mouse_delta > 0.0f)
IM_ASSERT(*size2 - mouse_delta >= min_size2);
*size1 += mouse_delta;
*size2 -= mouse_delta;
bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta));
MarkItemEdited(id);
}
}
// Render
const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : (hovered && g.HoveredIdTimer >= hover_visibility_delay) ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, g.Style.FrameRounding);
return held;
}
static int IMGUI_CDECL ShrinkWidthItemComparer(const void* lhs, const void* rhs)
{
const ImGuiShrinkWidthItem* a = (const ImGuiShrinkWidthItem*)lhs;
const ImGuiShrinkWidthItem* b = (const ImGuiShrinkWidthItem*)rhs;
if (int d = (int)(b->Width - a->Width))
return d;
return (b->Index - a->Index);
}
// Shrink excess width from a set of item, by removing width from the larger items first.
void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess)
{
if (count > 1)
ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer);
int count_same_width = 1;
while (width_excess > 0.0f && count_same_width < count)
{
while (count_same_width < count && items[0].Width == items[count_same_width].Width)
count_same_width++;
float width_to_remove_per_item_max = (count_same_width < count) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f);
float width_to_remove_per_item = ImMin(width_excess / count_same_width, width_to_remove_per_item_max);
for (int item_n = 0; item_n < count_same_width; item_n++)
items[item_n].Width -= width_to_remove_per_item;
width_excess -= width_to_remove_per_item * count_same_width;
}
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: ComboBox
//-------------------------------------------------------------------------
// - BeginCombo()
// - EndCombo()
// - Combo()
//-------------------------------------------------------------------------
static float CalcMaxPopupHeightFromItemCount(int items_count)
{
ImGuiContext& g = *GImGui;
if (items_count <= 0)
return FLT_MAX;
return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2);
}
bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags)
{
// Always consume the SetNextWindowSizeConstraint() call in our early return paths
ImGuiContext& g = *GImGui;
bool has_window_size_constraint = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint) != 0;
g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint;
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const float expected_w = CalcItemWidth();
const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : expected_w;
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id, &frame_bb))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held);
bool popup_open = IsPopupOpen(id);
const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
const float value_x2 = ImMax(frame_bb.Min.x, frame_bb.Max.x - arrow_size);
RenderNavHighlight(frame_bb, id);
if (!(flags & ImGuiComboFlags_NoPreview))
window->DrawList->AddRectFilled(frame_bb.Min, ImVec2(value_x2, frame_bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Left);
if (!(flags & ImGuiComboFlags_NoArrowButton))
{
ImU32 bg_col = GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
ImU32 text_col = GetColorU32(ImGuiCol_Text);
window->DrawList->AddRectFilled(ImVec2(value_x2, frame_bb.Min.y), frame_bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Right);
if (value_x2 + arrow_size - style.FramePadding.x <= frame_bb.Max.x)
RenderArrow(window->DrawList, ImVec2(value_x2 + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), text_col, ImGuiDir_Down, 1.0f);
}
RenderFrameBorder(frame_bb.Min, frame_bb.Max, style.FrameRounding);
if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview))
RenderTextClipped(frame_bb.Min + style.FramePadding, ImVec2(value_x2, frame_bb.Max.y), preview_value, NULL, NULL, ImVec2(0.0f,0.0f));
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
if ((pressed || g.NavActivateId == id) && !popup_open)
{
if (window->DC.NavLayerCurrent == 0)
window->NavLastIds[0] = id;
OpenPopupEx(id);
popup_open = true;
}
if (!popup_open)
return false;
if (has_window_size_constraint)
{
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w);
}
else
{
if ((flags & ImGuiComboFlags_HeightMask_) == 0)
flags |= ImGuiComboFlags_HeightRegular;
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one
int popup_max_height_in_items = -1;
if (flags & ImGuiComboFlags_HeightRegular) popup_max_height_in_items = 8;
else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4;
else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20;
SetNextWindowSizeConstraints(ImVec2(w, 0.0f), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
}
char name[16];
ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth
// Peak into expected window size so we can position it
if (ImGuiWindow* popup_window = FindWindowByName(name))
if (popup_window->WasActive)
{
ImVec2 size_expected = CalcWindowExpectedSize(popup_window);
if (flags & ImGuiComboFlags_PopupAlignLeft)
popup_window->AutoPosLastDirection = ImGuiDir_Left;
ImRect r_outer = GetWindowAllowedExtentRect(popup_window);
ImVec2 pos = FindBestWindowPosForPopupEx(frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, r_outer, frame_bb, ImGuiPopupPositionPolicy_ComboBox);
SetNextWindowPos(pos);
}
// Horizontally align ourselves with the framed text
ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(style.FramePadding.x, style.WindowPadding.y));
bool ret = Begin(name, NULL, window_flags);
PopStyleVar();
if (!ret)
{
EndPopup();
IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above
return false;
}
return true;
}
void ImGui::EndCombo()
{
EndPopup();
}
// Getter for the old Combo() API: const char*[]
static bool Items_ArrayGetter(void* data, int idx, const char** out_text)
{
const char* const* items = (const char* const*)data;
if (out_text)
*out_text = items[idx];
return true;
}
// Getter for the old Combo() API: "item1\0item2\0item3\0"
static bool Items_SingleStringGetter(void* data, int idx, const char** out_text)
{
// FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited.
const char* items_separated_by_zeros = (const char*)data;
int items_count = 0;
const char* p = items_separated_by_zeros;
while (*p)
{
if (idx == items_count)
break;
p += strlen(p) + 1;
items_count++;
}
if (!*p)
return false;
if (out_text)
*out_text = p;
return true;
}
// Old API, prefer using BeginCombo() nowadays if you can.
bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int popup_max_height_in_items)
{
ImGuiContext& g = *GImGui;
// Call the getter to obtain the preview string which is a parameter to BeginCombo()
const char* preview_value = NULL;
if (*current_item >= 0 && *current_item < items_count)
items_getter(data, *current_item, &preview_value);
// The old Combo() API exposed "popup_max_height_in_items". The new more general BeginCombo() API doesn't have/need it, but we emulate it here.
if (popup_max_height_in_items != -1 && !(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint))
SetNextWindowSizeConstraints(ImVec2(0,0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
if (!BeginCombo(label, preview_value, ImGuiComboFlags_None))
return false;
// Display items
// FIXME-OPT: Use clipper (but we need to disable it on the appearing frame to make sure our call to SetItemDefaultFocus() is processed)
bool value_changed = false;
for (int i = 0; i < items_count; i++)
{
PushID((void*)(intptr_t)i);
const bool item_selected = (i == *current_item);
const char* item_text;
if (!items_getter(data, i, &item_text))
item_text = "*Unknown item*";
if (Selectable(item_text, item_selected))
{
value_changed = true;
*current_item = i;
}
if (item_selected)
SetItemDefaultFocus();
PopID();
}
EndCombo();
return value_changed;
}
// Combo box helper allowing to pass an array of strings.
bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items)
{
const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items);
return value_changed;
}
// Combo box helper allowing to pass all items in a single string literal holding multiple zero-terminated items "item1\0item2\0"
bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items)
{
int items_count = 0;
const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open
while (*p)
{
p += strlen(p) + 1;
items_count++;
}
bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items);
return value_changed;
}
//-------------------------------------------------------------------------
// [SECTION] Data Type and Data Formatting Helpers [Internal]
//-------------------------------------------------------------------------
// - PatchFormatStringFloatToInt()
// - DataTypeGetInfo()
// - DataTypeFormatString()
// - DataTypeApplyOp()
// - DataTypeApplyOpFromText()
// - GetMinimumStepAtDecimalPrecision
// - RoundScalarWithFormat<>()
//-------------------------------------------------------------------------
static const ImGuiDataTypeInfo GDataTypeInfo[] =
{
{ sizeof(char), "%d", "%d" }, // ImGuiDataType_S8
{ sizeof(unsigned char), "%u", "%u" },
{ sizeof(short), "%d", "%d" }, // ImGuiDataType_S16
{ sizeof(unsigned short), "%u", "%u" },
{ sizeof(int), "%d", "%d" }, // ImGuiDataType_S32
{ sizeof(unsigned int), "%u", "%u" },
#ifdef _MSC_VER
{ sizeof(ImS64), "%I64d","%I64d" }, // ImGuiDataType_S64
{ sizeof(ImU64), "%I64u","%I64u" },
#else
{ sizeof(ImS64), "%lld", "%lld" }, // ImGuiDataType_S64
{ sizeof(ImU64), "%llu", "%llu" },
#endif
{ sizeof(float), "%f", "%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg)
{ sizeof(double), "%f", "%lf" }, // ImGuiDataType_Double
};
IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT);
// FIXME-LEGACY: Prior to 1.61 our DragInt() function internally used floats and because of this the compile-time default value for format was "%.0f".
// Even though we changed the compile-time default, we expect users to have carried %f around, which would break the display of DragInt() calls.
// To honor backward compatibility we are rewriting the format string, unless IMGUI_DISABLE_OBSOLETE_FUNCTIONS is enabled. What could possibly go wrong?!
static const char* PatchFormatStringFloatToInt(const char* fmt)
{
if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '0' && fmt[3] == 'f' && fmt[4] == 0) // Fast legacy path for "%.0f" which is expected to be the most common case.
return "%d";
const char* fmt_start = ImParseFormatFindStart(fmt); // Find % (if any, and ignore %%)
const char* fmt_end = ImParseFormatFindEnd(fmt_start); // Find end of format specifier, which itself is an exercise of confidence/recklessness (because snprintf is dependent on libc or user).
if (fmt_end > fmt_start && fmt_end[-1] == 'f')
{
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
if (fmt_start == fmt && fmt_end[0] == 0)
return "%d";
ImGuiContext& g = *GImGui;
ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%.*s%%d%s", (int)(fmt_start - fmt), fmt, fmt_end); // Honor leading and trailing decorations, but lose alignment/precision.
return g.TempBuffer;
#else
IM_ASSERT(0 && "DragInt(): Invalid format string!"); // Old versions used a default parameter of "%.0f", please replace with e.g. "%d"
#endif
}
return fmt;
}
const ImGuiDataTypeInfo* ImGui::DataTypeGetInfo(ImGuiDataType data_type)
{
IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);
return &GDataTypeInfo[data_type];
}
int ImGui::DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* data_ptr, const char* format)
{
// Signedness doesn't matter when pushing integer arguments
if (data_type == ImGuiDataType_S32 || data_type == ImGuiDataType_U32)
return ImFormatString(buf, buf_size, format, *(const ImU32*)data_ptr);
if (data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64)
return ImFormatString(buf, buf_size, format, *(const ImU64*)data_ptr);
if (data_type == ImGuiDataType_Float)
return ImFormatString(buf, buf_size, format, *(const float*)data_ptr);
if (data_type == ImGuiDataType_Double)
return ImFormatString(buf, buf_size, format, *(const double*)data_ptr);
if (data_type == ImGuiDataType_S8)
return ImFormatString(buf, buf_size, format, *(const ImS8*)data_ptr);
if (data_type == ImGuiDataType_U8)
return ImFormatString(buf, buf_size, format, *(const ImU8*)data_ptr);
if (data_type == ImGuiDataType_S16)
return ImFormatString(buf, buf_size, format, *(const ImS16*)data_ptr);
if (data_type == ImGuiDataType_U16)
return ImFormatString(buf, buf_size, format, *(const ImU16*)data_ptr);
IM_ASSERT(0);
return 0;
}
void ImGui::DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg1, const void* arg2)
{
IM_ASSERT(op == '+' || op == '-');
switch (data_type)
{
case ImGuiDataType_S8:
if (op == '+') { *(ImS8*)output = ImAddClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); }
if (op == '-') { *(ImS8*)output = ImSubClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); }
return;
case ImGuiDataType_U8:
if (op == '+') { *(ImU8*)output = ImAddClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); }
if (op == '-') { *(ImU8*)output = ImSubClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); }
return;
case ImGuiDataType_S16:
if (op == '+') { *(ImS16*)output = ImAddClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); }
if (op == '-') { *(ImS16*)output = ImSubClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); }
return;
case ImGuiDataType_U16:
if (op == '+') { *(ImU16*)output = ImAddClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); }
if (op == '-') { *(ImU16*)output = ImSubClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); }
return;
case ImGuiDataType_S32:
if (op == '+') { *(ImS32*)output = ImAddClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); }
if (op == '-') { *(ImS32*)output = ImSubClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); }
return;
case ImGuiDataType_U32:
if (op == '+') { *(ImU32*)output = ImAddClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); }
if (op == '-') { *(ImU32*)output = ImSubClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); }
return;
case ImGuiDataType_S64:
if (op == '+') { *(ImS64*)output = ImAddClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); }
if (op == '-') { *(ImS64*)output = ImSubClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); }
return;
case ImGuiDataType_U64:
if (op == '+') { *(ImU64*)output = ImAddClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); }
if (op == '-') { *(ImU64*)output = ImSubClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); }
return;
case ImGuiDataType_Float:
if (op == '+') { *(float*)output = *(const float*)arg1 + *(const float*)arg2; }
if (op == '-') { *(float*)output = *(const float*)arg1 - *(const float*)arg2; }
return;
case ImGuiDataType_Double:
if (op == '+') { *(double*)output = *(const double*)arg1 + *(const double*)arg2; }
if (op == '-') { *(double*)output = *(const double*)arg1 - *(const double*)arg2; }
return;
case ImGuiDataType_COUNT: break;
}
IM_ASSERT(0);
}
// User can input math operators (e.g. +100) to edit a numerical values.
// NB: This is _not_ a full expression evaluator. We should probably add one and replace this dumb mess..
bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* format)
{
while (ImCharIsBlankA(*buf))
buf++;
// We don't support '-' op because it would conflict with inputing negative value.
// Instead you can use +-100 to subtract from an existing value
char op = buf[0];
if (op == '+' || op == '*' || op == '/')
{
buf++;
while (ImCharIsBlankA(*buf))
buf++;
}
else
{
op = 0;
}
if (!buf[0])
return false;
// Copy the value in an opaque buffer so we can compare at the end of the function if it changed at all.
IM_ASSERT(data_type < ImGuiDataType_COUNT);
int data_backup[2];
const ImGuiDataTypeInfo* type_info = ImGui::DataTypeGetInfo(data_type);
IM_ASSERT(type_info->Size <= sizeof(data_backup));
memcpy(data_backup, data_ptr, type_info->Size);
if (format == NULL)
format = type_info->ScanFmt;
// FIXME-LEGACY: The aim is to remove those operators and write a proper expression evaluator at some point..
int arg1i = 0;
if (data_type == ImGuiDataType_S32)
{
int* v = (int*)data_ptr;
int arg0i = *v;
float arg1f = 0.0f;
if (op && sscanf(initial_value_buf, format, &arg0i) < 1)
return false;
// Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision
if (op == '+') { if (sscanf(buf, "%d", &arg1i)) *v = (int)(arg0i + arg1i); } // Add (use "+-" to subtract)
else if (op == '*') { if (sscanf(buf, "%f", &arg1f)) *v = (int)(arg0i * arg1f); } // Multiply
else if (op == '/') { if (sscanf(buf, "%f", &arg1f) && arg1f != 0.0f) *v = (int)(arg0i / arg1f); } // Divide
else { if (sscanf(buf, format, &arg1i) == 1) *v = arg1i; } // Assign constant
}
else if (data_type == ImGuiDataType_Float)
{
// For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in
format = "%f";
float* v = (float*)data_ptr;
float arg0f = *v, arg1f = 0.0f;
if (op && sscanf(initial_value_buf, format, &arg0f) < 1)
return false;
if (sscanf(buf, format, &arg1f) < 1)
return false;
if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract)
else if (op == '*') { *v = arg0f * arg1f; } // Multiply
else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide
else { *v = arg1f; } // Assign constant
}
else if (data_type == ImGuiDataType_Double)
{
format = "%lf"; // scanf differentiate float/double unlike printf which forces everything to double because of ellipsis
double* v = (double*)data_ptr;
double arg0f = *v, arg1f = 0.0;
if (op && sscanf(initial_value_buf, format, &arg0f) < 1)
return false;
if (sscanf(buf, format, &arg1f) < 1)
return false;
if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract)
else if (op == '*') { *v = arg0f * arg1f; } // Multiply
else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide
else { *v = arg1f; } // Assign constant
}
else if (data_type == ImGuiDataType_U32 || data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64)
{
// All other types assign constant
// We don't bother handling support for legacy operators since they are a little too crappy. Instead we will later implement a proper expression evaluator in the future.
sscanf(buf, format, data_ptr);
}
else
{
// Small types need a 32-bit buffer to receive the result from scanf()
int v32;
sscanf(buf, format, &v32);
if (data_type == ImGuiDataType_S8)
*(ImS8*)data_ptr = (ImS8)ImClamp(v32, (int)IM_S8_MIN, (int)IM_S8_MAX);
else if (data_type == ImGuiDataType_U8)
*(ImU8*)data_ptr = (ImU8)ImClamp(v32, (int)IM_U8_MIN, (int)IM_U8_MAX);
else if (data_type == ImGuiDataType_S16)
*(ImS16*)data_ptr = (ImS16)ImClamp(v32, (int)IM_S16_MIN, (int)IM_S16_MAX);
else if (data_type == ImGuiDataType_U16)
*(ImU16*)data_ptr = (ImU16)ImClamp(v32, (int)IM_U16_MIN, (int)IM_U16_MAX);
else
IM_ASSERT(0);
}
return memcmp(data_backup, data_ptr, type_info->Size) != 0;
}
static float GetMinimumStepAtDecimalPrecision(int decimal_precision)
{
static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f };
if (decimal_precision < 0)
return FLT_MIN;
return (decimal_precision < IM_ARRAYSIZE(min_steps)) ? min_steps[decimal_precision] : ImPow(10.0f, (float)-decimal_precision);
}
template<typename TYPE>
static const char* ImAtoi(const char* src, TYPE* output)
{
int negative = 0;
if (*src == '-') { negative = 1; src++; }
if (*src == '+') { src++; }
TYPE v = 0;
while (*src >= '0' && *src <= '9')
v = (v * 10) + (*src++ - '0');
*output = negative ? -v : v;
return src;
}
template<typename TYPE, typename SIGNEDTYPE>
TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, TYPE v)
{
const char* fmt_start = ImParseFormatFindStart(format);
if (fmt_start[0] != '%' || fmt_start[1] == '%') // Don't apply if the value is not visible in the format string
return v;
char v_str[64];
ImFormatString(v_str, IM_ARRAYSIZE(v_str), fmt_start, v);
const char* p = v_str;
while (*p == ' ')
p++;
if (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double)
v = (TYPE)ImAtof(p);
else
ImAtoi(p, (SIGNEDTYPE*)&v);
return v;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc.
//-------------------------------------------------------------------------
// - DragBehaviorT<>() [Internal]
// - DragBehavior() [Internal]
// - DragScalar()
// - DragScalarN()
// - DragFloat()
// - DragFloat2()
// - DragFloat3()
// - DragFloat4()
// - DragFloatRange2()
// - DragInt()
// - DragInt2()
// - DragInt3()
// - DragInt4()
// - DragIntRange2()
//-------------------------------------------------------------------------
// This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls)
template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragFlags flags)
{
ImGuiContext& g = *GImGui;
const ImGuiAxis axis = (flags & ImGuiDragFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;
const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
const bool has_min_max = (v_min != v_max);
const bool is_power = (power != 1.0f && is_decimal && has_min_max && (v_max - v_min < FLT_MAX));
// Default tweak speed
if (v_speed == 0.0f && has_min_max && (v_max - v_min < FLT_MAX))
v_speed = (float)((v_max - v_min) * g.DragSpeedDefaultRatio);
// Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings
float adjust_delta = 0.0f;
if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && g.IO.MouseDragMaxDistanceSqr[0] > 1.0f*1.0f)
{
adjust_delta = g.IO.MouseDelta[axis];
if (g.IO.KeyAlt)
adjust_delta *= 1.0f / 100.0f;
if (g.IO.KeyShift)
adjust_delta *= 10.0f;
}
else if (g.ActiveIdSource == ImGuiInputSource_Nav)
{
int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0;
adjust_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 1.0f / 10.0f, 10.0f)[axis];
v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision));
}
adjust_delta *= v_speed;
// For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter.
if (axis == ImGuiAxis_Y)
adjust_delta = -adjust_delta;
// Clear current value on activation
// Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300.
bool is_just_activated = g.ActiveIdIsJustActivated;
bool is_already_past_limits_and_pushing_outward = has_min_max && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f));
bool is_drag_direction_change_with_power = is_power && ((adjust_delta < 0 && g.DragCurrentAccum > 0) || (adjust_delta > 0 && g.DragCurrentAccum < 0));
if (is_just_activated || is_already_past_limits_and_pushing_outward || is_drag_direction_change_with_power)
{
g.DragCurrentAccum = 0.0f;
g.DragCurrentAccumDirty = false;
}
else if (adjust_delta != 0.0f)
{
g.DragCurrentAccum += adjust_delta;
g.DragCurrentAccumDirty = true;
}
if (!g.DragCurrentAccumDirty)
return false;
TYPE v_cur = *v;
FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f;
if (is_power)
{
// Offset + round to user desired precision, with a curve on the v_min..v_max range to get more precision on one side of the range
FLOATTYPE v_old_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power);
FLOATTYPE v_new_norm_curved = v_old_norm_curved + (g.DragCurrentAccum / (v_max - v_min));
v_cur = v_min + (TYPE)ImPow(ImSaturate((float)v_new_norm_curved), power) * (v_max - v_min);
v_old_ref_for_accum_remainder = v_old_norm_curved;
}
else
{
v_cur += (TYPE)g.DragCurrentAccum;
}
// Round to user desired precision based on format string
v_cur = RoundScalarWithFormatT<TYPE, SIGNEDTYPE>(format, data_type, v_cur);
// Preserve remainder after rounding has been applied. This also allow slow tweaking of values.
g.DragCurrentAccumDirty = false;
if (is_power)
{
FLOATTYPE v_cur_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power);
g.DragCurrentAccum -= (float)(v_cur_norm_curved - v_old_ref_for_accum_remainder);
}
else
{
g.DragCurrentAccum -= (float)((SIGNEDTYPE)v_cur - (SIGNEDTYPE)*v);
}
// Lose zero sign for float/double
if (v_cur == (TYPE)-0)
v_cur = (TYPE)0;
// Clamp values (+ handle overflow/wrap-around for integer types)
if (*v != v_cur && has_min_max)
{
if (v_cur < v_min || (v_cur > *v && adjust_delta < 0.0f && !is_decimal))
v_cur = v_min;
if (v_cur > v_max || (v_cur < *v && adjust_delta > 0.0f && !is_decimal))
v_cur = v_max;
}
// Apply result
if (*v == v_cur)
return false;
*v = v_cur;
return true;
}
bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* v, float v_speed, const void* v_min, const void* v_max, const char* format, float power, ImGuiDragFlags flags)
{
ImGuiContext& g = *GImGui;
if (g.ActiveId == id)
{
if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0])
ClearActiveID();
else if (g.ActiveIdSource == ImGuiInputSource_Nav && g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
ClearActiveID();
}
if (g.ActiveId != id)
return false;
switch (data_type)
{
case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)v; bool r = DragBehaviorT<ImS32, ImS32, float >(ImGuiDataType_S32, &v32, v_speed, v_min ? *(const ImS8*) v_min : IM_S8_MIN, v_max ? *(const ImS8*)v_max : IM_S8_MAX, format, power, flags); if (r) *(ImS8*)v = (ImS8)v32; return r; }
case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)v; bool r = DragBehaviorT<ImU32, ImS32, float >(ImGuiDataType_U32, &v32, v_speed, v_min ? *(const ImU8*) v_min : IM_U8_MIN, v_max ? *(const ImU8*)v_max : IM_U8_MAX, format, power, flags); if (r) *(ImU8*)v = (ImU8)v32; return r; }
case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)v; bool r = DragBehaviorT<ImS32, ImS32, float >(ImGuiDataType_S32, &v32, v_speed, v_min ? *(const ImS16*)v_min : IM_S16_MIN, v_max ? *(const ImS16*)v_max : IM_S16_MAX, format, power, flags); if (r) *(ImS16*)v = (ImS16)v32; return r; }
case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)v; bool r = DragBehaviorT<ImU32, ImS32, float >(ImGuiDataType_U32, &v32, v_speed, v_min ? *(const ImU16*)v_min : IM_U16_MIN, v_max ? *(const ImU16*)v_max : IM_U16_MAX, format, power, flags); if (r) *(ImU16*)v = (ImU16)v32; return r; }
case ImGuiDataType_S32: return DragBehaviorT<ImS32, ImS32, float >(data_type, (ImS32*)v, v_speed, v_min ? *(const ImS32* )v_min : IM_S32_MIN, v_max ? *(const ImS32* )v_max : IM_S32_MAX, format, power, flags);
case ImGuiDataType_U32: return DragBehaviorT<ImU32, ImS32, float >(data_type, (ImU32*)v, v_speed, v_min ? *(const ImU32* )v_min : IM_U32_MIN, v_max ? *(const ImU32* )v_max : IM_U32_MAX, format, power, flags);
case ImGuiDataType_S64: return DragBehaviorT<ImS64, ImS64, double>(data_type, (ImS64*)v, v_speed, v_min ? *(const ImS64* )v_min : IM_S64_MIN, v_max ? *(const ImS64* )v_max : IM_S64_MAX, format, power, flags);
case ImGuiDataType_U64: return DragBehaviorT<ImU64, ImS64, double>(data_type, (ImU64*)v, v_speed, v_min ? *(const ImU64* )v_min : IM_U64_MIN, v_max ? *(const ImU64* )v_max : IM_U64_MAX, format, power, flags);
case ImGuiDataType_Float: return DragBehaviorT<float, float, float >(data_type, (float*)v, v_speed, v_min ? *(const float* )v_min : -FLT_MAX, v_max ? *(const float* )v_max : FLT_MAX, format, power, flags);
case ImGuiDataType_Double: return DragBehaviorT<double,double,double>(data_type, (double*)v, v_speed, v_min ? *(const double*)v_min : -DBL_MAX, v_max ? *(const double*)v_max : DBL_MAX, format, power, flags);
case ImGuiDataType_COUNT: break;
}
IM_ASSERT(0);
return false;
}
bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, float v_speed, const void* v_min, const void* v_max, const char* format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
if (power != 1.0f)
IM_ASSERT(v_min != NULL && v_max != NULL); // When using a power curve the drag needs to have known bounds
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const float w = CalcItemWidth();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id, &frame_bb))
return false;
// Default format string when passing NULL
if (format == NULL)
format = DataTypeGetInfo(data_type)->PrintFmt;
else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) // (FIXME-LEGACY: Patch old "%.0f" format string to use "%d", read function more details.)
format = PatchFormatStringFloatToInt(format);
// Tabbing or CTRL-clicking on Drag turns it into an input box
const bool hovered = ItemHoverable(frame_bb, id);
bool temp_input_is_active = TempInputTextIsActive(id);
bool temp_input_start = false;
if (!temp_input_is_active)
{
const bool focus_requested = FocusableItemRegister(window, id);
const bool clicked = (hovered && g.IO.MouseClicked[0]);
const bool double_clicked = (hovered && g.IO.MouseDoubleClicked[0]);
if (focus_requested || clicked || double_clicked || g.NavActivateId == id || g.NavInputId == id)
{
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
if (focus_requested || (clicked && g.IO.KeyCtrl) || double_clicked || g.NavInputId == id)
{
temp_input_start = true;
FocusableItemUnregister(window);
}
}
}
if (temp_input_is_active || temp_input_start)
return TempInputTextScalar(frame_bb, id, label, data_type, v, format);
// Draw frame
const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
RenderNavHighlight(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
// Drag behavior
const bool value_changed = DragBehavior(id, data_type, v, v_speed, v_min, v_max, format, power, ImGuiDragFlags_None);
if (value_changed)
MarkItemEdited(id);
// Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
char value_buf[64];
const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, v, format);
RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);
return value_changed;
}
bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* v, int components, float v_speed, const void* v_min, const void* v_max, const char* format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components, CalcItemWidth());
size_t type_size = GDataTypeInfo[data_type].Size;
for (int i = 0; i < components; i++)
{
PushID(i);
if (i > 0)
SameLine(0, g.Style.ItemInnerSpacing.x);
value_changed |= DragScalar("", data_type, v, v_speed, v_min, v_max, format, power);
PopID();
PopItemWidth();
v = (void*)((char*)v + type_size);
}
PopID();
const char* label_end = FindRenderedTextEnd(label);
if (label != label_end)
{
SameLine(0, g.Style.ItemInnerSpacing.x);
TextEx(label, label_end);
}
EndGroup();
return value_changed;
}
bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power)
{
return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power);
}
bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power)
{
return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power);
}
bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power)
{
return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power);
}
bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power)
{
return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power);
}
bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
PushID(label);
BeginGroup();
PushMultiItemsWidths(2, CalcItemWidth());
bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format, power);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, format_max ? format_max : format, power);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
TextEx(label, FindRenderedTextEnd(label));
EndGroup();
PopID();
return value_changed;
}
// NB: v_speed is float to allow adjusting the drag speed with more precision
bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format)
{
return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format);
}
bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format)
{
return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format);
}
bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format)
{
return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format);
}
bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format)
{
return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format);
}
bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
PushID(label);
BeginGroup();
PushMultiItemsWidths(2, CalcItemWidth());
bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, format_max ? format_max : format);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
TextEx(label, FindRenderedTextEnd(label));
EndGroup();
PopID();
return value_changed;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc.
//-------------------------------------------------------------------------
// - SliderBehaviorT<>() [Internal]
// - SliderBehavior() [Internal]
// - SliderScalar()
// - SliderScalarN()
// - SliderFloat()
// - SliderFloat2()
// - SliderFloat3()
// - SliderFloat4()
// - SliderAngle()
// - SliderInt()
// - SliderInt2()
// - SliderInt3()
// - SliderInt4()
// - VSliderScalar()
// - VSliderFloat()
// - VSliderInt()
//-------------------------------------------------------------------------
template<typename TYPE, typename FLOATTYPE>
float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos)
{
if (v_min == v_max)
return 0.0f;
const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double);
const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min);
if (is_power)
{
if (v_clamped < 0.0f)
{
const float f = 1.0f - (float)((v_clamped - v_min) / (ImMin((TYPE)0, v_max) - v_min));
return (1.0f - ImPow(f, 1.0f/power)) * linear_zero_pos;
}
else
{
const float f = (float)((v_clamped - ImMax((TYPE)0, v_min)) / (v_max - ImMax((TYPE)0, v_min)));
return linear_zero_pos + ImPow(f, 1.0f/power) * (1.0f - linear_zero_pos);
}
}
// Linear slider
return (float)((FLOATTYPE)(v_clamped - v_min) / (FLOATTYPE)(v_max - v_min));
}
// FIXME: Move some of the code into SliderBehavior(). Current responsability is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc.
template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;
const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
const bool is_power = (power != 1.0f) && is_decimal;
const float grab_padding = 2.0f;
const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f;
float grab_sz = style.GrabMinSize;
SIGNEDTYPE v_range = (v_min < v_max ? v_max - v_min : v_min - v_max);
if (!is_decimal && v_range >= 0) // v_range < 0 may happen on integer overflows
grab_sz = ImMax((float)(slider_sz / (v_range + 1)), style.GrabMinSize); // For integer sliders: if possible have the grab size represent 1 unit
grab_sz = ImMin(grab_sz, slider_sz);
const float slider_usable_sz = slider_sz - grab_sz;
const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5f;
const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f;
// For power curve sliders that cross over sign boundary we want the curve to be symmetric around 0.0f
float linear_zero_pos; // 0.0->1.0f
if (is_power && v_min * v_max < 0.0f)
{
// Different sign
const FLOATTYPE linear_dist_min_to_0 = ImPow(v_min >= 0 ? (FLOATTYPE)v_min : -(FLOATTYPE)v_min, (FLOATTYPE)1.0f / power);
const FLOATTYPE linear_dist_max_to_0 = ImPow(v_max >= 0 ? (FLOATTYPE)v_max : -(FLOATTYPE)v_max, (FLOATTYPE)1.0f / power);
linear_zero_pos = (float)(linear_dist_min_to_0 / (linear_dist_min_to_0 + linear_dist_max_to_0));
}
else
{
// Same sign
linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f;
}
// Process interacting with the slider
bool value_changed = false;
if (g.ActiveId == id)
{
bool set_new_value = false;
float clicked_t = 0.0f;
if (g.ActiveIdSource == ImGuiInputSource_Mouse)
{
if (!g.IO.MouseDown[0])
{
ClearActiveID();
}
else
{
const float mouse_abs_pos = g.IO.MousePos[axis];
clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f;
if (axis == ImGuiAxis_Y)
clicked_t = 1.0f - clicked_t;
set_new_value = true;
}
}
else if (g.ActiveIdSource == ImGuiInputSource_Nav)
{
const ImVec2 delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f);
float delta = (axis == ImGuiAxis_X) ? delta2.x : -delta2.y;
if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
{
ClearActiveID();
}
else if (delta != 0.0f)
{
clicked_t = SliderCalcRatioFromValueT<TYPE,FLOATTYPE>(data_type, *v, v_min, v_max, power, linear_zero_pos);
const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0;
if ((decimal_precision > 0) || is_power)
{
delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds
if (IsNavInputDown(ImGuiNavInput_TweakSlow))
delta /= 10.0f;
}
else
{
if ((v_range >= -100.0f && v_range <= 100.0f) || IsNavInputDown(ImGuiNavInput_TweakSlow))
delta = ((delta < 0.0f) ? -1.0f : +1.0f) / (float)v_range; // Gamepad/keyboard tweak speeds in integer steps
else
delta /= 100.0f;
}
if (IsNavInputDown(ImGuiNavInput_TweakFast))
delta *= 10.0f;
set_new_value = true;
if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits
set_new_value = false;
else
clicked_t = ImSaturate(clicked_t + delta);
}
}
if (set_new_value)
{
TYPE v_new;
if (is_power)
{
// Account for power curve scale on both sides of the zero
if (clicked_t < linear_zero_pos)
{
// Negative: rescale to the negative range before powering
float a = 1.0f - (clicked_t / linear_zero_pos);
a = ImPow(a, power);
v_new = ImLerp(ImMin(v_max, (TYPE)0), v_min, a);
}
else
{
// Positive: rescale to the positive range before powering
float a;
if (ImFabs(linear_zero_pos - 1.0f) > 1.e-6f)
a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos);
else
a = clicked_t;
a = ImPow(a, power);
v_new = ImLerp(ImMax(v_min, (TYPE)0), v_max, a);
}
}
else
{
// Linear slider
if (is_decimal)
{
v_new = ImLerp(v_min, v_max, clicked_t);
}
else
{
// For integer values we want the clicking position to match the grab box so we round above
// This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property..
FLOATTYPE v_new_off_f = (v_max - v_min) * clicked_t;
TYPE v_new_off_floor = (TYPE)(v_new_off_f);
TYPE v_new_off_round = (TYPE)(v_new_off_f + (FLOATTYPE)0.5);
if (!is_decimal && v_new_off_floor < v_new_off_round)
v_new = v_min + v_new_off_round;
else
v_new = v_min + v_new_off_floor;
}
}
// Round to user desired precision based on format string
v_new = RoundScalarWithFormatT<TYPE,SIGNEDTYPE>(format, data_type, v_new);
// Apply result
if (*v != v_new)
{
*v = v_new;
value_changed = true;
}
}
}
if (slider_sz < 1.0f)
{
*out_grab_bb = ImRect(bb.Min, bb.Min);
}
else
{
// Output grab position so it can be displayed by the caller
float grab_t = SliderCalcRatioFromValueT<TYPE, FLOATTYPE>(data_type, *v, v_min, v_max, power, linear_zero_pos);
if (axis == ImGuiAxis_Y)
grab_t = 1.0f - grab_t;
const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
if (axis == ImGuiAxis_X)
*out_grab_bb = ImRect(grab_pos - grab_sz * 0.5f, bb.Min.y + grab_padding, grab_pos + grab_sz * 0.5f, bb.Max.y - grab_padding);
else
*out_grab_bb = ImRect(bb.Min.x + grab_padding, grab_pos - grab_sz * 0.5f, bb.Max.x - grab_padding, grab_pos + grab_sz * 0.5f);
}
return value_changed;
}
// For 32-bits and larger types, slider bounds are limited to half the natural type range.
// So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok.
// It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders.
bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb)
{
switch (data_type)
{
case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)v; bool r = SliderBehaviorT<ImS32, ImS32, float >(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)v_min, *(const ImS8*)v_max, format, power, flags, out_grab_bb); if (r) *(ImS8*)v = (ImS8)v32; return r; }
case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)v; bool r = SliderBehaviorT<ImU32, ImS32, float >(bb, id, ImGuiDataType_U32, &v32, *(const ImU8*)v_min, *(const ImU8*)v_max, format, power, flags, out_grab_bb); if (r) *(ImU8*)v = (ImU8)v32; return r; }
case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)v; bool r = SliderBehaviorT<ImS32, ImS32, float >(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)v_min, *(const ImS16*)v_max, format, power, flags, out_grab_bb); if (r) *(ImS16*)v = (ImS16)v32; return r; }
case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)v; bool r = SliderBehaviorT<ImU32, ImS32, float >(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)v_min, *(const ImU16*)v_max, format, power, flags, out_grab_bb); if (r) *(ImU16*)v = (ImU16)v32; return r; }
case ImGuiDataType_S32:
IM_ASSERT(*(const ImS32*)v_min >= IM_S32_MIN/2 && *(const ImS32*)v_max <= IM_S32_MAX/2);
return SliderBehaviorT<ImS32, ImS32, float >(bb, id, data_type, (ImS32*)v, *(const ImS32*)v_min, *(const ImS32*)v_max, format, power, flags, out_grab_bb);
case ImGuiDataType_U32:
IM_ASSERT(*(const ImU32*)v_min <= IM_U32_MAX/2);
return SliderBehaviorT<ImU32, ImS32, float >(bb, id, data_type, (ImU32*)v, *(const ImU32*)v_min, *(const ImU32*)v_max, format, power, flags, out_grab_bb);
case ImGuiDataType_S64:
IM_ASSERT(*(const ImS64*)v_min >= IM_S64_MIN/2 && *(const ImS64*)v_max <= IM_S64_MAX/2);
return SliderBehaviorT<ImS64, ImS64, double>(bb, id, data_type, (ImS64*)v, *(const ImS64*)v_min, *(const ImS64*)v_max, format, power, flags, out_grab_bb);
case ImGuiDataType_U64:
IM_ASSERT(*(const ImU64*)v_min <= IM_U64_MAX/2);
return SliderBehaviorT<ImU64, ImS64, double>(bb, id, data_type, (ImU64*)v, *(const ImU64*)v_min, *(const ImU64*)v_max, format, power, flags, out_grab_bb);
case ImGuiDataType_Float:
IM_ASSERT(*(const float*)v_min >= -FLT_MAX/2.0f && *(const float*)v_max <= FLT_MAX/2.0f);
return SliderBehaviorT<float, float, float >(bb, id, data_type, (float*)v, *(const float*)v_min, *(const float*)v_max, format, power, flags, out_grab_bb);
case ImGuiDataType_Double:
IM_ASSERT(*(const double*)v_min >= -DBL_MAX/2.0f && *(const double*)v_max <= DBL_MAX/2.0f);
return SliderBehaviorT<double,double,double>(bb, id, data_type, (double*)v, *(const double*)v_min, *(const double*)v_max, format, power, flags, out_grab_bb);
case ImGuiDataType_COUNT: break;
}
IM_ASSERT(0);
return false;
}
bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const float w = CalcItemWidth();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id, &frame_bb))
return false;
// Default format string when passing NULL
if (format == NULL)
format = DataTypeGetInfo(data_type)->PrintFmt;
else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) // (FIXME-LEGACY: Patch old "%.0f" format string to use "%d", read function more details.)
format = PatchFormatStringFloatToInt(format);
// Tabbing or CTRL-clicking on Slider turns it into an input box
const bool hovered = ItemHoverable(frame_bb, id);
bool temp_input_is_active = TempInputTextIsActive(id);
bool temp_input_start = false;
if (!temp_input_is_active)
{
const bool focus_requested = FocusableItemRegister(window, id);
const bool clicked = (hovered && g.IO.MouseClicked[0]);
if (focus_requested || clicked || g.NavActivateId == id || g.NavInputId == id)
{
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
if (focus_requested || (clicked && g.IO.KeyCtrl) || g.NavInputId == id)
{
temp_input_start = true;
FocusableItemUnregister(window);
}
}
}
if (temp_input_is_active || temp_input_start)
return TempInputTextScalar(frame_bb, id, label, data_type, v, format);
// Draw frame
const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
RenderNavHighlight(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);
// Slider behavior
ImRect grab_bb;
const bool value_changed = SliderBehavior(frame_bb, id, data_type, v, v_min, v_max, format, power, ImGuiSliderFlags_None, &grab_bb);
if (value_changed)
MarkItemEdited(id);
// Render grab
if (grab_bb.Max.x > grab_bb.Min.x)
window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
// Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
char value_buf[64];
const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, v, format);
RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);
return value_changed;
}
// Add multiple sliders on 1 line for compact edition of multiple components
bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components, CalcItemWidth());
size_t type_size = GDataTypeInfo[data_type].Size;
for (int i = 0; i < components; i++)
{
PushID(i);
if (i > 0)
SameLine(0, g.Style.ItemInnerSpacing.x);
value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, power);
PopID();
PopItemWidth();
v = (void*)((char*)v + type_size);
}
PopID();
const char* label_end = FindRenderedTextEnd(label);
if (label != label_end)
{
SameLine(0, g.Style.ItemInnerSpacing.x);
TextEx(label, label_end);
}
EndGroup();
return value_changed;
}
bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power)
{
return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power);
}
bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power)
{
return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power);
}
bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power)
{
return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power);
}
bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power)
{
return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power);
}
bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format)
{
if (format == NULL)
format = "%.0f deg";
float v_deg = (*v_rad) * 360.0f / (2*IM_PI);
bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, 1.0f);
*v_rad = v_deg * (2*IM_PI) / 360.0f;
return value_changed;
}
bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format)
{
return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format);
}
bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format)
{
return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format);
}
bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format)
{
return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format);
}
bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format)
{
return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format);
}
bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(bb, style.FramePadding.y);
if (!ItemAdd(frame_bb, id))
return false;
// Default format string when passing NULL
if (format == NULL)
format = DataTypeGetInfo(data_type)->PrintFmt;
else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) // (FIXME-LEGACY: Patch old "%.0f" format string to use "%d", read function more details.)
format = PatchFormatStringFloatToInt(format);
const bool hovered = ItemHoverable(frame_bb, id);
if ((hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || g.NavInputId == id)
{
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
}
// Draw frame
const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
RenderNavHighlight(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);
// Slider behavior
ImRect grab_bb;
const bool value_changed = SliderBehavior(frame_bb, id, data_type, v, v_min, v_max, format, power, ImGuiSliderFlags_Vertical, &grab_bb);
if (value_changed)
MarkItemEdited(id);
// Render grab
if (grab_bb.Max.y > grab_bb.Min.y)
window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
// Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
// For the vertical slider we allow centered text to overlap the frame padding
char value_buf[64];
const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, v, format);
RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.0f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
return value_changed;
}
bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power)
{
return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, power);
}
bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format)
{
return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format);
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc.
//-------------------------------------------------------------------------
// - ImParseFormatFindStart() [Internal]
// - ImParseFormatFindEnd() [Internal]
// - ImParseFormatTrimDecorations() [Internal]
// - ImParseFormatPrecision() [Internal]
// - TempInputTextScalar() [Internal]
// - InputScalar()
// - InputScalarN()
// - InputFloat()
// - InputFloat2()
// - InputFloat3()
// - InputFloat4()
// - InputInt()
// - InputInt2()
// - InputInt3()
// - InputInt4()
// - InputDouble()
//-------------------------------------------------------------------------
// We don't use strchr() because our strings are usually very short and often start with '%'
const char* ImParseFormatFindStart(const char* fmt)
{
while (char c = fmt[0])
{
if (c == '%' && fmt[1] != '%')
return fmt;
else if (c == '%')
fmt++;
fmt++;
}
return fmt;
}
const char* ImParseFormatFindEnd(const char* fmt)
{
// Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format.
if (fmt[0] != '%')
return fmt;
const unsigned int ignored_uppercase_mask = (1 << ('I'-'A')) | (1 << ('L'-'A'));
const unsigned int ignored_lowercase_mask = (1 << ('h'-'a')) | (1 << ('j'-'a')) | (1 << ('l'-'a')) | (1 << ('t'-'a')) | (1 << ('w'-'a')) | (1 << ('z'-'a'));
for (char c; (c = *fmt) != 0; fmt++)
{
if (c >= 'A' && c <= 'Z' && ((1 << (c - 'A')) & ignored_uppercase_mask) == 0)
return fmt + 1;
if (c >= 'a' && c <= 'z' && ((1 << (c - 'a')) & ignored_lowercase_mask) == 0)
return fmt + 1;
}
return fmt;
}
// Extract the format out of a format string with leading or trailing decorations
// fmt = "blah blah" -> return fmt
// fmt = "%.3f" -> return fmt
// fmt = "hello %.3f" -> return fmt + 6
// fmt = "%.3f hello" -> return buf written with "%.3f"
const char* ImParseFormatTrimDecorations(const char* fmt, char* buf, size_t buf_size)
{
const char* fmt_start = ImParseFormatFindStart(fmt);
if (fmt_start[0] != '%')
return fmt;
const char* fmt_end = ImParseFormatFindEnd(fmt_start);
if (fmt_end[0] == 0) // If we only have leading decoration, we don't need to copy the data.
return fmt_start;
ImStrncpy(buf, fmt_start, ImMin((size_t)(fmt_end - fmt_start) + 1, buf_size));
return buf;
}
// Parse display precision back from the display format string
// FIXME: This is still used by some navigation code path to infer a minimum tweak step, but we should aim to rework widgets so it isn't needed.
int ImParseFormatPrecision(const char* fmt, int default_precision)
{
fmt = ImParseFormatFindStart(fmt);
if (fmt[0] != '%')
return default_precision;
fmt++;
while (*fmt >= '0' && *fmt <= '9')
fmt++;
int precision = INT_MAX;
if (*fmt == '.')
{
fmt = ImAtoi<int>(fmt + 1, &precision);
if (precision < 0 || precision > 99)
precision = default_precision;
}
if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation
precision = -1;
if ((*fmt == 'g' || *fmt == 'G') && precision == INT_MAX)
precision = -1;
return (precision == INT_MAX) ? default_precision : precision;
}
// Create text input in place of another active widget (e.g. used when doing a CTRL+Click on drag/slider widgets)
// FIXME: Facilitate using this in variety of other situations.
bool ImGui::TempInputTextScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* data_ptr, const char* format)
{
ImGuiContext& g = *GImGui;
// On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id.
// We clear ActiveID on the first frame to allow the InputText() taking it back.
const bool init = (g.TempInputTextId != id);
if (init)
ClearActiveID();
char fmt_buf[32];
char data_buf[32];
format = ImParseFormatTrimDecorations(format, fmt_buf, IM_ARRAYSIZE(fmt_buf));
DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, data_ptr, format);
ImStrTrimBlanks(data_buf);
g.CurrentWindow->DC.CursorPos = bb.Min;
ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited;
flags |= ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal);
bool value_changed = InputTextEx(label, NULL, data_buf, IM_ARRAYSIZE(data_buf), bb.GetSize(), flags);
if (init)
{
// First frame we started displaying the InputText widget, we expect it to take the active id.
IM_ASSERT(g.ActiveId == id);
g.TempInputTextId = g.ActiveId;
}
if (value_changed)
{
value_changed = DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, NULL);
if (value_changed)
MarkItemEdited(id);
}
return value_changed;
}
bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_ptr, const void* step, const void* step_fast, const char* format, ImGuiInputTextFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
if (format == NULL)
format = DataTypeGetInfo(data_type)->PrintFmt;
char buf[64];
DataTypeFormatString(buf, IM_ARRAYSIZE(buf), data_type, data_ptr, format);
bool value_changed = false;
if ((flags & (ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsScientific)) == 0)
flags |= ImGuiInputTextFlags_CharsDecimal;
flags |= ImGuiInputTextFlags_AutoSelectAll;
flags |= ImGuiInputTextFlags_NoMarkEdited; // We call MarkItemEdited() ourselve by comparing the actual data rather than the string.
if (step != NULL)
{
const float button_size = GetFrameHeight();
BeginGroup(); // The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive()
PushID(label);
SetNextItemWidth(ImMax(1.0f, CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2));
if (InputText("", buf, IM_ARRAYSIZE(buf), flags)) // PushId(label) + "" gives us the expected ID from outside point of view
value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, format);
// Step buttons
const ImVec2 backup_frame_padding = style.FramePadding;
style.FramePadding.x = style.FramePadding.y;
ImGuiButtonFlags button_flags = ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups;
if (flags & ImGuiInputTextFlags_ReadOnly)
button_flags |= ImGuiButtonFlags_Disabled;
SameLine(0, style.ItemInnerSpacing.x);
if (ButtonEx("-", ImVec2(button_size, button_size), button_flags))
{
DataTypeApplyOp(data_type, '-', data_ptr, data_ptr, g.IO.KeyCtrl && step_fast ? step_fast : step);
value_changed = true;
}
SameLine(0, style.ItemInnerSpacing.x);
if (ButtonEx("+", ImVec2(button_size, button_size), button_flags))
{
DataTypeApplyOp(data_type, '+', data_ptr, data_ptr, g.IO.KeyCtrl && step_fast ? step_fast : step);
value_changed = true;
}
const char* label_end = FindRenderedTextEnd(label);
if (label != label_end)
{
SameLine(0, style.ItemInnerSpacing.x);
TextEx(label, label_end);
}
style.FramePadding = backup_frame_padding;
PopID();
EndGroup();
}
else
{
if (InputText(label, buf, IM_ARRAYSIZE(buf), flags))
value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, format);
}
if (value_changed)
MarkItemEdited(window->DC.LastItemId);
return value_changed;
}
bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* step, const void* step_fast, const char* format, ImGuiInputTextFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components, CalcItemWidth());
size_t type_size = GDataTypeInfo[data_type].Size;
for (int i = 0; i < components; i++)
{
PushID(i);
if (i > 0)
SameLine(0, g.Style.ItemInnerSpacing.x);
value_changed |= InputScalar("", data_type, v, step, step_fast, format, flags);
PopID();
PopItemWidth();
v = (void*)((char*)v + type_size);
}
PopID();
const char* label_end = FindRenderedTextEnd(label);
if (label != label_end)
{
SameLine(0.0f, g.Style.ItemInnerSpacing.x);
TextEx(label, label_end);
}
EndGroup();
return value_changed;
}
bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags)
{
flags |= ImGuiInputTextFlags_CharsScientific;
return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), format, flags);
}
bool ImGui::InputFloat2(const char* label, float v[2], const char* format, ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags);
}
bool ImGui::InputFloat3(const char* label, float v[3], const char* format, ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags);
}
bool ImGui::InputFloat4(const char* label, float v[4], const char* format, ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags);
}
// Prefer using "const char* format" directly, which is more flexible and consistent with other API.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags flags)
{
char format[16] = "%f";
if (decimal_precision >= 0)
ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision);
return InputFloat(label, v, step, step_fast, format, flags);
}
bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags flags)
{
char format[16] = "%f";
if (decimal_precision >= 0)
ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision);
return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags);
}
bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags flags)
{
char format[16] = "%f";
if (decimal_precision >= 0)
ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision);
return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags);
}
bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags flags)
{
char format[16] = "%f";
if (decimal_precision >= 0)
ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision);
return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags);
}
#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS
bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags flags)
{
// Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes.
const char* format = (flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d";
return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step>0 ? &step : NULL), (void*)(step_fast>0 ? &step_fast : NULL), format, flags);
}
bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_S32, v, 2, NULL, NULL, "%d", flags);
}
bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_S32, v, 3, NULL, NULL, "%d", flags);
}
bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_S32, v, 4, NULL, NULL, "%d", flags);
}
bool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags)
{
flags |= ImGuiInputTextFlags_CharsScientific;
return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step>0.0 ? &step : NULL), (void*)(step_fast>0.0 ? &step_fast : NULL), format, flags);
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: InputText, InputTextMultiline, InputTextWithHint
//-------------------------------------------------------------------------
// - InputText()
// - InputTextWithHint()
// - InputTextMultiline()
// - InputTextEx() [Internal]
//-------------------------------------------------------------------------
bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
{
IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
return InputTextEx(label, NULL, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data);
}
bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
{
return InputTextEx(label, NULL, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data);
}
bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
{
IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data);
}
static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end)
{
int line_count = 0;
const char* s = text_begin;
while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding
if (c == '\n')
line_count++;
s--;
if (s[0] != '\n' && s[0] != '\r')
line_count++;
*out_text_end = s;
return line_count;
}
static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line)
{
ImGuiContext& g = *GImGui;
ImFont* font = g.Font;
const float line_height = g.FontSize;
const float scale = line_height / font->FontSize;
ImVec2 text_size = ImVec2(0,0);
float line_width = 0.0f;
const ImWchar* s = text_begin;
while (s < text_end)
{
unsigned int c = (unsigned int)(*s++);
if (c == '\n')
{
text_size.x = ImMax(text_size.x, line_width);
text_size.y += line_height;
line_width = 0.0f;
if (stop_on_new_line)
break;
continue;
}
if (c == '\r')
continue;
const float char_width = font->GetCharAdvance((ImWchar)c) * scale;
line_width += char_width;
}
if (text_size.x < line_width)
text_size.x = line_width;
if (out_offset)
*out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n
if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n
text_size.y += line_height;
if (remaining)
*remaining = s;
return text_size;
}
// Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar)
namespace ImStb
{
static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; }
static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->TextW[idx]; }
static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->TextW[line_start_idx + char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *GImGui; return g.Font->GetCharAdvance(c) * (g.FontSize / g.Font->FontSize); }
static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; }
static ImWchar STB_TEXTEDIT_NEWLINE = '\n';
static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx)
{
const ImWchar* text = obj->TextW.Data;
const ImWchar* text_remaining = NULL;
const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true);
r->x0 = 0.0f;
r->x1 = size.x;
r->baseline_y_delta = size.y;
r->ymin = 0.0f;
r->ymax = size.y;
r->num_chars = (int)(text_remaining - (text + line_start_idx));
}
static bool is_separator(unsigned int c) { return ImCharIsBlankW(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; }
static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->TextW[idx-1] ) && !is_separator( obj->TextW[idx] ) ) : 1; }
static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; }
#ifdef __APPLE__ // FIXME: Move setting to IO structure
static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->TextW[idx-1] ) && is_separator( obj->TextW[idx] ) ) : 1; }
static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; }
#else
static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; }
#endif
#define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h
#define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n)
{
ImWchar* dst = obj->TextW.Data + pos;
// We maintain our buffer length in both UTF-8 and wchar formats
obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n);
obj->CurLenW -= n;
// Offset remaining text (FIXME-OPT: Use memmove)
const ImWchar* src = obj->TextW.Data + pos + n;
while (ImWchar c = *src++)
*dst++ = c;
*dst = '\0';
}
static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len)
{
const bool is_resizable = (obj->UserFlags & ImGuiInputTextFlags_CallbackResize) != 0;
const int text_len = obj->CurLenW;
IM_ASSERT(pos <= text_len);
const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len);
if (!is_resizable && (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufCapacityA))
return false;
// Grow internal buffer if needed
if (new_text_len + text_len + 1 > obj->TextW.Size)
{
if (!is_resizable)
return false;
IM_ASSERT(text_len < obj->TextW.Size);
obj->TextW.resize(text_len + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1);
}
ImWchar* text = obj->TextW.Data;
if (pos != text_len)
memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar));
memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar));
obj->CurLenW += new_text_len;
obj->CurLenA += new_text_len_utf8;
obj->TextW[obj->CurLenW] = '\0';
return true;
}
// We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols)
#define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left
#define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right
#define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up
#define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down
#define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line
#define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line
#define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text
#define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text
#define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor
#define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor
#define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo
#define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo
#define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word
#define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word
#define STB_TEXTEDIT_K_SHIFT 0x20000
#define STB_TEXTEDIT_IMPLEMENTATION
#include "imstb_textedit.h"
}
void ImGuiInputTextState::OnKeyPressed(int key)
{
stb_textedit_key(this, &Stb, key);
CursorFollow = true;
CursorAnimReset();
}
ImGuiInputTextCallbackData::ImGuiInputTextCallbackData()
{
memset(this, 0, sizeof(*this));
}
// Public API to manipulate UTF-8 text
// We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar)
// FIXME: The existence of this rarely exercised code path is a bit of a nuisance.
void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count)
{
IM_ASSERT(pos + bytes_count <= BufTextLen);
char* dst = Buf + pos;
const char* src = Buf + pos + bytes_count;
while (char c = *src++)
*dst++ = c;
*dst = '\0';
if (CursorPos + bytes_count >= pos)
CursorPos -= bytes_count;
else if (CursorPos >= pos)
CursorPos = pos;
SelectionStart = SelectionEnd = CursorPos;
BufDirty = true;
BufTextLen -= bytes_count;
}
void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end)
{
const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0;
const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text);
if (new_text_len + BufTextLen >= BufSize)
{
if (!is_resizable)
return;
// Contrary to STB_TEXTEDIT_INSERTCHARS() this is working in the UTF8 buffer, hence the midly similar code (until we remove the U16 buffer alltogether!)
ImGuiContext& g = *GImGui;
ImGuiInputTextState* edit_state = &g.InputTextState;
IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID);
IM_ASSERT(Buf == edit_state->TextA.Data);
int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1;
edit_state->TextA.reserve(new_buf_size + 1);
Buf = edit_state->TextA.Data;
BufSize = edit_state->BufCapacityA = new_buf_size;
}
if (BufTextLen != pos)
memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos));
memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char));
Buf[BufTextLen + new_text_len] = '\0';
if (CursorPos >= pos)
CursorPos += new_text_len;
SelectionStart = SelectionEnd = CursorPos;
BufDirty = true;
BufTextLen += new_text_len;
}
// Return false to discard a character.
static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
{
unsigned int c = *p_char;
// Filter non-printable (NB: isprint is unreliable! see #2467)
if (c < 0x20)
{
bool pass = false;
pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline));
pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput));
if (!pass)
return false;
}
// Filter private Unicode range. GLFW on OSX seems to send private characters for special keys like arrow keys (FIXME)
if (c >= 0xE000 && c <= 0xF8FF)
return false;
// Generic named filters
if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific))
{
if (flags & ImGuiInputTextFlags_CharsDecimal)
if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/'))
return false;
if (flags & ImGuiInputTextFlags_CharsScientific)
if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E'))
return false;
if (flags & ImGuiInputTextFlags_CharsHexadecimal)
if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F'))
return false;
if (flags & ImGuiInputTextFlags_CharsUppercase)
if (c >= 'a' && c <= 'z')
*p_char = (c += (unsigned int)('A'-'a'));
if (flags & ImGuiInputTextFlags_CharsNoBlank)
if (ImCharIsBlankW(c))
return false;
}
// Custom callback filter
if (flags & ImGuiInputTextFlags_CallbackCharFilter)
{
ImGuiInputTextCallbackData callback_data;
memset(&callback_data, 0, sizeof(ImGuiInputTextCallbackData));
callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter;
callback_data.EventChar = (ImWchar)c;
callback_data.Flags = flags;
callback_data.UserData = user_data;
if (callback(&callback_data) != 0)
return false;
*p_char = callback_data.EventChar;
if (!callback_data.EventChar)
return false;
}
return true;
}
// Edit a string of text
// - buf_size account for the zero-terminator, so a buf_size of 6 can hold "Hello" but not "Hello!".
// This is so we can easily call InputText() on static arrays using ARRAYSIZE() and to match
// Note that in std::string world, capacity() would omit 1 byte used by the zero-terminator.
// - When active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while the InputText is active has no effect.
// - If you want to use ImGui::InputText() with std::string, see misc/cpp/imgui_stdlib.h
// (FIXME: Rather confusing and messy function, among the worse part of our codebase, expecting to rewrite a V2 at some point.. Partly because we are
// doing UTF8 > U16 > UTF8 conversions on the go to easily interface with stb_textedit. Ideally should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188)
bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* callback_user_data)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys)
IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key)
ImGuiContext& g = *GImGui;
ImGuiIO& io = g.IO;
const ImGuiStyle& style = g.Style;
const bool RENDER_SELECTION_WHEN_INACTIVE = false;
const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0;
const bool is_readonly = (flags & ImGuiInputTextFlags_ReadOnly) != 0;
const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;
const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0;
const bool is_resizable = (flags & ImGuiInputTextFlags_CallbackResize) != 0;
if (is_resizable)
IM_ASSERT(callback != NULL); // Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag!
if (is_multiline) // Open group before calling GetID() because groups tracks id created within their scope,
BeginGroup();
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f));
ImGuiWindow* draw_window = window;
if (is_multiline)
{
if (!ItemAdd(total_bb, id, &frame_bb))
{
ItemSize(total_bb, style.FramePadding.y);
EndGroup();
return false;
}
if (!BeginChildFrame(id, frame_bb.GetSize()))
{
EndChildFrame();
EndGroup();
return false;
}
draw_window = GetCurrentWindow();
draw_window->DC.NavLayerActiveMaskNext |= draw_window->DC.NavLayerCurrentMask; // This is to ensure that EndChild() will display a navigation highlight
size.x -= draw_window->ScrollbarSizes.x;
}
else
{
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id, &frame_bb))
return false;
}
const bool hovered = ItemHoverable(frame_bb, id);
if (hovered)
g.MouseCursor = ImGuiMouseCursor_TextInput;
// NB: we are only allowed to access 'edit_state' if we are the active widget.
ImGuiInputTextState* state = NULL;
if (g.InputTextState.ID == id)
state = &g.InputTextState;
const bool focus_requested = FocusableItemRegister(window, id);
const bool focus_requested_by_code = focus_requested && (g.FocusRequestCurrWindow == window && g.FocusRequestCurrCounterAll == window->DC.FocusCounterAll);
const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code;
const bool user_clicked = hovered && io.MouseClicked[0];
const bool user_nav_input_start = (g.ActiveId != id) && ((g.NavInputId == id) || (g.NavActivateId == id && g.NavInputSource == ImGuiInputSource_NavKeyboard));
const bool user_scroll_finish = is_multiline && state != NULL && g.ActiveId == 0 && g.ActiveIdPreviousFrame == GetScrollbarID(draw_window, ImGuiAxis_Y);
const bool user_scroll_active = is_multiline && state != NULL && g.ActiveId == GetScrollbarID(draw_window, ImGuiAxis_Y);
bool clear_active_id = false;
bool select_all = (g.ActiveId != id) && ((flags & ImGuiInputTextFlags_AutoSelectAll) != 0 || user_nav_input_start) && (!is_multiline);
const bool init_make_active = (focus_requested || user_clicked || user_scroll_finish || user_nav_input_start);
const bool init_state = (init_make_active || user_scroll_active);
if (init_state && g.ActiveId != id)
{
// Access state even if we don't own it yet.
state = &g.InputTextState;
state->CursorAnimReset();
// Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar)
// From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode)
const int buf_len = (int)strlen(buf);
state->InitialTextA.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string.
memcpy(state->InitialTextA.Data, buf, buf_len + 1);
// Start edition
const char* buf_end = NULL;
state->TextW.resize(buf_size + 1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data is always pointing to at least an empty string.
state->TextA.resize(0);
state->TextAIsValid = false; // TextA is not valid yet (we will display buf until then)
state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, buf_size, buf, NULL, &buf_end);
state->CurLenA = (int)(buf_end - buf); // We can't get the result from ImStrncpy() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8.
// Preserve cursor position and undo/redo stack if we come back to same widget
// FIXME: For non-readonly widgets we might be able to require that TextAIsValid && TextA == buf ? (untested) and discard undo stack if user buffer has changed.
const bool recycle_state = (state->ID == id);
if (recycle_state)
{
// Recycle existing cursor/selection/undo stack but clamp position
// Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
state->CursorClamp();
}
else
{
state->ID = id;
state->ScrollX = 0.0f;
stb_textedit_initialize_state(&state->Stb, !is_multiline);
if (!is_multiline && focus_requested_by_code)
select_all = true;
}
if (flags & ImGuiInputTextFlags_AlwaysInsertMode)
state->Stb.insert_mode = 1;
if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl)))
select_all = true;
}
if (g.ActiveId != id && init_make_active)
{
IM_ASSERT(state && state->ID == id);
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
IM_ASSERT(ImGuiNavInput_COUNT < 32);
g.ActiveIdBlockNavInputFlags = (1 << ImGuiNavInput_Cancel);
if (flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_AllowTabInput)) // Disable keyboard tabbing out as we will use the \t character.
g.ActiveIdBlockNavInputFlags |= (1 << ImGuiNavInput_KeyTab_);
if (!is_multiline && !(flags & ImGuiInputTextFlags_CallbackHistory))
g.ActiveIdAllowNavDirFlags = ((1 << ImGuiDir_Up) | (1 << ImGuiDir_Down));
}
// We have an edge case if ActiveId was set through another widget (e.g. widget being swapped), clear id immediately (don't wait until the end of the function)
if (g.ActiveId == id && state == NULL)
ClearActiveID();
// Release focus when we click outside
if (g.ActiveId == id && io.MouseClicked[0] && !init_state && !init_make_active) //-V560
clear_active_id = true;
// Lock the decision of whether we are going to take the path displaying the cursor or selection
const bool render_cursor = (g.ActiveId == id) || (state && user_scroll_active);
bool render_selection = state && state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor);
bool value_changed = false;
bool enter_pressed = false;
// When read-only we always use the live data passed to the function
// FIXME-OPT: Because our selection/cursor code currently needs the wide text we need to convert it when active, which is not ideal :(
if (is_readonly && state != NULL && (render_cursor || render_selection))
{
const char* buf_end = NULL;
state->TextW.resize(buf_size + 1);
state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, buf, NULL, &buf_end);
state->CurLenA = (int)(buf_end - buf);
state->CursorClamp();
render_selection &= state->HasSelection();
}
// Select the buffer to render.
const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state && state->TextAIsValid;
const bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0);
// Password pushes a temporary font with only a fallback glyph
if (is_password && !is_displaying_hint)
{
const ImFontGlyph* glyph = g.Font->FindGlyph('*');
ImFont* password_font = &g.InputTextPasswordFont;
password_font->FontSize = g.Font->FontSize;
password_font->Scale = g.Font->Scale;
password_font->DisplayOffset = g.Font->DisplayOffset;
password_font->Ascent = g.Font->Ascent;
password_font->Descent = g.Font->Descent;
password_font->ContainerAtlas = g.Font->ContainerAtlas;
password_font->FallbackGlyph = glyph;
password_font->FallbackAdvanceX = glyph->AdvanceX;
IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty());
PushFont(password_font);
}
// Process mouse inputs and character inputs
int backup_current_text_length = 0;
if (g.ActiveId == id)
{
IM_ASSERT(state != NULL);
backup_current_text_length = state->CurLenA;
state->BufCapacityA = buf_size;
state->UserFlags = flags;
state->UserCallback = callback;
state->UserCallbackData = callback_user_data;
// Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
// Down the line we should have a cleaner library-wide concept of Selected vs Active.
g.ActiveIdAllowOverlap = !io.MouseDown[0];
g.WantTextInputNextFrame = 1;
// Edit in progress
const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + state->ScrollX;
const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f));
const bool is_osx = io.ConfigMacOSXBehaviors;
if (select_all || (hovered && !is_osx && io.MouseDoubleClicked[0]))
{
state->SelectAll();
state->SelectedAllMouseLock = true;
}
else if (hovered && is_osx && io.MouseDoubleClicked[0])
{
// Double-click select a word only, OS X style (by simulating keystrokes)
state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT);
state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);
}
else if (io.MouseClicked[0] && !state->SelectedAllMouseLock)
{
if (hovered)
{
stb_textedit_click(state, &state->Stb, mouse_x, mouse_y);
state->CursorAnimReset();
}
}
else if (io.MouseDown[0] && !state->SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))
{
stb_textedit_drag(state, &state->Stb, mouse_x, mouse_y);
state->CursorAnimReset();
state->CursorFollow = true;
}
if (state->SelectedAllMouseLock && !io.MouseDown[0])
state->SelectedAllMouseLock = false;
// It is ill-defined whether the back-end needs to send a \t character when pressing the TAB keys.
// Win32 and GLFW naturally do it but not SDL.
const bool ignore_char_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeySuper);
if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !ignore_char_inputs && !io.KeyShift && !is_readonly)
if (!io.InputQueueCharacters.contains('\t'))
{
unsigned int c = '\t'; // Insert TAB
if (InputTextFilterCharacter(&c, flags, callback, callback_user_data))
state->OnKeyPressed((int)c);
}
// Process regular text input (before we check for Return because using some IME will effectively send a Return?)
// We ignore CTRL inputs, but need to allow ALT+CTRL as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters.
if (io.InputQueueCharacters.Size > 0)
{
if (!ignore_char_inputs && !is_readonly && !user_nav_input_start)
for (int n = 0; n < io.InputQueueCharacters.Size; n++)
{
// Insert character if they pass filtering
unsigned int c = (unsigned int)io.InputQueueCharacters[n];
if (c == '\t' && io.KeyShift)
continue;
if (InputTextFilterCharacter(&c, flags, callback, callback_user_data))
state->OnKeyPressed((int)c);
}
// Consume characters
io.InputQueueCharacters.resize(0);
}
}
// Process other shortcuts/key-presses
bool cancel_edit = false;
if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id)
{
IM_ASSERT(state != NULL);
const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0);
const bool is_osx = io.ConfigMacOSXBehaviors;
const bool is_shortcut_key = (is_osx ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl
const bool is_osx_shift_shortcut = is_osx && io.KeySuper && io.KeyShift && !io.KeyCtrl && !io.KeyAlt;
const bool is_wordmove_key_down = is_osx ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
const bool is_startend_key_down = is_osx && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End
const bool is_ctrl_key_only = io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !io.KeySuper;
const bool is_shift_key_only = io.KeyShift && !io.KeyCtrl && !io.KeyAlt && !io.KeySuper;
const bool is_cut = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Delete))) && !is_readonly && !is_password && (!is_multiline || state->HasSelection());
const bool is_copy = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_C)) || (is_ctrl_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_password && (!is_multiline || state->HasSelection());
const bool is_paste = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_readonly;
const bool is_undo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Z)) && !is_readonly && is_undoable);
const bool is_redo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Y)) || (is_osx_shift_shortcut && IsKeyPressedMap(ImGuiKey_Z))) && !is_readonly && is_undoable;
if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_Home)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_End)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_Delete) && !is_readonly) { state->OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_Backspace) && !is_readonly)
{
if (!state->HasSelection())
{
if (is_wordmove_key_down)
state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT);
else if (is_osx && io.KeySuper && !io.KeyAlt && !io.KeyCtrl)
state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT);
}
state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask);
}
else if (IsKeyPressedMap(ImGuiKey_Enter) || IsKeyPressedMap(ImGuiKey_KeyPadEnter))
{
bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0;
if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl))
{
enter_pressed = clear_active_id = true;
}
else if (!is_readonly)
{
unsigned int c = '\n'; // Insert new line
if (InputTextFilterCharacter(&c, flags, callback, callback_user_data))
state->OnKeyPressed((int)c);
}
}
else if (IsKeyPressedMap(ImGuiKey_Escape))
{
clear_active_id = cancel_edit = true;
}
else if (is_undo || is_redo)
{
state->OnKeyPressed(is_undo ? STB_TEXTEDIT_K_UNDO : STB_TEXTEDIT_K_REDO);
state->ClearSelection();
}
else if (is_shortcut_key && IsKeyPressedMap(ImGuiKey_A))
{
state->SelectAll();
state->CursorFollow = true;
}
else if (is_cut || is_copy)
{
// Cut, Copy
if (io.SetClipboardTextFn)
{
const int ib = state->HasSelection() ? ImMin(state->Stb.select_start, state->Stb.select_end) : 0;
const int ie = state->HasSelection() ? ImMax(state->Stb.select_start, state->Stb.select_end) : state->CurLenW;
const int clipboard_data_len = ImTextCountUtf8BytesFromStr(state->TextW.Data + ib, state->TextW.Data + ie) + 1;
char* clipboard_data = (char*)IM_ALLOC(clipboard_data_len * sizeof(char));
ImTextStrToUtf8(clipboard_data, clipboard_data_len, state->TextW.Data + ib, state->TextW.Data + ie);
SetClipboardText(clipboard_data);
MemFree(clipboard_data);
}
if (is_cut)
{
if (!state->HasSelection())
state->SelectAll();
state->CursorFollow = true;
stb_textedit_cut(state, &state->Stb);
}
}
else if (is_paste)
{
if (const char* clipboard = GetClipboardText())
{
// Filter pasted buffer
const int clipboard_len = (int)strlen(clipboard);
ImWchar* clipboard_filtered = (ImWchar*)IM_ALLOC((clipboard_len+1) * sizeof(ImWchar));
int clipboard_filtered_len = 0;
for (const char* s = clipboard; *s; )
{
unsigned int c;
s += ImTextCharFromUtf8(&c, s, NULL);
if (c == 0)
break;
if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, callback_user_data))
continue;
clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c;
}
clipboard_filtered[clipboard_filtered_len] = 0;
if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation
{
stb_textedit_paste(state, &state->Stb, clipboard_filtered, clipboard_filtered_len);
state->CursorFollow = true;
}
MemFree(clipboard_filtered);
}
}
// Update render selection flag after events have been handled, so selection highlight can be displayed during the same frame.
render_selection |= state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor);
}
// Process callbacks and apply result back to user's buffer.
if (g.ActiveId == id)
{
IM_ASSERT(state != NULL);
const char* apply_new_text = NULL;
int apply_new_text_length = 0;
if (cancel_edit)
{
// Restore initial value. Only return true if restoring to the initial value changes the current buffer contents.
if (!is_readonly && strcmp(buf, state->InitialTextA.Data) != 0)
{
apply_new_text = state->InitialTextA.Data;
apply_new_text_length = state->InitialTextA.Size - 1;
}
}
// When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer before clearing ActiveId, even though strictly speaking it wasn't modified on this frame.
// If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail. Also this allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage.
bool apply_edit_back_to_user_buffer = !cancel_edit || (enter_pressed && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0);
if (apply_edit_back_to_user_buffer)
{
// Apply new value immediately - copy modified buffer back
// Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer
// FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect.
// FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks.
if (!is_readonly)
{
state->TextAIsValid = true;
state->TextA.resize(state->TextW.Size * 4 + 1);
ImTextStrToUtf8(state->TextA.Data, state->TextA.Size, state->TextW.Data, NULL);
}
// User callback
if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0)
{
IM_ASSERT(callback != NULL);
// The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment.
ImGuiInputTextFlags event_flag = 0;
ImGuiKey event_key = ImGuiKey_COUNT;
if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab))
{
event_flag = ImGuiInputTextFlags_CallbackCompletion;
event_key = ImGuiKey_Tab;
}
else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow))
{
event_flag = ImGuiInputTextFlags_CallbackHistory;
event_key = ImGuiKey_UpArrow;
}
else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow))
{
event_flag = ImGuiInputTextFlags_CallbackHistory;
event_key = ImGuiKey_DownArrow;
}
else if (flags & ImGuiInputTextFlags_CallbackAlways)
event_flag = ImGuiInputTextFlags_CallbackAlways;
if (event_flag)
{
ImGuiInputTextCallbackData callback_data;
memset(&callback_data, 0, sizeof(ImGuiInputTextCallbackData));
callback_data.EventFlag = event_flag;
callback_data.Flags = flags;
callback_data.UserData = callback_user_data;
callback_data.EventKey = event_key;
callback_data.Buf = state->TextA.Data;
callback_data.BufTextLen = state->CurLenA;
callback_data.BufSize = state->BufCapacityA;
callback_data.BufDirty = false;
// We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188)
ImWchar* text = state->TextW.Data;
const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + state->Stb.cursor);
const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_start);
const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_end);
// Call user code
callback(&callback_data);
// Read back what user may have modified
IM_ASSERT(callback_data.Buf == state->TextA.Data); // Invalid to modify those fields
IM_ASSERT(callback_data.BufSize == state->BufCapacityA);
IM_ASSERT(callback_data.Flags == flags);
if (callback_data.CursorPos != utf8_cursor_pos) { state->Stb.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); state->CursorFollow = true; }
if (callback_data.SelectionStart != utf8_selection_start) { state->Stb.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); }
if (callback_data.SelectionEnd != utf8_selection_end) { state->Stb.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); }
if (callback_data.BufDirty)
{
IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
if (callback_data.BufTextLen > backup_current_text_length && is_resizable)
state->TextW.resize(state->TextW.Size + (callback_data.BufTextLen - backup_current_text_length));
state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, callback_data.Buf, NULL);
state->CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
state->CursorAnimReset();
}
}
}
// Will copy result string if modified
if (!is_readonly && strcmp(state->TextA.Data, buf) != 0)
{
apply_new_text = state->TextA.Data;
apply_new_text_length = state->CurLenA;
}
}
// Copy result to user buffer
if (apply_new_text)
{
IM_ASSERT(apply_new_text_length >= 0);
if (backup_current_text_length != apply_new_text_length && is_resizable)
{
ImGuiInputTextCallbackData callback_data;
callback_data.EventFlag = ImGuiInputTextFlags_CallbackResize;
callback_data.Flags = flags;
callback_data.Buf = buf;
callback_data.BufTextLen = apply_new_text_length;
callback_data.BufSize = ImMax(buf_size, apply_new_text_length + 1);
callback_data.UserData = callback_user_data;
callback(&callback_data);
buf = callback_data.Buf;
buf_size = callback_data.BufSize;
apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1);
IM_ASSERT(apply_new_text_length <= buf_size);
}
// If the underlying buffer resize was denied or not carried to the next frame, apply_new_text_length+1 may be >= buf_size.
ImStrncpy(buf, apply_new_text, ImMin(apply_new_text_length + 1, buf_size));
value_changed = true;
}
// Clear temporary user storage
state->UserFlags = 0;
state->UserCallback = NULL;
state->UserCallbackData = NULL;
}
// Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value)
if (clear_active_id && g.ActiveId == id)
ClearActiveID();
// Render frame
if (!is_multiline)
{
RenderNavHighlight(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
}
const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size
ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding;
ImVec2 text_size(0.0f, 0.0f);
// Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line
// without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether.
// Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash.
const int buf_display_max_length = 2 * 1024 * 1024;
const char* buf_display = buf_display_from_state ? state->TextA.Data : buf; //-V595
const char* buf_display_end = NULL; // We have specialized paths below for setting the length
if (is_displaying_hint)
{
buf_display = hint;
buf_display_end = hint + strlen(hint);
}
// Render text. We currently only render selection when the widget is active or while scrolling.
// FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive.
if (render_cursor || render_selection)
{
IM_ASSERT(state != NULL);
if (!is_displaying_hint)
buf_display_end = buf_display + state->CurLenA;
// Render text (with cursor and selection)
// This is going to be messy. We need to:
// - Display the text (this alone can be more easily clipped)
// - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation)
// - Measure text height (for scrollbar)
// We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort)
// FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
const ImWchar* text_begin = state->TextW.Data;
ImVec2 cursor_offset, select_start_offset;
{
// Find lines numbers straddling 'cursor' (slot 0) and 'select_start' (slot 1) positions.
const ImWchar* searches_input_ptr[2] = { NULL, NULL };
int searches_result_line_no[2] = { -1000, -1000 };
int searches_remaining = 0;
if (render_cursor)
{
searches_input_ptr[0] = text_begin + state->Stb.cursor;
searches_result_line_no[0] = -1;
searches_remaining++;
}
if (render_selection)
{
searches_input_ptr[1] = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end);
searches_result_line_no[1] = -1;
searches_remaining++;
}
// Iterate all lines to find our line numbers
// In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter.
searches_remaining += is_multiline ? 1 : 0;
int line_count = 0;
//for (const ImWchar* s = text_begin; (s = (const ImWchar*)wcschr((const wchar_t*)s, (wchar_t)'\n')) != NULL; s++) // FIXME-OPT: Could use this when wchar_t are 16-bits
for (const ImWchar* s = text_begin; *s != 0; s++)
if (*s == '\n')
{
line_count++;
if (searches_result_line_no[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_no[0] = line_count; if (--searches_remaining <= 0) break; }
if (searches_result_line_no[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_no[1] = line_count; if (--searches_remaining <= 0) break; }
}
line_count++;
if (searches_result_line_no[0] == -1)
searches_result_line_no[0] = line_count;
if (searches_result_line_no[1] == -1)
searches_result_line_no[1] = line_count;
// Calculate 2d position by finding the beginning of the line and measuring distance
cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x;
cursor_offset.y = searches_result_line_no[0] * g.FontSize;
if (searches_result_line_no[1] >= 0)
{
select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x;
select_start_offset.y = searches_result_line_no[1] * g.FontSize;
}
// Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224)
if (is_multiline)
text_size = ImVec2(size.x, line_count * g.FontSize);
}
// Scroll
if (render_cursor && state->CursorFollow)
{
// Horizontal scroll in chunks of quarter width
if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll))
{
const float scroll_increment_x = size.x * 0.25f;
if (cursor_offset.x < state->ScrollX)
state->ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x);
else if (cursor_offset.x - size.x >= state->ScrollX)
state->ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x);
}
else
{
state->ScrollX = 0.0f;
}
// Vertical scroll
if (is_multiline)
{
float scroll_y = draw_window->Scroll.y;
if (cursor_offset.y - g.FontSize < scroll_y)
scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize);
else if (cursor_offset.y - size.y >= scroll_y)
scroll_y = cursor_offset.y - size.y;
draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag
draw_window->Scroll.y = scroll_y;
}
state->CursorFollow = false;
}
// Draw selection
const ImVec2 draw_scroll = ImVec2(state->ScrollX, 0.0f);
if (render_selection)
{
const ImWchar* text_selected_begin = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end);
const ImWchar* text_selected_end = text_begin + ImMax(state->Stb.select_start, state->Stb.select_end);
ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests.
float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection.
float bg_offy_dn = is_multiline ? 0.0f : 2.0f;
ImVec2 rect_pos = draw_pos + select_start_offset - draw_scroll;
for (const ImWchar* p = text_selected_begin; p < text_selected_end; )
{
if (rect_pos.y > clip_rect.w + g.FontSize)
break;
if (rect_pos.y < clip_rect.y)
{
//p = (const ImWchar*)wmemchr((const wchar_t*)p, '\n', text_selected_end - p); // FIXME-OPT: Could use this when wchar_t are 16-bits
//p = p ? p + 1 : text_selected_end;
while (p < text_selected_end)
if (*p++ == '\n')
break;
}
else
{
ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true);
if (rect_size.x <= 0.0f) rect_size.x = (float)(int)(g.Font->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines
ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn));
rect.ClipWith(clip_rect);
if (rect.Overlaps(clip_rect))
draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
}
rect_pos.x = draw_pos.x - draw_scroll.x;
rect_pos.y += g.FontSize;
}
}
// We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash.
if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)
{
ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);
}
// Draw blinking cursor
if (render_cursor)
{
state->CursorAnim += io.DeltaTime;
bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f;
ImVec2 cursor_screen_pos = draw_pos + cursor_offset - draw_scroll;
ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f);
if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect))
draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text));
// Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.)
if (!is_readonly)
g.PlatformImePos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize);
}
}
else
{
// Render text only (no selection, no cursor)
if (is_multiline)
text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_display_end) * g.FontSize); // We don't need width
else if (!is_displaying_hint && g.ActiveId == id)
buf_display_end = buf_display + state->CurLenA;
else if (!is_displaying_hint)
buf_display_end = buf_display + strlen(buf_display);
if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)
{
ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);
}
}
if (is_multiline)
{
Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line
EndChildFrame();
EndGroup();
}
if (is_password && !is_displaying_hint)
PopFont();
// Log as text
if (g.LogEnabled && !(is_password && !is_displaying_hint))
LogRenderedText(&draw_pos, buf_display, buf_display_end);
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
if (value_changed && !(flags & ImGuiInputTextFlags_NoMarkEdited))
MarkItemEdited(id);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);
if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)
return enter_pressed;
else
return value_changed;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc.
//-------------------------------------------------------------------------
// - ColorEdit3()
// - ColorEdit4()
// - ColorPicker3()
// - RenderColorRectWithAlphaCheckerboard() [Internal]
// - ColorPicker4()
// - ColorButton()
// - SetColorEditOptions()
// - ColorTooltip() [Internal]
// - ColorEditOptionsPopup() [Internal]
// - ColorPickerOptionsPopup() [Internal]
//-------------------------------------------------------------------------
bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags)
{
return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha);
}
// Edit colors components (each component in 0.0f..1.0f range).
// See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
// With typical options: Left-click on colored square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item.
bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const float square_sz = GetFrameHeight();
const float w_full = CalcItemWidth();
const float w_button = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x);
const float w_inputs = w_full - w_button;
const char* label_display_end = FindRenderedTextEnd(label);
g.NextItemData.ClearFlags();
BeginGroup();
PushID(label);
// If we're not showing any slider there's no point in doing any HSV conversions
const ImGuiColorEditFlags flags_untouched = flags;
if (flags & ImGuiColorEditFlags_NoInputs)
flags = (flags & (~ImGuiColorEditFlags__DisplayMask)) | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_NoOptions;
// Context menu: display and modify options (before defaults are applied)
if (!(flags & ImGuiColorEditFlags_NoOptions))
ColorEditOptionsPopup(col, flags);
// Read stored options
if (!(flags & ImGuiColorEditFlags__DisplayMask))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DisplayMask);
if (!(flags & ImGuiColorEditFlags__DataTypeMask))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DataTypeMask);
if (!(flags & ImGuiColorEditFlags__PickerMask))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags__PickerMask);
if (!(flags & ImGuiColorEditFlags__InputMask))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags__InputMask);
flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__DisplayMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags__InputMask));
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DisplayMask)); // Check that only 1 is selected
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__InputMask)); // Check that only 1 is selected
const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0;
const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0;
const int components = alpha ? 4 : 3;
// Convert to the formats we need
float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f };
if ((flags & ImGuiColorEditFlags_InputHSV) && (flags & ImGuiColorEditFlags_DisplayRGB))
ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
else if ((flags & ImGuiColorEditFlags_InputRGB) && (flags & ImGuiColorEditFlags_DisplayHSV))
ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) };
bool value_changed = false;
bool value_changed_as_float = false;
const ImVec2 pos = window->DC.CursorPos;
const float inputs_offset_x = (style.ColorButtonPosition == ImGuiDir_Left) ? w_button : 0.0f;
window->DC.CursorPos.x = pos.x + inputs_offset_x;
if ((flags & (ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
{
// RGB/HSV 0..255 Sliders
const float w_item_one = ImMax(1.0f, (float)(int)((w_inputs - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
const float w_item_last = ImMax(1.0f, (float)(int)(w_inputs - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x);
static const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
static const char* fmt_table_int[3][4] =
{
{ "%3d", "%3d", "%3d", "%3d" }, // Short display
{ "R:%3d", "G:%3d", "B:%3d", "A:%3d" }, // Long display for RGBA
{ "H:%3d", "S:%3d", "V:%3d", "A:%3d" } // Long display for HSVA
};
static const char* fmt_table_float[3][4] =
{
{ "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display
{ "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA
{ "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA
};
const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_DisplayHSV) ? 2 : 1;
for (int n = 0; n < components; n++)
{
if (n > 0)
SameLine(0, style.ItemInnerSpacing.x);
SetNextItemWidth((n + 1 < components) ? w_item_one : w_item_last);
if (flags & ImGuiColorEditFlags_Float)
{
value_changed |= DragFloat(ids[n], &f[n], 1.0f/255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]);
value_changed_as_float |= value_changed;
}
else
{
value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]);
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
}
}
else if ((flags & ImGuiColorEditFlags_DisplayHex) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
{
// RGB Hexadecimal Input
char buf[64];
if (alpha)
ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255), ImClamp(i[3],0,255));
else
ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255));
SetNextItemWidth(w_inputs);
if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase))
{
value_changed = true;
char* p = buf;
while (*p == '#' || ImCharIsBlankA(*p))
p++;
i[0] = i[1] = i[2] = i[3] = 0;
if (alpha)
sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned)
else
sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]);
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
}
ImGuiWindow* picker_active_window = NULL;
if (!(flags & ImGuiColorEditFlags_NoSmallPreview))
{
const float button_offset_x = ((flags & ImGuiColorEditFlags_NoInputs) || (style.ColorButtonPosition == ImGuiDir_Left)) ? 0.0f : w_inputs + style.ItemInnerSpacing.x;
window->DC.CursorPos = ImVec2(pos.x + button_offset_x, pos.y);
const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f);
if (ColorButton("##ColorButton", col_v4, flags))
{
if (!(flags & ImGuiColorEditFlags_NoPicker))
{
// Store current color and open a picker
g.ColorPickerRef = col_v4;
OpenPopup("picker");
SetNextWindowPos(window->DC.LastItemRect.GetBL() + ImVec2(-1,style.ItemSpacing.y));
}
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
if (BeginPopup("picker"))
{
picker_active_window = g.CurrentWindow;
if (label != label_display_end)
{
TextEx(label, label_display_end);
Spacing();
}
ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar;
ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__DisplayMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf;
SetNextItemWidth(square_sz * 12.0f); // Use 256 + bar sizes?
value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x);
EndPopup();
}
}
if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel))
{
window->DC.CursorPos = ImVec2(pos.x + w_full + style.ItemInnerSpacing.x, pos.y + style.FramePadding.y);
TextEx(label, label_display_end);
}
// Convert back
if (value_changed && picker_active_window == NULL)
{
if (!value_changed_as_float)
for (int n = 0; n < 4; n++)
f[n] = i[n] / 255.0f;
if ((flags & ImGuiColorEditFlags_DisplayHSV) && (flags & ImGuiColorEditFlags_InputRGB))
ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
if ((flags & ImGuiColorEditFlags_DisplayRGB) && (flags & ImGuiColorEditFlags_InputHSV))
ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
col[0] = f[0];
col[1] = f[1];
col[2] = f[2];
if (alpha)
col[3] = f[3];
}
PopID();
EndGroup();
// Drag and Drop Target
// NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test.
if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropTarget())
{
bool accepted_drag_drop = false;
if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
{
memcpy((float*)col, payload->Data, sizeof(float) * 3); // Preserve alpha if any //-V512
value_changed = accepted_drag_drop = true;
}
if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
{
memcpy((float*)col, payload->Data, sizeof(float) * components);
value_changed = accepted_drag_drop = true;
}
// Drag-drop payloads are always RGB
if (accepted_drag_drop && (flags & ImGuiColorEditFlags_InputHSV))
ColorConvertRGBtoHSV(col[0], col[1], col[2], col[0], col[1], col[2]);
EndDragDropTarget();
}
// When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4().
if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window)
window->DC.LastItemId = g.ActiveId;
if (value_changed)
MarkItemEdited(window->DC.LastItemId);
return value_changed;
}
bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags)
{
float col4[4] = { col[0], col[1], col[2], 1.0f };
if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha))
return false;
col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2];
return true;
}
static inline ImU32 ImAlphaBlendColor(ImU32 col_a, ImU32 col_b)
{
float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
return IM_COL32(r, g, b, 0xFF);
}
// Helper for ColorPicker4()
// NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that.
// I spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding alltogether.
void ImGui::RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, int rounding_corners_flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF)
{
ImU32 col_bg1 = GetColorU32(ImAlphaBlendColor(IM_COL32(204,204,204,255), col));
ImU32 col_bg2 = GetColorU32(ImAlphaBlendColor(IM_COL32(128,128,128,255), col));
window->DrawList->AddRectFilled(p_min, p_max, col_bg1, rounding, rounding_corners_flags);
int yi = 0;
for (float y = p_min.y + grid_off.y; y < p_max.y; y += grid_step, yi++)
{
float y1 = ImClamp(y, p_min.y, p_max.y), y2 = ImMin(y + grid_step, p_max.y);
if (y2 <= y1)
continue;
for (float x = p_min.x + grid_off.x + (yi & 1) * grid_step; x < p_max.x; x += grid_step * 2.0f)
{
float x1 = ImClamp(x, p_min.x, p_max.x), x2 = ImMin(x + grid_step, p_max.x);
if (x2 <= x1)
continue;
int rounding_corners_flags_cell = 0;
if (y1 <= p_min.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopRight; }
if (y2 >= p_max.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotRight; }
rounding_corners_flags_cell &= rounding_corners_flags;
window->DrawList->AddRectFilled(ImVec2(x1,y1), ImVec2(x2,y2), col_bg2, rounding_corners_flags_cell ? rounding : 0.0f, rounding_corners_flags_cell);
}
}
}
else
{
window->DrawList->AddRectFilled(p_min, p_max, col, rounding, rounding_corners_flags);
}
}
// Helper for ColorPicker4()
static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w)
{
ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32_BLACK);
ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32_WHITE);
ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32_BLACK);
ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32_WHITE);
}
// Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
// (In C++ the 'float col[4]' notation for a function argument is equivalent to 'float* col', we only specify a size to facilitate understanding of the code.)
// FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..)
bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImDrawList* draw_list = window->DrawList;
ImGuiStyle& style = g.Style;
ImGuiIO& io = g.IO;
const float width = CalcItemWidth();
g.NextItemData.ClearFlags();
PushID(label);
BeginGroup();
if (!(flags & ImGuiColorEditFlags_NoSidePreview))
flags |= ImGuiColorEditFlags_NoSmallPreview;
// Context menu: display and store options.
if (!(flags & ImGuiColorEditFlags_NoOptions))
ColorPickerOptionsPopup(col, flags);
// Read stored options
if (!(flags & ImGuiColorEditFlags__PickerMask))
flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__PickerMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__PickerMask;
if (!(flags & ImGuiColorEditFlags__InputMask))
flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__InputMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__InputMask;
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__PickerMask)); // Check that only 1 is selected
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__InputMask)); // Check that only 1 is selected
if (!(flags & ImGuiColorEditFlags_NoOptions))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar);
// Setup
int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4;
bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha);
ImVec2 picker_pos = window->DC.CursorPos;
float square_sz = GetFrameHeight();
float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars
float sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box
float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x;
float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x;
float bars_triangles_half_sz = (float)(int)(bars_width * 0.20f);
float backup_initial_col[4];
memcpy(backup_initial_col, col, components * sizeof(float));
float wheel_thickness = sv_picker_size * 0.08f;
float wheel_r_outer = sv_picker_size * 0.50f;
float wheel_r_inner = wheel_r_outer - wheel_thickness;
ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size*0.5f);
// Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic.
float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f);
ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point.
ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point.
ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point.
float H = col[0], S = col[1], V = col[2];
float R = col[0], G = col[1], B = col[2];
if (flags & ImGuiColorEditFlags_InputRGB)
ColorConvertRGBtoHSV(R, G, B, H, S, V);
else if (flags & ImGuiColorEditFlags_InputHSV)
ColorConvertHSVtoRGB(H, S, V, R, G, B);
bool value_changed = false, value_changed_h = false, value_changed_sv = false;
PushItemFlag(ImGuiItemFlags_NoNav, true);
if (flags & ImGuiColorEditFlags_PickerHueWheel)
{
// Hue wheel + SV triangle logic
InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size));
if (IsItemActive())
{
ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center;
ImVec2 current_off = g.IO.MousePos - wheel_center;
float initial_dist2 = ImLengthSqr(initial_off);
if (initial_dist2 >= (wheel_r_inner-1)*(wheel_r_inner-1) && initial_dist2 <= (wheel_r_outer+1)*(wheel_r_outer+1))
{
// Interactive with Hue wheel
H = ImAtan2(current_off.y, current_off.x) / IM_PI*0.5f;
if (H < 0.0f)
H += 1.0f;
value_changed = value_changed_h = true;
}
float cos_hue_angle = ImCos(-H * 2.0f * IM_PI);
float sin_hue_angle = ImSin(-H * 2.0f * IM_PI);
if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle)))
{
// Interacting with SV triangle
ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle);
if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated))
current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated);
float uu, vv, ww;
ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww);
V = ImClamp(1.0f - vv, 0.0001f, 1.0f);
S = ImClamp(uu / V, 0.0001f, 1.0f);
value_changed = value_changed_sv = true;
}
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
}
else if (flags & ImGuiColorEditFlags_PickerHueBar)
{
// SV rectangle logic
InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size));
if (IsItemActive())
{
S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size-1));
V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
value_changed = value_changed_sv = true;
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
// Hue bar logic
SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y));
InvisibleButton("hue", ImVec2(bars_width, sv_picker_size));
if (IsItemActive())
{
H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
value_changed = value_changed_h = true;
}
}
// Alpha bar logic
if (alpha_bar)
{
SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y));
InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size));
if (IsItemActive())
{
col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
value_changed = true;
}
}
PopItemFlag(); // ImGuiItemFlags_NoNav
if (!(flags & ImGuiColorEditFlags_NoSidePreview))
{
SameLine(0, style.ItemInnerSpacing.x);
BeginGroup();
}
if (!(flags & ImGuiColorEditFlags_NoLabel))
{
const char* label_display_end = FindRenderedTextEnd(label);
if (label != label_display_end)
{
if ((flags & ImGuiColorEditFlags_NoSidePreview))
SameLine(0, style.ItemInnerSpacing.x);
TextEx(label, label_display_end);
}
}
if (!(flags & ImGuiColorEditFlags_NoSidePreview))
{
PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true);
ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
if ((flags & ImGuiColorEditFlags_NoLabel))
Text("Current");
ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_NoTooltip;
ColorButton("##current", col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2));
if (ref_col != NULL)
{
Text("Original");
ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]);
if (ColorButton("##original", ref_col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2)))
{
memcpy(col, ref_col, components * sizeof(float));
value_changed = true;
}
}
PopItemFlag();
EndGroup();
}
// Convert back color to RGB
if (value_changed_h || value_changed_sv)
{
if (flags & ImGuiColorEditFlags_InputRGB)
{
ColorConvertHSVtoRGB(H >= 1.0f ? H - 10 * 1e-6f : H, S > 0.0f ? S : 10*1e-6f, V > 0.0f ? V : 1e-6f, col[0], col[1], col[2]);
}
else if (flags & ImGuiColorEditFlags_InputHSV)
{
col[0] = H;
col[1] = S;
col[2] = V;
}
}
// R,G,B and H,S,V slider color editor
bool value_changed_fix_hue_wrap = false;
if ((flags & ImGuiColorEditFlags_NoInputs) == 0)
{
PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x);
ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf;
ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker;
if (flags & ImGuiColorEditFlags_DisplayRGB || (flags & ImGuiColorEditFlags__DisplayMask) == 0)
if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_DisplayRGB))
{
// FIXME: Hackily differenciating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget.
// For the later we don't want to run the hue-wrap canceling code. If you are well versed in HSV picker please provide your input! (See #2050)
value_changed_fix_hue_wrap = (g.ActiveId != 0 && !g.ActiveIdAllowOverlap);
value_changed = true;
}
if (flags & ImGuiColorEditFlags_DisplayHSV || (flags & ImGuiColorEditFlags__DisplayMask) == 0)
value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_DisplayHSV);
if (flags & ImGuiColorEditFlags_DisplayHex || (flags & ImGuiColorEditFlags__DisplayMask) == 0)
value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_DisplayHex);
PopItemWidth();
}
// Try to cancel hue wrap (after ColorEdit4 call), if any
if (value_changed_fix_hue_wrap && (flags & ImGuiColorEditFlags_InputRGB))
{
float new_H, new_S, new_V;
ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V);
if (new_H <= 0 && H > 0)
{
if (new_V <= 0 && V != new_V)
ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]);
else if (new_S <= 0)
ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]);
}
}
if (value_changed)
{
if (flags & ImGuiColorEditFlags_InputRGB)
{
R = col[0];
G = col[1];
B = col[2];
ColorConvertRGBtoHSV(R, G, B, H, S, V);
}
else if (flags & ImGuiColorEditFlags_InputHSV)
{
H = col[0];
S = col[1];
V = col[2];
ColorConvertHSVtoRGB(H, S, V, R, G, B);
}
}
ImVec4 hue_color_f(1, 1, 1, 1); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z);
ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f);
ImU32 col32_no_alpha = ColorConvertFloat4ToU32(ImVec4(R, G, B, 1.0f));
const ImU32 hue_colors[6+1] = { IM_COL32(255,0,0,255), IM_COL32(255,255,0,255), IM_COL32(0,255,0,255), IM_COL32(0,255,255,255), IM_COL32(0,0,255,255), IM_COL32(255,0,255,255), IM_COL32(255,0,0,255) };
ImVec2 sv_cursor_pos;
if (flags & ImGuiColorEditFlags_PickerHueWheel)
{
// Render Hue Wheel
const float aeps = 1.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out).
const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12);
for (int n = 0; n < 6; n++)
{
const float a0 = (n) /6.0f * 2.0f * IM_PI - aeps;
const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps;
const int vert_start_idx = draw_list->VtxBuffer.Size;
draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc);
draw_list->PathStroke(IM_COL32_WHITE, false, wheel_thickness);
const int vert_end_idx = draw_list->VtxBuffer.Size;
// Paint colors over existing vertices
ImVec2 gradient_p0(wheel_center.x + ImCos(a0) * wheel_r_inner, wheel_center.y + ImSin(a0) * wheel_r_inner);
ImVec2 gradient_p1(wheel_center.x + ImCos(a1) * wheel_r_inner, wheel_center.y + ImSin(a1) * wheel_r_inner);
ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, hue_colors[n], hue_colors[n+1]);
}
// Render Cursor + preview on Hue Wheel
float cos_hue_angle = ImCos(H * 2.0f * IM_PI);
float sin_hue_angle = ImSin(H * 2.0f * IM_PI);
ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f);
float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f;
int hue_cursor_segments = ImClamp((int)(hue_cursor_rad / 1.4f), 9, 32);
draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments);
draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad+1, IM_COL32(128,128,128,255), hue_cursor_segments);
draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, IM_COL32_WHITE, hue_cursor_segments);
// Render SV triangle (rotated according to hue)
ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle);
ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle);
ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle);
ImVec2 uv_white = GetFontTexUvWhitePixel();
draw_list->PrimReserve(6, 6);
draw_list->PrimVtx(tra, uv_white, hue_color32);
draw_list->PrimVtx(trb, uv_white, hue_color32);
draw_list->PrimVtx(trc, uv_white, IM_COL32_WHITE);
draw_list->PrimVtx(tra, uv_white, IM_COL32_BLACK_TRANS);
draw_list->PrimVtx(trb, uv_white, IM_COL32_BLACK);
draw_list->PrimVtx(trc, uv_white, IM_COL32_BLACK_TRANS);
draw_list->AddTriangle(tra, trb, trc, IM_COL32(128,128,128,255), 1.5f);
sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V));
}
else if (flags & ImGuiColorEditFlags_PickerHueBar)
{
// Render SV Square
draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_WHITE, hue_color32, hue_color32, IM_COL32_WHITE);
draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_BLACK_TRANS, IM_COL32_BLACK_TRANS, IM_COL32_BLACK, IM_COL32_BLACK);
RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), 0.0f);
sv_cursor_pos.x = ImClamp((float)(int)(picker_pos.x + ImSaturate(S) * sv_picker_size + 0.5f), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much
sv_cursor_pos.y = ImClamp((float)(int)(picker_pos.y + ImSaturate(1 - V) * sv_picker_size + 0.5f), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2);
// Render Hue Bar
for (int i = 0; i < 6; ++i)
draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), hue_colors[i], hue_colors[i], hue_colors[i + 1], hue_colors[i + 1]);
float bar0_line_y = (float)(int)(picker_pos.y + H * sv_picker_size + 0.5f);
RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f);
RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f);
}
// Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range)
float sv_cursor_rad = value_changed_sv ? 10.0f : 6.0f;
draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, col32_no_alpha, 12);
draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad+1, IM_COL32(128,128,128,255), 12);
draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, IM_COL32_WHITE, 12);
// Render alpha bar
if (alpha_bar)
{
float alpha = ImSaturate(col[3]);
ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size);
RenderColorRectWithAlphaCheckerboard(bar1_bb.Min, bar1_bb.Max, IM_COL32(0,0,0,0), bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f));
draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, col32_no_alpha, col32_no_alpha, col32_no_alpha & ~IM_COL32_A_MASK, col32_no_alpha & ~IM_COL32_A_MASK);
float bar1_line_y = (float)(int)(picker_pos.y + (1.0f - alpha) * sv_picker_size + 0.5f);
RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f);
RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f);
}
EndGroup();
if (value_changed && memcmp(backup_initial_col, col, components * sizeof(float)) == 0)
value_changed = false;
if (value_changed)
MarkItemEdited(window->DC.LastItemId);
PopID();
return value_changed;
}
// A little colored square. Return true when clicked.
// FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip.
// 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip.
// Note that 'col' may be encoded in HSV if ImGuiColorEditFlags_InputHSV is set.
bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, ImVec2 size)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiID id = window->GetID(desc_id);
float default_size = GetFrameHeight();
if (size.x == 0.0f)
size.x = default_size;
if (size.y == 0.0f)
size.y = default_size;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
if (flags & ImGuiColorEditFlags_NoAlpha)
flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf);
ImVec4 col_rgb = col;
if (flags & ImGuiColorEditFlags_InputHSV)
ColorConvertHSVtoRGB(col_rgb.x, col_rgb.y, col_rgb.z, col_rgb.x, col_rgb.y, col_rgb.z);
ImVec4 col_rgb_without_alpha(col_rgb.x, col_rgb.y, col_rgb.z, 1.0f);
float grid_step = ImMin(size.x, size.y) / 2.99f;
float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f);
ImRect bb_inner = bb;
float off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts.
bb_inner.Expand(off);
if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f)
{
float mid_x = (float)(int)((bb_inner.Min.x + bb_inner.Max.x) * 0.5f + 0.5f);
RenderColorRectWithAlphaCheckerboard(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawCornerFlags_TopRight| ImDrawCornerFlags_BotRight);
window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotLeft);
}
else
{
// Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha
ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col_rgb : col_rgb_without_alpha;
if (col_source.w < 1.0f)
RenderColorRectWithAlphaCheckerboard(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding);
else
window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding, ImDrawCornerFlags_All);
}
RenderNavHighlight(bb, id);
if (g.Style.FrameBorderSize > 0.0f)
RenderFrameBorder(bb.Min, bb.Max, rounding);
else
window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border
// Drag and Drop Source
// NB: The ActiveId test is merely an optional micro-optimization, BeginDragDropSource() does the same test.
if (g.ActiveId == id && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropSource())
{
if (flags & ImGuiColorEditFlags_NoAlpha)
SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col_rgb, sizeof(float) * 3, ImGuiCond_Once);
else
SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col_rgb, sizeof(float) * 4, ImGuiCond_Once);
ColorButton(desc_id, col, flags);
SameLine();
TextEx("Color");
EndDragDropSource();
}
// Tooltip
if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered)
ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf));
return pressed;
}
// Initialize/override default color options
void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags)
{
ImGuiContext& g = *GImGui;
if ((flags & ImGuiColorEditFlags__DisplayMask) == 0)
flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DisplayMask;
if ((flags & ImGuiColorEditFlags__DataTypeMask) == 0)
flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DataTypeMask;
if ((flags & ImGuiColorEditFlags__PickerMask) == 0)
flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__PickerMask;
if ((flags & ImGuiColorEditFlags__InputMask) == 0)
flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__InputMask;
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DisplayMask)); // Check only 1 option is selected
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DataTypeMask)); // Check only 1 option is selected
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__PickerMask)); // Check only 1 option is selected
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__InputMask)); // Check only 1 option is selected
g.ColorEditOptions = flags;
}
// Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags)
{
ImGuiContext& g = *GImGui;
BeginTooltipEx(0, true);
const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text;
if (text_end > text)
{
TextEx(text, text_end);
Separator();
}
ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2);
ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
ColorButton("##preview", cf, (flags & (ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz);
SameLine();
if ((flags & ImGuiColorEditFlags_InputRGB) || !(flags & ImGuiColorEditFlags__InputMask))
{
if (flags & ImGuiColorEditFlags_NoAlpha)
Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]);
else
Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]);
}
else if (flags & ImGuiColorEditFlags_InputHSV)
{
if (flags & ImGuiColorEditFlags_NoAlpha)
Text("H: %.3f, S: %.3f, V: %.3f", col[0], col[1], col[2]);
else
Text("H: %.3f, S: %.3f, V: %.3f, A: %.3f", col[0], col[1], col[2], col[3]);
}
EndTooltip();
}
void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags)
{
bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__DisplayMask);
bool allow_opt_datatype = !(flags & ImGuiColorEditFlags__DataTypeMask);
if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context"))
return;
ImGuiContext& g = *GImGui;
ImGuiColorEditFlags opts = g.ColorEditOptions;
if (allow_opt_inputs)
{
if (RadioButton("RGB", (opts & ImGuiColorEditFlags_DisplayRGB) != 0)) opts = (opts & ~ImGuiColorEditFlags__DisplayMask) | ImGuiColorEditFlags_DisplayRGB;
if (RadioButton("HSV", (opts & ImGuiColorEditFlags_DisplayHSV) != 0)) opts = (opts & ~ImGuiColorEditFlags__DisplayMask) | ImGuiColorEditFlags_DisplayHSV;
if (RadioButton("Hex", (opts & ImGuiColorEditFlags_DisplayHex) != 0)) opts = (opts & ~ImGuiColorEditFlags__DisplayMask) | ImGuiColorEditFlags_DisplayHex;
}
if (allow_opt_datatype)
{
if (allow_opt_inputs) Separator();
if (RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) != 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Uint8;
if (RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) != 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Float;
}
if (allow_opt_inputs || allow_opt_datatype)
Separator();
if (Button("Copy as..", ImVec2(-1,0)))
OpenPopup("Copy");
if (BeginPopup("Copy"))
{
int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
char buf[64];
ImFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
if (Selectable(buf))
SetClipboardText(buf);
ImFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca);
if (Selectable(buf))
SetClipboardText(buf);
if (flags & ImGuiColorEditFlags_NoAlpha)
ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X", cr, cg, cb);
else
ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X%02X", cr, cg, cb, ca);
if (Selectable(buf))
SetClipboardText(buf);
EndPopup();
}
g.ColorEditOptions = opts;
EndPopup();
}
void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags)
{
bool allow_opt_picker = !(flags & ImGuiColorEditFlags__PickerMask);
bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar);
if ((!allow_opt_picker && !allow_opt_alpha_bar) || !BeginPopup("context"))
return;
ImGuiContext& g = *GImGui;
if (allow_opt_picker)
{
ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function
PushItemWidth(picker_size.x);
for (int picker_type = 0; picker_type < 2; picker_type++)
{
// Draw small/thumbnail version of each picker type (over an invisible button for selection)
if (picker_type > 0) Separator();
PushID(picker_type);
ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs|ImGuiColorEditFlags_NoOptions|ImGuiColorEditFlags_NoLabel|ImGuiColorEditFlags_NoSidePreview|(flags & ImGuiColorEditFlags_NoAlpha);
if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar;
if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel;
ImVec2 backup_pos = GetCursorScreenPos();
if (Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup
g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags__PickerMask) | (picker_flags & ImGuiColorEditFlags__PickerMask);
SetCursorScreenPos(backup_pos);
ImVec4 dummy_ref_col;
memcpy(&dummy_ref_col, ref_col, sizeof(float) * ((picker_flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4));
ColorPicker4("##dummypicker", &dummy_ref_col.x, picker_flags);
PopID();
}
PopItemWidth();
}
if (allow_opt_alpha_bar)
{
if (allow_opt_picker) Separator();
CheckboxFlags("Alpha Bar", (unsigned int*)&g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar);
}
EndPopup();
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: TreeNode, CollapsingHeader, etc.
//-------------------------------------------------------------------------
// - TreeNode()
// - TreeNodeV()
// - TreeNodeEx()
// - TreeNodeExV()
// - TreeNodeBehavior() [Internal]
// - TreePush()
// - TreePop()
// - GetTreeNodeToLabelSpacing()
// - SetNextItemOpen()
// - CollapsingHeader()
//-------------------------------------------------------------------------
bool ImGui::TreeNode(const char* str_id, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(str_id, 0, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(ptr_id, 0, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNode(const char* label)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
return TreeNodeBehavior(window->GetID(label), 0, label, NULL);
}
bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args)
{
return TreeNodeExV(str_id, 0, fmt, args);
}
bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args)
{
return TreeNodeExV(ptr_id, 0, fmt, args);
}
bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
return TreeNodeBehavior(window->GetID(label), flags, label, NULL);
}
bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(str_id, flags, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(ptr_id, flags, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end);
}
bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end);
}
bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags)
{
if (flags & ImGuiTreeNodeFlags_Leaf)
return true;
// We only write to the tree storage if the user clicks (or explicitly use the SetNextItemOpen function)
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiStorage* storage = window->DC.StateStorage;
bool is_open;
if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasOpen)
{
if (g.NextItemData.OpenCond & ImGuiCond_Always)
{
is_open = g.NextItemData.OpenVal;
storage->SetInt(id, is_open);
}
else
{
// We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently.
const int stored_value = storage->GetInt(id, -1);
if (stored_value == -1)
{
is_open = g.NextItemData.OpenVal;
storage->SetInt(id, is_open);
}
else
{
is_open = stored_value != 0;
}
}
}
else
{
is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0;
}
// When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior).
// NB- If we are above max depth we still allow manually opened nodes to be logged.
if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && (window->DC.TreeDepth - g.LogDepthRef) < g.LogDepthToExpand)
is_open = true;
return is_open;
}
bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0;
const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f);
if (!label_end)
label_end = FindRenderedTextEnd(label);
const ImVec2 label_size = CalcTextSize(label, label_end, false);
// We vertically grow up to current line height up the typical widget height.
const float text_base_offset_y = ImMax(padding.y, window->DC.CurrLineTextBaseOffset); // Latch before ItemSize changes it
const float frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2);
ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(window->WorkRect.Max.x, window->DC.CursorPos.y + frame_height));
if (display_frame)
{
// Framed header expand a little outside the default padding
frame_bb.Min.x -= (float)(int)(window->WindowPadding.x * 0.5f - 1.0f);
frame_bb.Max.x += (float)(int)(window->WindowPadding.x * 0.5f);
}
const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing
const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser
ItemSize(ImVec2(text_width, frame_height), text_base_offset_y);
// For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
// (Ideally we'd want to add a flag for the user to specify if we want the hit test to be done up to the right side of the content or not)
const ImRect interact_bb = display_frame ? frame_bb : ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + text_width + style.ItemSpacing.x*2, frame_bb.Max.y);
bool is_open = TreeNodeBehaviorIsOpen(id, flags);
bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0;
// Store a flag for the current depth to tell if we will allow closing this node when navigating one of its child.
// For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop().
// This is currently only support 32 level deep and we are fine with (1 << Depth) overflowing into a zero.
if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
window->DC.TreeStoreMayJumpToParentOnPop |= (1 << window->DC.TreeDepth);
bool item_add = ItemAdd(interact_bb, id);
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDisplayRect;
window->DC.LastItemDisplayRect = frame_bb;
if (!item_add)
{
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushOverrideID(id);
IMGUI_TEST_ENGINE_ITEM_INFO(window->DC.LastItemId, label, window->DC.ItemFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));
return is_open;
}
// Flags that affects opening behavior:
// - 0 (default) .................... single-click anywhere to open
// - OpenOnDoubleClick .............. double-click anywhere to open
// - OpenOnArrow .................... single-click on arrow to open
// - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open
ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers;
if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)
button_flags |= ImGuiButtonFlags_AllowItemOverlap;
if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0);
if (!is_leaf)
button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0;
const bool was_selected = selected;
bool hovered, held;
bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
bool toggled = false;
if (!is_leaf)
{
if (pressed)
{
toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) || (g.NavActivateId == id);
if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)) && (!g.NavDisableMouseHover);
if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
toggled |= g.IO.MouseDoubleClicked[0];
if (g.DragDropActive && is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again.
toggled = false;
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Left && is_open)
{
toggled = true;
NavMoveRequestCancel();
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?
{
toggled = true;
NavMoveRequestCancel();
}
if (toggled)
{
is_open = !is_open;
window->DC.StateStorage->SetInt(id, is_open);
}
}
if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)
SetItemAllowOverlap();
// In this branch, TreeNodeBehavior() cannot toggle the selection so this will never trigger.
if (selected != was_selected) //-V547
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection;
// Render
const ImU32 text_col = GetColorU32(ImGuiCol_Text);
const ImVec2 text_pos = frame_bb.Min + ImVec2(text_offset_x, text_base_offset_y);
ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin;
if (display_frame)
{
// Framed type
const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding);
RenderNavHighlight(frame_bb, id, nav_highlight_flags);
RenderArrow(window->DrawList, frame_bb.Min + ImVec2(padding.x, text_base_offset_y), text_col, is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f);
if (flags & ImGuiTreeNodeFlags_ClipLabelForTrailingButton)
frame_bb.Max.x -= g.FontSize + style.FramePadding.x;
if (g.LogEnabled)
{
// NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here.
const char log_prefix[] = "\n##";
const char log_suffix[] = "##";
LogRenderedText(&text_pos, log_prefix, log_prefix+3);
RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
LogRenderedText(&text_pos, log_suffix, log_suffix+2);
}
else
{
RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
}
}
else
{
// Unframed typed for tree nodes
if (hovered || selected)
{
const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false);
RenderNavHighlight(frame_bb, id, nav_highlight_flags);
}
if (flags & ImGuiTreeNodeFlags_Bullet)
RenderBullet(window->DrawList, frame_bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y), text_col);
else if (!is_leaf)
RenderArrow(window->DrawList, frame_bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), text_col, is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f);
if (g.LogEnabled)
LogRenderedText(&text_pos, ">");
RenderText(text_pos, label, label_end, false);
}
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushOverrideID(id);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));
return is_open;
}
void ImGui::TreePush(const char* str_id)
{
ImGuiWindow* window = GetCurrentWindow();
Indent();
window->DC.TreeDepth++;
PushID(str_id ? str_id : "#TreePush");
}
void ImGui::TreePush(const void* ptr_id)
{
ImGuiWindow* window = GetCurrentWindow();
Indent();
window->DC.TreeDepth++;
PushID(ptr_id ? ptr_id : (const void*)"#TreePush");
}
void ImGui::TreePushOverrideID(ImGuiID id)
{
ImGuiWindow* window = GetCurrentWindow();
Indent();
window->DC.TreeDepth++;
window->IDStack.push_back(id);
}
void ImGui::TreePop()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
Unindent();
window->DC.TreeDepth--;
if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet())
if (g.NavIdIsAlive && (window->DC.TreeStoreMayJumpToParentOnPop & (1 << window->DC.TreeDepth)))
{
SetNavID(window->IDStack.back(), g.NavLayer);
NavMoveRequestCancel();
}
window->DC.TreeStoreMayJumpToParentOnPop &= (1 << window->DC.TreeDepth) - 1;
IM_ASSERT(window->IDStack.Size > 1); // There should always be 1 element in the IDStack (pushed during window creation). If this triggers you called TreePop/PopID too much.
PopID();
}
// Horizontal distance preceding label when using TreeNode() or Bullet()
float ImGui::GetTreeNodeToLabelSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + (g.Style.FramePadding.x * 2.0f);
}
// Set next TreeNode/CollapsingHeader open state.
void ImGui::SetNextItemOpen(bool is_open, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
if (g.CurrentWindow->SkipItems)
return;
g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasOpen;
g.NextItemData.OpenVal = is_open;
g.NextItemData.OpenCond = cond ? cond : ImGuiCond_Always;
}
// CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag).
// This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode().
bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader, label);
}
bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
if (p_open && !*p_open)
return false;
ImGuiID id = window->GetID(label);
flags |= ImGuiTreeNodeFlags_CollapsingHeader | (p_open ? ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_ClipLabelForTrailingButton : 0);
bool is_open = TreeNodeBehavior(id, flags, label);
if (p_open)
{
// Create a small overlapping close button
// FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc.
// FIXME: CloseButton can overlap into text, need find a way to clip the text somehow.
ImGuiContext& g = *GImGui;
ImGuiItemHoveredDataBackup last_item_backup;
float button_size = g.FontSize;
float button_x = ImMax(window->DC.LastItemRect.Min.x, window->DC.LastItemRect.Max.x - g.Style.FramePadding.x * 2.0f - button_size);
float button_y = window->DC.LastItemRect.Min.y;
if (CloseButton(window->GetID((void*)((intptr_t)id + 1)), ImVec2(button_x, button_y)))
*p_open = false;
last_item_backup.Restore();
}
return is_open;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: Selectable
//-------------------------------------------------------------------------
// - Selectable()
//-------------------------------------------------------------------------
// Tip: pass a non-visible label (e.g. "##dummy") then you can use the space to draw other text or image.
// But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id.
bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns) // FIXME-OPT: Avoid if vertically clipped.
PushColumnsBackground();
ImGuiID id = window->GetID(label);
ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y);
ImVec2 pos = window->DC.CursorPos;
pos.y += window->DC.CurrLineTextBaseOffset;
ImRect bb_inner(pos, pos + size);
ItemSize(size);
// Fill horizontal space.
ImVec2 window_padding = window->WindowPadding;
float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x;
float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - pos.x);
ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y);
ImRect bb(pos, pos + size_draw);
if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth))
bb.Max.x += window_padding.x;
// Selectables are tightly packed together so we extend the box to cover spacing between selectable.
const float spacing_x = style.ItemSpacing.x;
const float spacing_y = style.ItemSpacing.y;
const float spacing_L = (float)(int)(spacing_x * 0.50f);
const float spacing_U = (float)(int)(spacing_y * 0.50f);
bb.Min.x -= spacing_L;
bb.Min.y -= spacing_U;
bb.Max.x += (spacing_x - spacing_L);
bb.Max.y += (spacing_y - spacing_U);
bool item_add;
if (flags & ImGuiSelectableFlags_Disabled)
{
ImGuiItemFlags backup_item_flags = window->DC.ItemFlags;
window->DC.ItemFlags |= ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNavDefaultFocus;
item_add = ItemAdd(bb, id);
window->DC.ItemFlags = backup_item_flags;
}
else
{
item_add = ItemAdd(bb, id);
}
if (!item_add)
{
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns)
PopColumnsBackground();
return false;
}
// We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries
ImGuiButtonFlags button_flags = 0;
if (flags & ImGuiSelectableFlags_NoHoldingActiveID) button_flags |= ImGuiButtonFlags_NoHoldingActiveID;
if (flags & ImGuiSelectableFlags_PressedOnClick) button_flags |= ImGuiButtonFlags_PressedOnClick;
if (flags & ImGuiSelectableFlags_PressedOnRelease) button_flags |= ImGuiButtonFlags_PressedOnRelease;
if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled;
if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;
if (flags & ImGuiSelectableFlags_AllowItemOverlap) button_flags |= ImGuiButtonFlags_AllowItemOverlap;
if (flags & ImGuiSelectableFlags_Disabled)
selected = false;
const bool was_selected = selected;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);
// Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard
if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover)))
{
if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)
{
g.NavDisableHighlight = true;
SetNavID(id, window->DC.NavLayerCurrent);
}
}
if (pressed)
MarkItemEdited(id);
if (flags & ImGuiSelectableFlags_AllowItemOverlap)
SetItemAllowOverlap();
// In this branch, Selectable() cannot toggle the selection so this will never trigger.
if (selected != was_selected) //-V547
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection;
// Render
if (held && (flags & ImGuiSelectableFlags_DrawHoveredWhenHeld))
hovered = true;
if (hovered || selected)
{
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
RenderFrame(bb.Min, bb.Max, col, false, 0.0f);
RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);
}
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns)
{
PopColumnsBackground();
bb.Max.x -= (GetContentRegionMax().x - max_x);
}
if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]);
RenderTextClipped(bb_inner.Min, bb_inner.Max, label, NULL, &label_size, style.SelectableTextAlign, &bb);
if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();
// Automatically close popups
if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup))
CloseCurrentPopup();
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);
return pressed;
}
bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
{
if (Selectable(label, *p_selected, flags, size_arg))
{
*p_selected = !*p_selected;
return true;
}
return false;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: ListBox
//-------------------------------------------------------------------------
// - ListBox()
// - ListBoxHeader()
// - ListBoxFooter()
//-------------------------------------------------------------------------
// FIXME: This is an old API. We should redesign some of it, rename ListBoxHeader->BeginListBox, ListBoxFooter->EndListBox
// and promote using them over existing ListBox() functions, similarly to change with combo boxes.
//-------------------------------------------------------------------------
// FIXME: In principle this function should be called BeginListBox(). We should rename it after re-evaluating if we want to keep the same signature.
// Helper to calculate the size of a listbox and display a label on the right.
// Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an non-visible label e.g. "##empty"
bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
const ImGuiStyle& style = g.Style;
const ImGuiID id = GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
// Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y);
ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y));
ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
window->DC.LastItemRect = bb; // Forward storage for ListBoxFooter.. dodgy.
g.NextItemData.ClearFlags();
if (!IsRectVisible(bb.Min, bb.Max))
{
ItemSize(bb.GetSize(), style.FramePadding.y);
ItemAdd(bb, 0, &frame_bb);
return false;
}
BeginGroup();
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
BeginChildFrame(id, frame_bb.GetSize());
return true;
}
// FIXME: In principle this function should be called EndListBox(). We should rename it after re-evaluating if we want to keep the same signature.
bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items)
{
// Size default to hold ~7.25 items.
// We add +25% worth of item height to allow the user to see at a glance if there are more items up/down, without looking at the scrollbar.
// We don't add this extra bit if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size.
// I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution.
if (height_in_items < 0)
height_in_items = ImMin(items_count, 7);
const ImGuiStyle& style = GetStyle();
float height_in_items_f = (height_in_items < items_count) ? (height_in_items + 0.25f) : (height_in_items + 0.00f);
// We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild().
ImVec2 size;
size.x = 0.0f;
size.y = GetTextLineHeightWithSpacing() * height_in_items_f + style.FramePadding.y * 2.0f;
return ListBoxHeader(label, size);
}
// FIXME: In principle this function should be called EndListBox(). We should rename it after re-evaluating if we want to keep the same signature.
void ImGui::ListBoxFooter()
{
ImGuiWindow* parent_window = GetCurrentWindow()->ParentWindow;
const ImRect bb = parent_window->DC.LastItemRect;
const ImGuiStyle& style = GetStyle();
EndChildFrame();
// Redeclare item size so that it includes the label (we have stored the full size in LastItemRect)
// We call SameLine() to restore DC.CurrentLine* data
SameLine();
parent_window->DC.CursorPos = bb.Min;
ItemSize(bb, style.FramePadding.y);
EndGroup();
}
bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items)
{
const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items);
return value_changed;
}
bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items)
{
if (!ListBoxHeader(label, items_count, height_in_items))
return false;
// Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper.
ImGuiContext& g = *GImGui;
bool value_changed = false;
ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to.
while (clipper.Step())
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
{
const bool item_selected = (i == *current_item);
const char* item_text;
if (!items_getter(data, i, &item_text))
item_text = "*Unknown item*";
PushID(i);
if (Selectable(item_text, item_selected))
{
*current_item = i;
value_changed = true;
}
if (item_selected)
SetItemDefaultFocus();
PopID();
}
ListBoxFooter();
if (value_changed)
MarkItemEdited(g.CurrentWindow->DC.LastItemId);
return value_changed;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: PlotLines, PlotHistogram
//-------------------------------------------------------------------------
// - PlotEx() [Internal]
// - PlotLines()
// - PlotHistogram()
//-------------------------------------------------------------------------
void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 frame_size)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
if (frame_size.x == 0.0f)
frame_size.x = CalcItemWidth();
if (frame_size.y == 0.0f)
frame_size.y = label_size.y + (style.FramePadding.y * 2);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, 0, &frame_bb))
return;
const bool hovered = ItemHoverable(frame_bb, id);
// Determine scale from values if not specified
if (scale_min == FLT_MAX || scale_max == FLT_MAX)
{
float v_min = FLT_MAX;
float v_max = -FLT_MAX;
for (int i = 0; i < values_count; i++)
{
const float v = values_getter(data, i);
if (v != v) // Ignore NaN values
continue;
v_min = ImMin(v_min, v);
v_max = ImMax(v_max, v);
}
if (scale_min == FLT_MAX)
scale_min = v_min;
if (scale_max == FLT_MAX)
scale_max = v_max;
}
RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
const int values_count_min = (plot_type == ImGuiPlotType_Lines) ? 2 : 1;
if (values_count >= values_count_min)
{
int res_w = ImMin((int)frame_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
// Tooltip on hover
int v_hovered = -1;
if (hovered && inner_bb.Contains(g.IO.MousePos))
{
const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f);
const int v_idx = (int)(t * item_count);
IM_ASSERT(v_idx >= 0 && v_idx < values_count);
const float v0 = values_getter(data, (v_idx + values_offset) % values_count);
const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count);
if (plot_type == ImGuiPlotType_Lines)
SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1);
else if (plot_type == ImGuiPlotType_Histogram)
SetTooltip("%d: %8.4g", v_idx, v0);
v_hovered = v_idx;
}
const float t_step = 1.0f / (float)res_w;
const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min));
float v0 = values_getter(data, (0 + values_offset) % values_count);
float t0 = 0.0f;
ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle
float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands
const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram);
const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered);
for (int n = 0; n < res_w; n++)
{
const float t1 = t0 + t_step;
const int v1_idx = (int)(t0 * item_count + 0.5f);
IM_ASSERT(v1_idx >= 0 && v1_idx < values_count);
const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count);
const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) );
// NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU.
ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0);
ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t));
if (plot_type == ImGuiPlotType_Lines)
{
window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
}
else if (plot_type == ImGuiPlotType_Histogram)
{
if (pos1.x >= pos0.x + 2.0f)
pos1.x -= 1.0f;
window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
}
t0 = t1;
tp0 = tp1;
}
}
// Text overlay
if (overlay_text)
RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f,0.0f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
}
struct ImGuiPlotArrayGetterData
{
const float* Values;
int Stride;
ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; }
};
static float Plot_ArrayGetter(void* data, int idx)
{
ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data;
const float v = *(const float*)(const void*)((const unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride);
return v;
}
void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
{
ImGuiPlotArrayGetterData data(values, stride);
PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
{
PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
{
ImGuiPlotArrayGetterData data(values, stride);
PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
{
PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: Value helpers
// Those is not very useful, legacy API.
//-------------------------------------------------------------------------
// - Value()
//-------------------------------------------------------------------------
void ImGui::Value(const char* prefix, bool b)
{
Text("%s: %s", prefix, (b ? "true" : "false"));
}
void ImGui::Value(const char* prefix, int v)
{
Text("%s: %d", prefix, v);
}
void ImGui::Value(const char* prefix, unsigned int v)
{
Text("%s: %d", prefix, v);
}
void ImGui::Value(const char* prefix, float v, const char* float_format)
{
if (float_format)
{
char fmt[64];
ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format);
Text(fmt, prefix, v);
}
else
{
Text("%s: %.3f", prefix, v);
}
}
//-------------------------------------------------------------------------
// [SECTION] MenuItem, BeginMenu, EndMenu, etc.
//-------------------------------------------------------------------------
// - ImGuiMenuColumns [Internal]
// - BeginMainMenuBar()
// - EndMainMenuBar()
// - BeginMenuBar()
// - EndMenuBar()
// - BeginMenu()
// - EndMenu()
// - MenuItem()
//-------------------------------------------------------------------------
// Helpers for internal use
ImGuiMenuColumns::ImGuiMenuColumns()
{
Spacing = Width = NextWidth = 0.0f;
memset(Pos, 0, sizeof(Pos));
memset(NextWidths, 0, sizeof(NextWidths));
}
void ImGuiMenuColumns::Update(int count, float spacing, bool clear)
{
IM_ASSERT(count == IM_ARRAYSIZE(Pos));
IM_UNUSED(count);
Width = NextWidth = 0.0f;
Spacing = spacing;
if (clear)
memset(NextWidths, 0, sizeof(NextWidths));
for (int i = 0; i < IM_ARRAYSIZE(Pos); i++)
{
if (i > 0 && NextWidths[i] > 0.0f)
Width += Spacing;
Pos[i] = (float)(int)Width;
Width += NextWidths[i];
NextWidths[i] = 0.0f;
}
}
float ImGuiMenuColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double
{
NextWidth = 0.0f;
NextWidths[0] = ImMax(NextWidths[0], w0);
NextWidths[1] = ImMax(NextWidths[1], w1);
NextWidths[2] = ImMax(NextWidths[2], w2);
for (int i = 0; i < IM_ARRAYSIZE(Pos); i++)
NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f);
return ImMax(Width, NextWidth);
}
float ImGuiMenuColumns::CalcExtraSpace(float avail_w)
{
return ImMax(0.0f, avail_w - Width);
}
// For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set.
bool ImGui::BeginMainMenuBar()
{
ImGuiContext& g = *GImGui;
g.NextWindowData.MenuBarOffsetMinVal = ImVec2(g.Style.DisplaySafeAreaPadding.x, ImMax(g.Style.DisplaySafeAreaPadding.y - g.Style.FramePadding.y, 0.0f));
SetNextWindowPos(ImVec2(0.0f, 0.0f));
SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.NextWindowData.MenuBarOffsetMinVal.y + g.FontBaseSize + g.Style.FramePadding.y));
PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0));
ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar;
bool is_open = Begin("##MainMenuBar", NULL, window_flags) && BeginMenuBar();
PopStyleVar(2);
g.NextWindowData.MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f);
if (!is_open)
{
End();
return false;
}
return true; //-V1020
}
void ImGui::EndMainMenuBar()
{
EndMenuBar();
// When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window
// FIXME: With this strategy we won't be able to restore a NULL focus.
ImGuiContext& g = *GImGui;
if (g.CurrentWindow == g.NavWindow && g.NavLayer == 0 && !g.NavAnyRequest)
FocusTopMostWindowUnderOne(g.NavWindow, NULL);
End();
}
// FIXME: Provided a rectangle perhaps e.g. a BeginMenuBarEx() could be used anywhere..
// Currently the main responsibility of this function being to setup clip-rect + horizontal layout + menu navigation layer.
// Ideally we also want this to be responsible for claiming space out of the main window scrolling rectangle, in which case ImGuiWindowFlags_MenuBar will become unnecessary.
// Then later the same system could be used for multiple menu-bars, scrollbars, side-bars.
bool ImGui::BeginMenuBar()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
if (!(window->Flags & ImGuiWindowFlags_MenuBar))
return false;
IM_ASSERT(!window->DC.MenuBarAppending);
BeginGroup(); // Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore
PushID("##menubar");
// We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect.
// We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy.
ImRect bar_rect = window->MenuBarRect();
ImRect clip_rect(ImFloor(bar_rect.Min.x + 0.5f), ImFloor(bar_rect.Min.y + window->WindowBorderSize + 0.5f), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - window->WindowRounding) + 0.5f), ImFloor(bar_rect.Max.y + 0.5f));
clip_rect.ClipWith(window->OuterRectClipped);
PushClipRect(clip_rect.Min, clip_rect.Max, false);
window->DC.CursorPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y);
window->DC.LayoutType = ImGuiLayoutType_Horizontal;
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
window->DC.MenuBarAppending = true;
AlignTextToFramePadding();
return true;
}
void ImGui::EndMenuBar()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
// Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings.
if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
{
ImGuiWindow* nav_earliest_child = g.NavWindow;
while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu))
nav_earliest_child = nav_earliest_child->ParentWindow;
if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && g.NavMoveRequestForward == ImGuiNavForward_None)
{
// To do so we claim focus back, restore NavId and then process the movement request for yet another frame.
// This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth the hassle/cost)
const ImGuiNavLayer layer = ImGuiNavLayer_Menu;
IM_ASSERT(window->DC.NavLayerActiveMaskNext & (1 << layer)); // Sanity check
FocusWindow(window);
SetNavIDWithRectRel(window->NavLastIds[layer], layer, window->NavRectRel[layer]);
g.NavLayer = layer;
g.NavDisableHighlight = true; // Hide highlight for the current frame so we don't see the intermediary selection.
g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
NavMoveRequestCancel();
}
}
IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
IM_ASSERT(window->DC.MenuBarAppending);
PopClipRect();
PopID();
window->DC.MenuBarOffset.x = window->DC.CursorPos.x - window->MenuBarRect().Min.x; // Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos.
window->DC.GroupStack.back().EmitItem = false;
EndGroup(); // Restore position on layer 0
window->DC.LayoutType = ImGuiLayoutType_Vertical;
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->DC.MenuBarAppending = false;
}
bool ImGui::BeginMenu(const char* label, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
ImVec2 label_size = CalcTextSize(label, NULL, true);
bool pressed;
bool menu_is_open = IsPopupOpen(id);
bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].OpenParentId == window->IDStack.back());
ImGuiWindow* backed_nav_window = g.NavWindow;
if (menuset_is_open)
g.NavWindow = window; // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent)
// The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu,
// However the final position is going to be different! It is choosen by FindBestWindowPosForPopup().
// e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering.
ImVec2 popup_pos, pos = window->DC.CursorPos;
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
{
// Menu inside an horizontal menu bar
// Selectable extend their highlight by half ItemSpacing in each direction.
// For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin()
popup_pos = ImVec2(pos.x - 1.0f - (float)(int)(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight());
window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x * 2.0f, style.ItemSpacing.y));
float w = label_size.x;
pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_PressedOnClick | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
PopStyleVar();
window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
}
else
{
// Menu inside a menu
popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y);
float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame
float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_PressedOnClick | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
ImU32 text_col = GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled);
RenderArrow(window->DrawList, pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.30f, 0.0f), text_col, ImGuiDir_Right);
}
const bool hovered = enabled && ItemHoverable(window->DC.LastItemRect, id);
if (menuset_is_open)
g.NavWindow = backed_nav_window;
bool want_open = false;
bool want_close = false;
if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
{
// Close menu when not hovering it anymore unless we are moving roughly in the direction of the menu
// Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive.
bool moving_toward_other_child_menu = false;
ImGuiWindow* child_menu_window = (g.BeginPopupStack.Size < g.OpenPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].SourceWindow == window) ? g.OpenPopupStack[g.BeginPopupStack.Size].Window : NULL;
if (g.HoveredWindow == window && child_menu_window != NULL && !(window->Flags & ImGuiWindowFlags_MenuBar))
{
// FIXME-DPI: Values should be derived from a master "scale" factor.
ImRect next_window_rect = child_menu_window->Rect();
ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta;
ImVec2 tb = (window->Pos.x < child_menu_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR();
ImVec2 tc = (window->Pos.x < child_menu_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR();
float extra = ImClamp(ImFabs(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack.
ta.x += (window->Pos.x < child_menu_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues
tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale?
tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f);
moving_toward_other_child_menu = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos);
//GetForegroundDrawList()->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); // [DEBUG]
}
if (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_toward_other_child_menu)
want_close = true;
if (!menu_is_open && hovered && pressed) // Click to open
want_open = true;
else if (!menu_is_open && hovered && !moving_toward_other_child_menu) // Hover to open
want_open = true;
if (g.NavActivateId == id)
{
want_close = menu_is_open;
want_open = !menu_is_open;
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right) // Nav-Right to open
{
want_open = true;
NavMoveRequestCancel();
}
}
else
{
// Menu bar
if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it
{
want_close = true;
want_open = menu_is_open = false;
}
else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others
{
want_open = true;
}
else if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Down) // Nav-Down to open
{
want_open = true;
NavMoveRequestCancel();
}
}
if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }'
want_close = true;
if (want_close && IsPopupOpen(id))
ClosePopupToLevel(g.BeginPopupStack.Size, true);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0));
if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size)
{
// Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.
OpenPopup(label);
return false;
}
menu_is_open |= want_open;
if (want_open)
OpenPopup(label);
if (menu_is_open)
{
// Sub-menus are ChildWindow so that mouse can be hovering across them (otherwise top-most popup menu would steal focus and not allow hovering on parent menu)
SetNextWindowPos(popup_pos, ImGuiCond_Always);
ImGuiWindowFlags flags = ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus;
if (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
flags |= ImGuiWindowFlags_ChildWindow;
menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
}
return menu_is_open;
}
void ImGui::EndMenu()
{
// Nav: When a left move request _within our child menu_ failed, close ourselves (the _parent_ menu).
// A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs.
// However, it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavWindow && g.NavWindow->ParentWindow == window && g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical)
{
ClosePopupToLevel(g.BeginPopupStack.Size, true);
NavMoveRequestCancel();
}
EndPopup();
}
bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImVec2 pos = window->DC.CursorPos;
ImVec2 label_size = CalcTextSize(label, NULL, true);
// We've been using the equivalent of ImGuiSelectableFlags_SetNavIdOnHover on all Selectable() since early Nav system days (commit 43ee5d73),
// but I am unsure whether this should be kept at all. For now moved it to be an opt-in feature used by menus only.
ImGuiSelectableFlags flags = ImGuiSelectableFlags_PressedOnRelease | ImGuiSelectableFlags_SetNavIdOnHover | (enabled ? 0 : ImGuiSelectableFlags_Disabled);
bool pressed;
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
{
// Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful
// Note that in this situation we render neither the shortcut neither the selected tick mark
float w = label_size.x;
window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x * 2.0f, style.ItemSpacing.y));
pressed = Selectable(label, false, flags, ImVec2(w, 0.0f));
PopStyleVar();
window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
}
else
{
ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f);
float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame
float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
pressed = Selectable(label, false, flags | ImGuiSelectableFlags_DrawFillAvailWidth, ImVec2(w, 0.0f));
if (shortcut_size.x > 0.0f)
{
PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false);
PopStyleColor();
}
if (selected)
RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled), g.FontSize * 0.866f);
}
IMGUI_TEST_ENGINE_ITEM_INFO(window->DC.LastItemId, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Checkable | (selected ? ImGuiItemStatusFlags_Checked : 0));
return pressed;
}
bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled)
{
if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled))
{
if (p_selected)
*p_selected = !*p_selected;
return true;
}
return false;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: BeginTabBar, EndTabBar, etc.
//-------------------------------------------------------------------------
// [BETA API] API may evolve! This code has been extracted out of the Docking branch,
// and some of the construct which are not used in Master may be left here to facilitate merging.
//-------------------------------------------------------------------------
// - BeginTabBar()
// - BeginTabBarEx() [Internal]
// - EndTabBar()
// - TabBarLayout() [Internal]
// - TabBarCalcTabID() [Internal]
// - TabBarCalcMaxTabWidth() [Internal]
// - TabBarFindTabById() [Internal]
// - TabBarRemoveTab() [Internal]
// - TabBarCloseTab() [Internal]
// - TabBarScrollClamp()v
// - TabBarScrollToTab() [Internal]
// - TabBarQueueChangeTabOrder() [Internal]
// - TabBarScrollingButtons() [Internal]
// - TabBarTabListPopupButton() [Internal]
//-------------------------------------------------------------------------
namespace ImGui
{
static void TabBarLayout(ImGuiTabBar* tab_bar);
static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label);
static float TabBarCalcMaxTabWidth();
static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling);
static void TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab);
static ImGuiTabItem* TabBarScrollingButtons(ImGuiTabBar* tab_bar);
static ImGuiTabItem* TabBarTabListPopupButton(ImGuiTabBar* tab_bar);
}
ImGuiTabBar::ImGuiTabBar()
{
ID = 0;
SelectedTabId = NextSelectedTabId = VisibleTabId = 0;
CurrFrameVisible = PrevFrameVisible = -1;
ContentsHeight = 0.0f;
OffsetMax = OffsetNextTab = 0.0f;
ScrollingAnim = ScrollingTarget = ScrollingTargetDistToVisibility = ScrollingSpeed = 0.0f;
Flags = ImGuiTabBarFlags_None;
ReorderRequestTabId = 0;
ReorderRequestDir = 0;
WantLayout = VisibleTabWasSubmitted = false;
LastTabItemIdx = -1;
}
static int IMGUI_CDECL TabItemComparerByVisibleOffset(const void* lhs, const void* rhs)
{
const ImGuiTabItem* a = (const ImGuiTabItem*)lhs;
const ImGuiTabItem* b = (const ImGuiTabItem*)rhs;
return (int)(a->Offset - b->Offset);
}
static ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiPtrOrIndex& ref)
{
ImGuiContext& g = *GImGui;
return ref.Ptr ? (ImGuiTabBar*)ref.Ptr : g.TabBars.GetByIndex(ref.Index);
}
static ImGuiPtrOrIndex GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar)
{
ImGuiContext& g = *GImGui;
if (g.TabBars.Contains(tab_bar))
return ImGuiPtrOrIndex(g.TabBars.GetIndex(tab_bar));
return ImGuiPtrOrIndex(tab_bar);
}
bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return false;
ImGuiID id = window->GetID(str_id);
ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id);
ImRect tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->WorkRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2);
tab_bar->ID = id;
return BeginTabBarEx(tab_bar, tab_bar_bb, flags | ImGuiTabBarFlags_IsFocused);
}
bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImGuiTabBarFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return false;
if ((flags & ImGuiTabBarFlags_DockNode) == 0)
PushOverrideID(tab_bar->ID);
// Add to stack
g.CurrentTabBarStack.push_back(GetTabBarRefFromTabBar(tab_bar));
g.CurrentTabBar = tab_bar;
if (tab_bar->CurrFrameVisible == g.FrameCount)
{
//IMGUI_DEBUG_LOG("BeginTabBarEx already called this frame\n", g.FrameCount);
IM_ASSERT(0);
return true;
}
// When toggling back from ordered to manually-reorderable, shuffle tabs to enforce the last visible order.
// Otherwise, the most recently inserted tabs would move at the end of visible list which can be a little too confusing or magic for the user.
if ((flags & ImGuiTabBarFlags_Reorderable) && !(tab_bar->Flags & ImGuiTabBarFlags_Reorderable) && tab_bar->Tabs.Size > 1 && tab_bar->PrevFrameVisible != -1)
ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByVisibleOffset);
// Flags
if ((flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0)
flags |= ImGuiTabBarFlags_FittingPolicyDefault_;
tab_bar->Flags = flags;
tab_bar->BarRect = tab_bar_bb;
tab_bar->WantLayout = true; // Layout will be done on the first call to ItemTab()
tab_bar->PrevFrameVisible = tab_bar->CurrFrameVisible;
tab_bar->CurrFrameVisible = g.FrameCount;
tab_bar->FramePadding = g.Style.FramePadding;
// Layout
ItemSize(ImVec2(0.0f /*tab_bar->OffsetMax*/, tab_bar->BarRect.GetHeight())); // Don't feed width back
window->DC.CursorPos.x = tab_bar->BarRect.Min.x;
// Draw separator
const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive);
const float y = tab_bar->BarRect.Max.y - 1.0f;
{
const float separator_min_x = tab_bar->BarRect.Min.x - ImFloor(window->WindowPadding.x * 0.5f);
const float separator_max_x = tab_bar->BarRect.Max.x + ImFloor(window->WindowPadding.x * 0.5f);
window->DrawList->AddLine(ImVec2(separator_min_x, y), ImVec2(separator_max_x, y), col, 1.0f);
}
return true;
}
void ImGui::EndTabBar()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
ImGuiTabBar* tab_bar = g.CurrentTabBar;
if (tab_bar == NULL)
{
IM_ASSERT(tab_bar != NULL && "Mismatched BeginTabBar()/EndTabBar()!");
return; // FIXME-ERRORHANDLING
}
if (tab_bar->WantLayout)
TabBarLayout(tab_bar);
// Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed().
const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);
if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabId == 0 || tab_bar_appearing)
tab_bar->ContentsHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, 0.0f);
else
window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->ContentsHeight;
if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0)
PopID();
g.CurrentTabBarStack.pop_back();
g.CurrentTabBar = g.CurrentTabBarStack.empty() ? NULL : GetTabBarFromTabBarRef(g.CurrentTabBarStack.back());
}
// This is called only once a frame before by the first call to ItemTab()
// The reason we're not calling it in BeginTabBar() is to leave a chance to the user to call the SetTabItemClosed() functions.
static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar)
{
ImGuiContext& g = *GImGui;
tab_bar->WantLayout = false;
// Garbage collect
int tab_dst_n = 0;
for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n];
if (tab->LastFrameVisible < tab_bar->PrevFrameVisible)
{
if (tab->ID == tab_bar->SelectedTabId)
tab_bar->SelectedTabId = 0;
continue;
}
if (tab_dst_n != tab_src_n)
tab_bar->Tabs[tab_dst_n] = tab_bar->Tabs[tab_src_n];
tab_dst_n++;
}
if (tab_bar->Tabs.Size != tab_dst_n)
tab_bar->Tabs.resize(tab_dst_n);
// Setup next selected tab
ImGuiID scroll_track_selected_tab_id = 0;
if (tab_bar->NextSelectedTabId)
{
tab_bar->SelectedTabId = tab_bar->NextSelectedTabId;
tab_bar->NextSelectedTabId = 0;
scroll_track_selected_tab_id = tab_bar->SelectedTabId;
}
// Process order change request (we could probably process it when requested but it's just saner to do it in a single spot).
if (tab_bar->ReorderRequestTabId != 0)
{
if (ImGuiTabItem* tab1 = TabBarFindTabByID(tab_bar, tab_bar->ReorderRequestTabId))
{
//IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools
int tab2_order = tab_bar->GetTabOrder(tab1) + tab_bar->ReorderRequestDir;
if (tab2_order >= 0 && tab2_order < tab_bar->Tabs.Size)
{
ImGuiTabItem* tab2 = &tab_bar->Tabs[tab2_order];
ImGuiTabItem item_tmp = *tab1;
*tab1 = *tab2;
*tab2 = item_tmp;
if (tab2->ID == tab_bar->SelectedTabId)
scroll_track_selected_tab_id = tab2->ID;
tab1 = tab2 = NULL;
}
if (tab_bar->Flags & ImGuiTabBarFlags_SaveSettings)
MarkIniSettingsDirty();
}
tab_bar->ReorderRequestTabId = 0;
}
// Tab List Popup (will alter tab_bar->BarRect and therefore the available width!)
const bool tab_list_popup_button = (tab_bar->Flags & ImGuiTabBarFlags_TabListPopupButton) != 0;
if (tab_list_popup_button)
if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Max.x!
scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID;
// Compute ideal widths
g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size);
float width_total_contents = 0.0f;
ImGuiTabItem* most_recently_selected_tab = NULL;
bool found_selected_tab_id = false;
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
IM_ASSERT(tab->LastFrameVisible >= tab_bar->PrevFrameVisible);
if (most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected)
most_recently_selected_tab = tab;
if (tab->ID == tab_bar->SelectedTabId)
found_selected_tab_id = true;
// Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar.
// Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet,
// and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window.
const char* tab_name = tab_bar->GetTabName(tab);
const bool has_close_button = (tab->Flags & ImGuiTabItemFlags_NoCloseButton) ? false : true;
tab->WidthContents = TabItemCalcSize(tab_name, has_close_button).x;
width_total_contents += (tab_n > 0 ? g.Style.ItemInnerSpacing.x : 0.0f) + tab->WidthContents;
// Store data so we can build an array sorted by width if we need to shrink tabs down
g.ShrinkWidthBuffer[tab_n].Index = tab_n;
g.ShrinkWidthBuffer[tab_n].Width = tab->WidthContents;
}
// Compute width
const float initial_offset_x = 0.0f; // g.Style.ItemInnerSpacing.x;
const float width_avail = ImMax(tab_bar->BarRect.GetWidth() - initial_offset_x, 0.0f);
float width_excess = (width_avail < width_total_contents) ? (width_total_contents - width_avail) : 0.0f;
if (width_excess > 0.0f && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown))
{
// If we don't have enough room, resize down the largest tabs first
ShrinkWidths(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Size, width_excess);
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index].Width = (float)(int)g.ShrinkWidthBuffer[tab_n].Width;
}
else
{
const float tab_max_width = TabBarCalcMaxTabWidth();
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
tab->Width = ImMin(tab->WidthContents, tab_max_width);
}
}
// Layout all active tabs
float offset_x = initial_offset_x;
tab_bar->OffsetNextTab = offset_x; // This is used by non-reorderable tab bar where the submission order is always honored.
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
tab->Offset = offset_x;
if (scroll_track_selected_tab_id == 0 && g.NavJustMovedToId == tab->ID)
scroll_track_selected_tab_id = tab->ID;
offset_x += tab->Width + g.Style.ItemInnerSpacing.x;
}
tab_bar->OffsetMax = ImMax(offset_x - g.Style.ItemInnerSpacing.x, 0.0f);
// Horizontal scrolling buttons
const bool scrolling_buttons = (tab_bar->OffsetMax > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll);
if (scrolling_buttons)
if (ImGuiTabItem* tab_to_select = TabBarScrollingButtons(tab_bar)) // NB: Will alter BarRect.Max.x!
scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID;
// If we have lost the selected tab, select the next most recently active one
if (found_selected_tab_id == false)
tab_bar->SelectedTabId = 0;
if (tab_bar->SelectedTabId == 0 && tab_bar->NextSelectedTabId == 0 && most_recently_selected_tab != NULL)
scroll_track_selected_tab_id = tab_bar->SelectedTabId = most_recently_selected_tab->ID;
// Lock in visible tab
tab_bar->VisibleTabId = tab_bar->SelectedTabId;
tab_bar->VisibleTabWasSubmitted = false;
// Update scrolling
if (scroll_track_selected_tab_id)
if (ImGuiTabItem* scroll_track_selected_tab = TabBarFindTabByID(tab_bar, scroll_track_selected_tab_id))
TabBarScrollToTab(tab_bar, scroll_track_selected_tab);
tab_bar->ScrollingAnim = TabBarScrollClamp(tab_bar, tab_bar->ScrollingAnim);
tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget);
if (tab_bar->ScrollingAnim != tab_bar->ScrollingTarget)
{
// Scrolling speed adjust itself so we can always reach our target in 1/3 seconds.
// Teleport if we are aiming far off the visible line
tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, 70.0f * g.FontSize);
tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, ImFabs(tab_bar->ScrollingTarget - tab_bar->ScrollingAnim) / 0.3f);
const bool teleport = (tab_bar->PrevFrameVisible + 1 < g.FrameCount) || (tab_bar->ScrollingTargetDistToVisibility > 10.0f * g.FontSize);
tab_bar->ScrollingAnim = teleport ? tab_bar->ScrollingTarget : ImLinearSweep(tab_bar->ScrollingAnim, tab_bar->ScrollingTarget, g.IO.DeltaTime * tab_bar->ScrollingSpeed);
}
else
{
tab_bar->ScrollingSpeed = 0.0f;
}
// Clear name buffers
if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0)
tab_bar->TabsNames.Buf.resize(0);
}
// Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack.
static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label)
{
if (tab_bar->Flags & ImGuiTabBarFlags_DockNode)
{
ImGuiID id = ImHashStr(label);
KeepAliveID(id);
return id;
}
else
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(label);
}
}
static float ImGui::TabBarCalcMaxTabWidth()
{
ImGuiContext& g = *GImGui;
return g.FontSize * 20.0f;
}
ImGuiTabItem* ImGui::TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id)
{
if (tab_id != 0)
for (int n = 0; n < tab_bar->Tabs.Size; n++)
if (tab_bar->Tabs[n].ID == tab_id)
return &tab_bar->Tabs[n];
return NULL;
}
// The *TabId fields be already set by the docking system _before_ the actual TabItem was created, so we clear them regardless.
void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id)
{
if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id))
tab_bar->Tabs.erase(tab);
if (tab_bar->VisibleTabId == tab_id) { tab_bar->VisibleTabId = 0; }
if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; }
if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; }
}
// Called on manual closure attempt
void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
{
if ((tab_bar->VisibleTabId == tab->ID) && !(tab->Flags & ImGuiTabItemFlags_UnsavedDocument))
{
// This will remove a frame of lag for selecting another tab on closure.
// However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure
tab->LastFrameVisible = -1;
tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = 0;
}
else if ((tab_bar->VisibleTabId != tab->ID) && (tab->Flags & ImGuiTabItemFlags_UnsavedDocument))
{
// Actually select before expecting closure
tab_bar->NextSelectedTabId = tab->ID;
}
}
static float ImGui::TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling)
{
scrolling = ImMin(scrolling, tab_bar->OffsetMax - tab_bar->BarRect.GetWidth());
return ImMax(scrolling, 0.0f);
}
static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
{
ImGuiContext& g = *GImGui;
float margin = g.FontSize * 1.0f; // When to scroll to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar)
int order = tab_bar->GetTabOrder(tab);
float tab_x1 = tab->Offset + (order > 0 ? -margin : 0.0f);
float tab_x2 = tab->Offset + tab->Width + (order + 1 < tab_bar->Tabs.Size ? margin : 1.0f);
tab_bar->ScrollingTargetDistToVisibility = 0.0f;
if (tab_bar->ScrollingTarget > tab_x1)
{
tab_bar->ScrollingTargetDistToVisibility = ImMax(tab_bar->ScrollingAnim - tab_x2, 0.0f);
tab_bar->ScrollingTarget = tab_x1;
}
else if (tab_bar->ScrollingTarget < tab_x2 - tab_bar->BarRect.GetWidth())
{
tab_bar->ScrollingTargetDistToVisibility = ImMax((tab_x1 - tab_bar->BarRect.GetWidth()) - tab_bar->ScrollingAnim, 0.0f);
tab_bar->ScrollingTarget = tab_x2 - tab_bar->BarRect.GetWidth();
}
}
void ImGui::TabBarQueueChangeTabOrder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int dir)
{
IM_ASSERT(dir == -1 || dir == +1);
IM_ASSERT(tab_bar->ReorderRequestTabId == 0);
tab_bar->ReorderRequestTabId = tab->ID;
tab_bar->ReorderRequestDir = (ImS8)dir;
}
static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImVec2 arrow_button_size(g.FontSize - 2.0f, g.FontSize + g.Style.FramePadding.y * 2.0f);
const float scrolling_buttons_width = arrow_button_size.x * 2.0f;
const ImVec2 backup_cursor_pos = window->DC.CursorPos;
//window->DrawList->AddRect(ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x, tab_bar->BarRect.Max.y), IM_COL32(255,0,0,255));
const ImRect avail_bar_rect = tab_bar->BarRect;
bool want_clip_rect = !avail_bar_rect.Contains(ImRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(scrolling_buttons_width, 0.0f)));
if (want_clip_rect)
PushClipRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max + ImVec2(g.Style.ItemInnerSpacing.x, 0.0f), true);
ImGuiTabItem* tab_to_select = NULL;
int select_dir = 0;
ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text];
arrow_col.w *= 0.5f;
PushStyleColor(ImGuiCol_Text, arrow_col);
PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
const float backup_repeat_delay = g.IO.KeyRepeatDelay;
const float backup_repeat_rate = g.IO.KeyRepeatRate;
g.IO.KeyRepeatDelay = 0.250f;
g.IO.KeyRepeatRate = 0.200f;
window->DC.CursorPos = ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y);
if (ArrowButtonEx("##<", ImGuiDir_Left, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat))
select_dir = -1;
window->DC.CursorPos = ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width + arrow_button_size.x, tab_bar->BarRect.Min.y);
if (ArrowButtonEx("##>", ImGuiDir_Right, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat))
select_dir = +1;
PopStyleColor(2);
g.IO.KeyRepeatRate = backup_repeat_rate;
g.IO.KeyRepeatDelay = backup_repeat_delay;
if (want_clip_rect)
PopClipRect();
if (select_dir != 0)
if (ImGuiTabItem* tab_item = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
{
int selected_order = tab_bar->GetTabOrder(tab_item);
int target_order = selected_order + select_dir;
tab_to_select = &tab_bar->Tabs[(target_order >= 0 && target_order < tab_bar->Tabs.Size) ? target_order : selected_order]; // If we are at the end of the list, still scroll to make our tab visible
}
window->DC.CursorPos = backup_cursor_pos;
tab_bar->BarRect.Max.x -= scrolling_buttons_width + 1.0f;
return tab_to_select;
}
static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// We use g.Style.FramePadding.y to match the square ArrowButton size
const float tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y;
const ImVec2 backup_cursor_pos = window->DC.CursorPos;
window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x - g.Style.FramePadding.y, tab_bar->BarRect.Min.y);
tab_bar->BarRect.Min.x += tab_list_popup_button_width;
ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text];
arrow_col.w *= 0.5f;
PushStyleColor(ImGuiCol_Text, arrow_col);
PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview);
PopStyleColor(2);
ImGuiTabItem* tab_to_select = NULL;
if (open)
{
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
const char* tab_name = tab_bar->GetTabName(tab);
if (Selectable(tab_name, tab_bar->SelectedTabId == tab->ID))
tab_to_select = tab;
}
EndCombo();
}
window->DC.CursorPos = backup_cursor_pos;
return tab_to_select;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: BeginTabItem, EndTabItem, etc.
//-------------------------------------------------------------------------
// [BETA API] API may evolve! This code has been extracted out of the Docking branch,
// and some of the construct which are not used in Master may be left here to facilitate merging.
//-------------------------------------------------------------------------
// - BeginTabItem()
// - EndTabItem()
// - TabItemEx() [Internal]
// - SetTabItemClosed()
// - TabItemCalcSize() [Internal]
// - TabItemBackground() [Internal]
// - TabItemLabelAndCloseButton() [Internal]
//-------------------------------------------------------------------------
bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return false;
ImGuiTabBar* tab_bar = g.CurrentTabBar;
if (tab_bar == NULL)
{
IM_ASSERT(tab_bar && "Needs to be called between BeginTabBar() and EndTabBar()!");
return false; // FIXME-ERRORHANDLING
}
bool ret = TabItemEx(tab_bar, label, p_open, flags);
if (ret && !(flags & ImGuiTabItemFlags_NoPushId))
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx];
PushOverrideID(tab->ID); // We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label)
}
return ret;
}
void ImGui::EndTabItem()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
ImGuiTabBar* tab_bar = g.CurrentTabBar;
if (tab_bar == NULL)
{
IM_ASSERT(tab_bar != NULL && "Needs to be called between BeginTabBar() and EndTabBar()!");
return;
}
IM_ASSERT(tab_bar->LastTabItemIdx >= 0);
ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx];
if (!(tab->Flags & ImGuiTabItemFlags_NoPushId))
window->IDStack.pop_back();
}
bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags)
{
// Layout whole tab bar if not already done
if (tab_bar->WantLayout)
TabBarLayout(tab_bar);
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return false;
const ImGuiStyle& style = g.Style;
const ImGuiID id = TabBarCalcTabID(tab_bar, label);
// If the user called us with *p_open == false, we early out and don't render. We make a dummy call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID.
if (p_open && !*p_open)
{
PushItemFlag(ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus, true);
ItemAdd(ImRect(), id);
PopItemFlag();
return false;
}
// Calculate tab contents size
ImVec2 size = TabItemCalcSize(label, p_open != NULL);
// Acquire tab data
ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, id);
bool tab_is_new = false;
if (tab == NULL)
{
tab_bar->Tabs.push_back(ImGuiTabItem());
tab = &tab_bar->Tabs.back();
tab->ID = id;
tab->Width = size.x;
tab_is_new = true;
}
tab_bar->LastTabItemIdx = (short)tab_bar->Tabs.index_from_ptr(tab);
tab->WidthContents = size.x;
if (p_open == NULL)
flags |= ImGuiTabItemFlags_NoCloseButton;
const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);
const bool tab_bar_focused = (tab_bar->Flags & ImGuiTabBarFlags_IsFocused) != 0;
const bool tab_appearing = (tab->LastFrameVisible + 1 < g.FrameCount);
tab->LastFrameVisible = g.FrameCount;
tab->Flags = flags;
// Append name with zero-terminator
tab->NameOffset = tab_bar->TabsNames.size();
tab_bar->TabsNames.append(label, label + strlen(label) + 1);
// If we are not reorderable, always reset offset based on submission order.
// (We already handled layout and sizing using the previous known order, but sizing is not affected by order!)
if (!tab_appearing && !(tab_bar->Flags & ImGuiTabBarFlags_Reorderable))
{
tab->Offset = tab_bar->OffsetNextTab;
tab_bar->OffsetNextTab += tab->Width + g.Style.ItemInnerSpacing.x;
}
// Update selected tab
if (tab_appearing && (tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs) && tab_bar->NextSelectedTabId == 0)
if (!tab_bar_appearing || tab_bar->SelectedTabId == 0)
tab_bar->NextSelectedTabId = id; // New tabs gets activated
if ((flags & ImGuiTabItemFlags_SetSelected) && (tab_bar->SelectedTabId != id)) // SetSelected can only be passed on explicit tab bar
tab_bar->NextSelectedTabId = id;
// Lock visibility
bool tab_contents_visible = (tab_bar->VisibleTabId == id);
if (tab_contents_visible)
tab_bar->VisibleTabWasSubmitted = true;
// On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches
if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing)
if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs))
tab_contents_visible = true;
if (tab_appearing && !(tab_bar_appearing && !tab_is_new))
{
PushItemFlag(ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus, true);
ItemAdd(ImRect(), id);
PopItemFlag();
return tab_contents_visible;
}
if (tab_bar->SelectedTabId == id)
tab->LastFrameSelected = g.FrameCount;
// Backup current layout position
const ImVec2 backup_main_cursor_pos = window->DC.CursorPos;
// Layout
size.x = tab->Width;
window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2((float)(int)tab->Offset - tab_bar->ScrollingAnim, 0.0f);
ImVec2 pos = window->DC.CursorPos;
ImRect bb(pos, pos + size);
// We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation)
bool want_clip_rect = (bb.Min.x < tab_bar->BarRect.Min.x) || (bb.Max.x >= tab_bar->BarRect.Max.x);
if (want_clip_rect)
PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->BarRect.Min.x), bb.Min.y - 1), ImVec2(tab_bar->BarRect.Max.x, bb.Max.y), true);
ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos;
ItemSize(bb.GetSize(), style.FramePadding.y);
window->DC.CursorMaxPos = backup_cursor_max_pos;
if (!ItemAdd(bb, id))
{
if (want_clip_rect)
PopClipRect();
window->DC.CursorPos = backup_main_cursor_pos;
return tab_contents_visible;
}
// Click to Select a tab
ImGuiButtonFlags button_flags = (ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_AllowItemOverlap);
if (g.DragDropActive)
button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);
if (pressed)
tab_bar->NextSelectedTabId = id;
hovered |= (g.HoveredId == id);
// Allow the close button to overlap unless we are dragging (in which case we don't want any overlapping tabs to be hovered)
if (!held)
SetItemAllowOverlap();
// Drag and drop: re-order tabs
if (held && !tab_appearing && IsMouseDragging(0))
{
if (!g.DragDropActive && (tab_bar->Flags & ImGuiTabBarFlags_Reorderable))
{
// While moving a tab it will jump on the other side of the mouse, so we also test for MouseDelta.x
if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < bb.Min.x)
{
if (tab_bar->Flags & ImGuiTabBarFlags_Reorderable)
TabBarQueueChangeTabOrder(tab_bar, tab, -1);
}
else if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > bb.Max.x)
{
if (tab_bar->Flags & ImGuiTabBarFlags_Reorderable)
TabBarQueueChangeTabOrder(tab_bar, tab, +1);
}
}
}
#if 0
if (hovered && g.HoveredIdNotActiveTimer > 0.50f && bb.GetWidth() < tab->WidthContents)
{
// Enlarge tab display when hovering
bb.Max.x = bb.Min.x + (float)(int)ImLerp(bb.GetWidth(), tab->WidthContents, ImSaturate((g.HoveredIdNotActiveTimer - 0.40f) * 6.0f));
display_draw_list = GetForegroundDrawList(window);
TabItemBackground(display_draw_list, bb, flags, GetColorU32(ImGuiCol_TitleBgActive));
}
#endif
// Render tab shape
ImDrawList* display_draw_list = window->DrawList;
const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabUnfocused));
TabItemBackground(display_draw_list, bb, flags, tab_col);
RenderNavHighlight(bb, id);
// Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget.
const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup);
if (hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1)))
tab_bar->NextSelectedTabId = id;
if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
// Render tab label, process close button
const ImGuiID close_button_id = p_open ? window->GetID((void*)((intptr_t)id + 1)) : 0;
bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id);
if (just_closed && p_open != NULL)
{
*p_open = false;
TabBarCloseTab(tab_bar, tab);
}
// Restore main window position so user can draw there
if (want_clip_rect)
PopClipRect();
window->DC.CursorPos = backup_main_cursor_pos;
// Tooltip (FIXME: Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer)
// We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar (which g.HoveredId ignores)
if (g.HoveredId == id && !held && g.HoveredIdNotActiveTimer > 0.50f && IsItemHovered())
if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip))
SetTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label);
return tab_contents_visible;
}
// [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed.
// To use it to need to call the function SetTabItemClosed() after BeginTabBar() and before any call to BeginTabItem()
void ImGui::SetTabItemClosed(const char* label)
{
ImGuiContext& g = *GImGui;
bool is_within_manual_tab_bar = g.CurrentTabBar && !(g.CurrentTabBar->Flags & ImGuiTabBarFlags_DockNode);
if (is_within_manual_tab_bar)
{
ImGuiTabBar* tab_bar = g.CurrentTabBar;
IM_ASSERT(tab_bar->WantLayout); // Needs to be called AFTER BeginTabBar() and BEFORE the first call to BeginTabItem()
ImGuiID tab_id = TabBarCalcTabID(tab_bar, label);
TabBarRemoveTab(tab_bar, tab_id);
}
}
ImVec2 ImGui::TabItemCalcSize(const char* label, bool has_close_button)
{
ImGuiContext& g = *GImGui;
ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x, label_size.y + g.Style.FramePadding.y * 2.0f);
if (has_close_button)
size.x += g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize); // We use Y intentionally to fit the close button circle.
else
size.x += g.Style.FramePadding.x + 1.0f;
return ImVec2(ImMin(size.x, TabBarCalcMaxTabWidth()), size.y);
}
void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col)
{
// While rendering tabs, we trim 1 pixel off the top of our bounding box so they can fit within a regular frame height while looking "detached" from it.
ImGuiContext& g = *GImGui;
const float width = bb.GetWidth();
IM_UNUSED(flags);
IM_ASSERT(width > 0.0f);
const float rounding = ImMax(0.0f, ImMin(g.Style.TabRounding, width * 0.5f - 1.0f));
const float y1 = bb.Min.y + 1.0f;
const float y2 = bb.Max.y - 1.0f;
draw_list->PathLineTo(ImVec2(bb.Min.x, y2));
draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding, y1 + rounding), rounding, 6, 9);
draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding, y1 + rounding), rounding, 9, 12);
draw_list->PathLineTo(ImVec2(bb.Max.x, y2));
draw_list->PathFillConvex(col);
if (g.Style.TabBorderSize > 0.0f)
{
draw_list->PathLineTo(ImVec2(bb.Min.x + 0.5f, y2));
draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding + 0.5f, y1 + rounding + 0.5f), rounding, 6, 9);
draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding - 0.5f, y1 + rounding + 0.5f), rounding, 9, 12);
draw_list->PathLineTo(ImVec2(bb.Max.x - 0.5f, y2));
draw_list->PathStroke(GetColorU32(ImGuiCol_Border), false, g.Style.TabBorderSize);
}
}
// Render text label (with custom clipping) + Unsaved Document marker + Close Button logic
// We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter.
bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id)
{
ImGuiContext& g = *GImGui;
ImVec2 label_size = CalcTextSize(label, NULL, true);
if (bb.GetWidth() <= 1.0f)
return false;
// Render text label (with clipping + alpha gradient) + unsaved marker
const char* TAB_UNSAVED_MARKER = "*";
ImRect text_pixel_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y);
if (flags & ImGuiTabItemFlags_UnsavedDocument)
{
text_pixel_clip_bb.Max.x -= CalcTextSize(TAB_UNSAVED_MARKER, NULL, false).x;
ImVec2 unsaved_marker_pos(ImMin(bb.Min.x + frame_padding.x + label_size.x + 2, text_pixel_clip_bb.Max.x), bb.Min.y + frame_padding.y + (float)(int)(-g.FontSize * 0.25f));
RenderTextClippedEx(draw_list, unsaved_marker_pos, bb.Max - frame_padding, TAB_UNSAVED_MARKER, NULL, NULL);
}
ImRect text_ellipsis_clip_bb = text_pixel_clip_bb;
// Close Button
// We are relying on a subtle and confusing distinction between 'hovered' and 'g.HoveredId' which happens because we are using ImGuiButtonFlags_AllowOverlapMode + SetItemAllowOverlap()
// 'hovered' will be true when hovering the Tab but NOT when hovering the close button
// 'g.HoveredId==id' will be true when hovering the Tab including when hovering the close button
// 'g.ActiveId==close_button_id' will be true when we are holding on the close button, in which case both hovered booleans are false
bool close_button_pressed = false;
bool close_button_visible = false;
if (close_button_id != 0)
if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == close_button_id)
close_button_visible = true;
if (close_button_visible)
{
ImGuiItemHoveredDataBackup last_item_backup;
const float close_button_sz = g.FontSize;
PushStyleVar(ImGuiStyleVar_FramePadding, frame_padding);
if (CloseButton(close_button_id, ImVec2(bb.Max.x - frame_padding.x * 2.0f - close_button_sz, bb.Min.y)))
close_button_pressed = true;
PopStyleVar();
last_item_backup.Restore();
// Close with middle mouse button
if (!(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2))
close_button_pressed = true;
text_pixel_clip_bb.Max.x -= close_button_sz;
}
float ellipsis_max_x = close_button_visible ? text_pixel_clip_bb.Max.x : bb.Max.x - 1.0f;
RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, text_pixel_clip_bb.Max.x, ellipsis_max_x, label, NULL, &label_size);
return close_button_pressed;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc.
// In the current version, Columns are very weak. Needs to be replaced with a more full-featured system.
//-------------------------------------------------------------------------
// - GetColumnIndex()
// - GetColumnCount()
// - GetColumnOffset()
// - GetColumnWidth()
// - SetColumnOffset()
// - SetColumnWidth()
// - PushColumnClipRect() [Internal]
// - PushColumnsBackground() [Internal]
// - PopColumnsBackground() [Internal]
// - FindOrCreateColumns() [Internal]
// - GetColumnsID() [Internal]
// - BeginColumns()
// - NextColumn()
// - EndColumns()
// - Columns()
//-------------------------------------------------------------------------
int ImGui::GetColumnIndex()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0;
}
int ImGui::GetColumnsCount()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1;
}
float ImGui::GetColumnOffsetFromNorm(const ImGuiColumns* columns, float offset_norm)
{
return offset_norm * (columns->OffMaxX - columns->OffMinX);
}
float ImGui::GetColumnNormFromOffset(const ImGuiColumns* columns, float offset)
{
return offset / (columns->OffMaxX - columns->OffMinX);
}
static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f;
static float GetDraggedColumnOffset(ImGuiColumns* columns, int column_index)
{
// Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
// window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(column_index > 0); // We are not supposed to drag column 0.
IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));
float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x;
x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths))
x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
return x;
}
float ImGui::GetColumnOffset(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
if (columns == NULL)
return 0.0f;
if (column_index < 0)
column_index = columns->Current;
IM_ASSERT(column_index < columns->Columns.Size);
const float t = columns->Columns[column_index].OffsetNorm;
const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t);
return x_offset;
}
static float GetColumnWidthEx(ImGuiColumns* columns, int column_index, bool before_resize = false)
{
if (column_index < 0)
column_index = columns->Current;
float offset_norm;
if (before_resize)
offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize;
else
offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm;
return ImGui::GetColumnOffsetFromNorm(columns, offset_norm);
}
float ImGui::GetColumnWidth(int column_index)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiColumns* columns = window->DC.CurrentColumns;
if (columns == NULL)
return GetContentRegionAvail().x;
if (column_index < 0)
column_index = columns->Current;
return GetColumnOffsetFromNorm(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm);
}
void ImGui::SetColumnOffset(int column_index, float offset)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiColumns* columns = window->DC.CurrentColumns;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
IM_ASSERT(column_index < columns->Columns.Size);
const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1);
const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;
if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow))
offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));
columns->Columns[column_index].OffsetNorm = GetColumnNormFromOffset(columns, offset - columns->OffMinX);
if (preserve_width)
SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
}
void ImGui::SetColumnWidth(int column_index, float width)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);
}
void ImGui::PushColumnClipRect(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
if (column_index < 0)
column_index = columns->Current;
ImGuiColumnData* column = &columns->Columns[column_index];
PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false);
}
// Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns)
void ImGui::PushColumnsBackground()
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
if (columns->Count == 1)
return;
window->DrawList->ChannelsSetCurrent(0);
int cmd_size = window->DrawList->CmdBuffer.Size;
PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false);
IM_UNUSED(cmd_size);
IM_ASSERT(cmd_size == window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd
}
void ImGui::PopColumnsBackground()
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
if (columns->Count == 1)
return;
window->DrawList->ChannelsSetCurrent(columns->Current + 1);
PopClipRect();
}
ImGuiColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id)
{
// We have few columns per window so for now we don't need bother much with turning this into a faster lookup.
for (int n = 0; n < window->ColumnsStorage.Size; n++)
if (window->ColumnsStorage[n].ID == id)
return &window->ColumnsStorage[n];
window->ColumnsStorage.push_back(ImGuiColumns());
ImGuiColumns* columns = &window->ColumnsStorage.back();
columns->ID = id;
return columns;
}
ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count)
{
ImGuiWindow* window = GetCurrentWindow();
// Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
// In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
PushID(0x11223347 + (str_id ? 0 : columns_count));
ImGuiID id = window->GetID(str_id ? str_id : "columns");
PopID();
return id;
}
void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(columns_count >= 1);
IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported
// Acquire storage for the columns set
ImGuiID id = GetColumnsID(str_id, columns_count);
ImGuiColumns* columns = FindOrCreateColumns(window, id);
IM_ASSERT(columns->ID == id);
columns->Current = 0;
columns->Count = columns_count;
columns->Flags = flags;
window->DC.CurrentColumns = columns;
columns->HostCursorPosY = window->DC.CursorPos.y;
columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x;
columns->HostClipRect = window->ClipRect;
columns->HostWorkRect = window->WorkRect;
// Set state for first column
// We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect
const float column_padding = g.Style.ItemSpacing.x;
const float half_clip_extend_x = ImFloor(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize));
const float max_1 = window->WorkRect.Max.x + column_padding - ImMax(column_padding - window->WindowPadding.x, 0.0f);
const float max_2 = window->WorkRect.Max.x + half_clip_extend_x;
columns->OffMinX = window->DC.Indent.x - column_padding + ImMax(column_padding - window->WindowPadding.x, 0.0f);
columns->OffMaxX = ImMax(ImMin(max_1, max_2) - window->Pos.x, columns->OffMinX + 1.0f);
columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y;
// Clear data if columns count changed
if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
columns->Columns.resize(0);
// Initialize default widths
columns->IsFirstFrame = (columns->Columns.Size == 0);
if (columns->Columns.Size == 0)
{
columns->Columns.reserve(columns_count + 1);
for (int n = 0; n < columns_count + 1; n++)
{
ImGuiColumnData column;
column.OffsetNorm = n / (float)columns_count;
columns->Columns.push_back(column);
}
}
for (int n = 0; n < columns_count; n++)
{
// Compute clipping rectangle
ImGuiColumnData* column = &columns->Columns[n];
float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n));
float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
column->ClipRect.ClipWith(window->ClipRect);
}
if (columns->Count > 1)
{
window->DrawList->ChannelsSplit(1 + columns->Count);
window->DrawList->ChannelsSetCurrent(1);
PushColumnClipRect(0);
}
// We don't generally store Indent.x inside ColumnsOffset because it may be manipulated by the user.
float offset_0 = GetColumnOffset(columns->Current);
float offset_1 = GetColumnOffset(columns->Current + 1);
float width = offset_1 - offset_0;
PushItemWidth(width * 0.65f);
window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;
}
void ImGui::NextColumn()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems || window->DC.CurrentColumns == NULL)
return;
ImGuiContext& g = *GImGui;
ImGuiColumns* columns = window->DC.CurrentColumns;
if (columns->Count == 1)
{
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
IM_ASSERT(columns->Current == 0);
return;
}
PopItemWidth();
PopClipRect();
const float column_padding = g.Style.ItemSpacing.x;
columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
if (++columns->Current < columns->Count)
{
// Columns 1+ ignore IndentX (by canceling it out)
// FIXME-COLUMNS: Unnecessary, could be locked?
window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + column_padding;
window->DrawList->ChannelsSetCurrent(columns->Current + 1);
}
else
{
// New row/line
// Column 0 honor IndentX
window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);
window->DrawList->ChannelsSetCurrent(1);
columns->Current = 0;
columns->LineMinY = columns->LineMaxY;
}
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
window->DC.CursorPos.y = columns->LineMinY;
window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
window->DC.CurrLineTextBaseOffset = 0.0f;
PushColumnClipRect(columns->Current); // FIXME-COLUMNS: Could it be an overwrite?
// FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup.
float offset_0 = GetColumnOffset(columns->Current);
float offset_1 = GetColumnOffset(columns->Current + 1);
float width = offset_1 - offset_0;
PushItemWidth(width * 0.65f);
window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;
}
void ImGui::EndColumns()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
ImGuiColumns* columns = window->DC.CurrentColumns;
IM_ASSERT(columns != NULL);
PopItemWidth();
if (columns->Count > 1)
{
PopClipRect();
window->DrawList->ChannelsMerge();
}
const ImGuiColumnsFlags flags = columns->Flags;
columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
window->DC.CursorPos.y = columns->LineMaxY;
if (!(flags & ImGuiColumnsFlags_GrowParentContentsSize))
window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent
// Draw columns borders and handle resize
// The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy
bool is_being_resized = false;
if (!(flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems)
{
// We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.
const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y);
const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y);
int dragging_column = -1;
for (int n = 1; n < columns->Count; n++)
{
ImGuiColumnData* column = &columns->Columns[n];
float x = window->Pos.x + GetColumnOffset(n);
const ImGuiID column_id = columns->ID + ImGuiID(n);
const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH;
const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2));
KeepAliveID(column_id);
if (IsClippedEx(column_hit_rect, column_id, false))
continue;
bool hovered = false, held = false;
if (!(flags & ImGuiColumnsFlags_NoResize))
{
ButtonBehavior(column_hit_rect, column_id, &hovered, &held);
if (hovered || held)
g.MouseCursor = ImGuiMouseCursor_ResizeEW;
if (held && !(column->Flags & ImGuiColumnsFlags_NoResize))
dragging_column = n;
}
// Draw column
const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
const float xi = (float)(int)x;
window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col);
}
// Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.
if (dragging_column != -1)
{
if (!columns->IsBeingResized)
for (int n = 0; n < columns->Count + 1; n++)
columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm;
columns->IsBeingResized = is_being_resized = true;
float x = GetDraggedColumnOffset(columns, dragging_column);
SetColumnOffset(dragging_column, x);
}
}
columns->IsBeingResized = is_being_resized;
window->WorkRect = columns->HostWorkRect;
window->DC.CurrentColumns = NULL;
window->DC.ColumnsOffset.x = 0.0f;
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
}
// [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing]
void ImGui::Columns(int columns_count, const char* id, bool border)
{
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(columns_count >= 1);
ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder);
//flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior
ImGuiColumns* columns = window->DC.CurrentColumns;
if (columns != NULL && columns->Count == columns_count && columns->Flags == flags)
return;
if (columns != NULL)
EndColumns();
if (columns_count != 1)
BeginColumns(id, columns_count, flags);
}
//-------------------------------------------------------------------------
|
NVIDIA-Omniverse/PhysX/flow/external/premake/LICENSE.txt | Copyright (c) 2003-2022 Jason Perkins and individual contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of Premake nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
NVIDIA-Omniverse/PhysX/flow/external/glslang/LICENSE.txt | Here, glslang proper means core GLSL parsing, HLSL parsing, and SPIR-V code
generation. Glslang proper requires use of a number of licenses, one that covers
preprocessing and others that covers non-preprocessing.
Bison was removed long ago. You can build glslang from the source grammar,
using tools of your choice, without using bison or any bison files.
Other parts, outside of glslang proper, include:
- gl_types.h, only needed for OpenGL-like reflection, and can be left out of
a parse and codegen project. See it for its license.
- update_glslang_sources.py, which is not part of the project proper and does
not need to be used.
- the SPIR-V "remapper", which is optional, but has the same license as
glslang proper
- Google tests and SPIR-V tools, and anything in the external subdirectory
are external and optional; see them for their respective licenses.
--------------------------------------------------------------------------------
The core of glslang-proper, minus the preprocessor is licenced as follows:
--------------------------------------------------------------------------------
3-Clause BSD License
--------------------------------------------------------------------------------
//
// Copyright (C) 2015-2018 Google, Inc.
// Copyright (C) <various other dates and companies>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
--------------------------------------------------------------------------------
2-Clause BSD License
--------------------------------------------------------------------------------
Copyright 2020 The Khronos Group Inc
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
The MIT License
--------------------------------------------------------------------------------
Copyright 2020 The Khronos Group Inc
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.
--------------------------------------------------------------------------------
APACHE LICENSE, VERSION 2.0
--------------------------------------------------------------------------------
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------------------
GPL 3 with special bison exception
--------------------------------------------------------------------------------
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
Bison Exception
As a special exception, you may create a larger work that contains part or all
of the Bison parser skeleton and distribute that work under terms of your
choice, so long as that work isn't itself a parser generator using the skeleton
or a modified version thereof as a parser skeleton. Alternatively, if you
modify or redistribute the parser skeleton itself, you may (at your option)
remove this special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public License without
this special exception.
This special exception was added by the Free Software Foundation in version
2.2 of Bison.
END OF TERMS AND CONDITIONS
--------------------------------------------------------------------------------
================================================================================
--------------------------------------------------------------------------------
The preprocessor has the core licenses stated above, plus additional licences:
/****************************************************************************\
Copyright (c) 2002, NVIDIA Corporation.
NVIDIA Corporation("NVIDIA") supplies this software to you in
consideration of your agreement to the following terms, and your use,
installation, modification or redistribution of this NVIDIA software
constitutes acceptance of these terms. If you do not agree with these
terms, please do not use, install, modify or redistribute this NVIDIA
software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, NVIDIA grants you a personal, non-exclusive
license, under NVIDIA's copyrights in this original NVIDIA software (the
"NVIDIA Software"), to use, reproduce, modify and redistribute the
NVIDIA Software, with or without modifications, in source and/or binary
forms; provided that if you redistribute the NVIDIA Software, you must
retain the copyright notice of NVIDIA, this notice and the following
text and disclaimers in all such redistributions of the NVIDIA Software.
Neither the name, trademarks, service marks nor logos of NVIDIA
Corporation may be used to endorse or promote products derived from the
NVIDIA Software without specific prior written permission from NVIDIA.
Except as expressly stated in this notice, no other rights or licenses
express or implied, are granted by NVIDIA herein, including but not
limited to any patent rights that may be infringed by your derivative
works or by other works in which the NVIDIA Software may be
incorporated. No hardware is licensed hereunder.
THE NVIDIA SOFTWARE IS BEING PROVIDED ON AN "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, WARRANTIES OR CONDITIONS OF TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
ITS USE AND OPERATION EITHER ALONE OR IN COMBINATION WITH OTHER
PRODUCTS.
IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT,
INCIDENTAL, EXEMPLARY, CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, LOST PROFITS; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) OR ARISING IN ANY WAY
OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE
NVIDIA SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT,
TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\****************************************************************************/
/*
** Copyright (c) 2014-2016 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and/or associated documentation files (the "Materials"),
** to deal in the Materials without restriction, including without limitation
** the rights to use, copy, modify, merge, publish, distribute, sublicense,
** and/or sell copies of the Materials, and to permit persons to whom the
** Materials are 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 Materials.
**
** MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS
** STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND
** HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/
**
** THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS
** IN THE MATERIALS.
*/ |
NVIDIA-Omniverse/PhysX/flow/PACKAGE-LICENSES/nvflow-LICENSE.md | Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of NVIDIA CORPORATION nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
|
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/NvFlowEditor.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <math.h>
#include "imgui.h"
#include "Loader.h"
#include "ImguiRenderer.h"
#include "ShapeRenderer.h"
#include "FrameCapture.h"
#include "NvFlowArray.h"
#include "NvFlowUploadBuffer.h"
#include "Camera.h"
#include "Timer.h"
#include "NvFlowDatabase.h"
#include "EditorCommon.h"
int testStandaloneMode();
void printError(const char* str, void* userdata)
{
fprintf(stderr, "FlowLoaderError: %s\n", str);
}
int init(App* ptr)
{
// initialize GLFW
if (!ptr->headless)
{
if (editorGlfw_init(ptr))
{
return 1;
}
}
// initialize graphics
{
NvFlowSwapchainDesc swapchainDesc = {};
editorGlfw_getSwapchainDesc(ptr, &swapchainDesc);
editorCompute_init(&ptr->compute, &swapchainDesc, ptr->headless);
ptr->camera = NvFlowCameraCreate((int)ptr->windowWidth, (int)ptr->windowHeight);
}
NvFlowContext* context = ptr->compute.loader.deviceInterface.getContext(ptr->compute.deviceQueue);
NvFlowLogPrint_t logPrint = ptr->compute.contextInterface.getLogPrint(context);
// initialize imgui
if (!ptr->headless)
{
editorImgui_init(&ptr->imgui, &ptr->compute.contextInterface, context);
}
// initialize shape renderer
{
NvFlowShapeRendererInterface_duplicate(&ptr->shapeRendererInterface, NvFlowGetShapeRendererInterface());
ptr->shapeRenderer = ptr->shapeRendererInterface.create(&ptr->compute.contextInterface, context);
logPrint(eNvFlowLogLevel_info, "Initialized Shape Renderer");
}
// initialize frame capture
{
NvFlowFrameCaptureInterface_duplicate(&ptr->frameCaptureInterface, NvFlowGetFrameCaptureInterface());
ptr->frameCapture = ptr->frameCaptureInterface.create(&ptr->compute.contextInterface, context);
logPrint(eNvFlowLogLevel_info, "Initialized Frame Capture");
}
// initialize flow
{
editorFlow_init(&ptr->compute, &ptr->flow);
}
// initialize profiling
{
fopen_s(&ptr->compute.perflog, "NvFlowPerfLog.txt", "w");
if (ptr->compute.perflog)
{
ptr->compute.loader.deviceInterface.enableProfiler(context, &ptr->compute, editorCompute_reportEntries);
}
appTimerInit(&ptr->flowTimerCPU);
appTimerInit(&ptr->imguiTimerCPU);
appTimerInit(&ptr->presentTimerCPU);
}
return 0;
}
int update(App* ptr)
{
// fixed dt for the moment
float deltaTime = 1.f / 60.f;
NvFlowTexture* swapchainTexture = nullptr;
if (!ptr->headless)
{
swapchainTexture = ptr->compute.loader.deviceInterface.getSwapchainFrontTexture(ptr->compute.swapchain);
}
NvFlowContext* context = ptr->compute.loader.deviceInterface.getContext(ptr->compute.deviceQueue);
NvFlowFloat4x4 projection = {};
NvFlowFloat4x4 view = {};
NvFlowCameraGetProjection(ptr->camera, &projection, float(ptr->windowWidth), float(ptr->windowHeight));
NvFlowCameraGetView(ptr->camera, &view);
NvFlowCameraAnimationTick(ptr->camera, 1.f / 60.f);
NvFlowTextureTransient* offscreenColorTransient = nullptr;
NvFlowTextureTransient* offscreenDepthTransient = nullptr;
if (ptr->windowWidth != 0 && ptr->windowHeight != 0)
{
NvFlowTextureDesc texDesc = {};
texDesc.textureType = eNvFlowTextureType_2d;
texDesc.usageFlags = eNvFlowTextureUsage_rwTexture | eNvFlowTextureUsage_texture;
texDesc.format = eNvFlowFormat_r16g16b16a16_float;
texDesc.width = ptr->windowWidth;
texDesc.height = ptr->windowHeight;
texDesc.depth = 1u;
texDesc.mipLevels = 1u;
offscreenColorTransient = ptr->compute.contextInterface.getTextureTransient(context, &texDesc);
texDesc.format = eNvFlowFormat_r32_float;
offscreenDepthTransient = ptr->compute.contextInterface.getTextureTransient(context, &texDesc);
}
if (offscreenColorTransient)
{
if (!ptr->flow.simonly)
{
NvFlowFloat4 spherePositionRadius[1] = { {-100.f, 0.f, 0.f, 50.f} };
NvFlowShapeRendererParams shapeParams = {};
shapeParams.numSpheres = ptr->sphereEnabled ? 1u : 0u;
shapeParams.spherePositionRadius = spherePositionRadius;
ptr->shapeRendererInterface.render(
context,
ptr->shapeRenderer,
&shapeParams,
&view,
&projection,
ptr->windowWidth,
ptr->windowHeight,
offscreenDepthTransient,
offscreenColorTransient
);
}
editorFlow_presimulate(&ptr->compute, &ptr->flow, deltaTime, ptr->isPaused);
appTimerBegin(&ptr->flowTimerCPU);
editorFlow_simulate(&ptr->compute, &ptr->flow, deltaTime, ptr->isPaused);
if (!ptr->flow.simonly)
{
editorFlow_offscreen(&ptr->compute, &ptr->flow);
NvFlowTextureTransient* colorFrontTransient = offscreenColorTransient;
editorFlow_render(
&ptr->compute,
&ptr->flow,
&colorFrontTransient,
offscreenDepthTransient,
ptr->windowWidth,
ptr->windowHeight,
&view,
&projection
);
// testing
ptr->compute.loader.gridInterface.copyTexture(
context,
ptr->flow.grid,
ptr->windowWidth,
ptr->windowHeight,
eNvFlowFormat_r16g16b16a16_float,
colorFrontTransient,
&colorFrontTransient
);
offscreenColorTransient = colorFrontTransient;
}
editorFlow_unmap(&ptr->compute, &ptr->flow);
appTimerEnd(&ptr->flowTimerCPU);
float flowCpuTime = 0.f;
appTimerGetResults(&ptr->flowTimerCPU, &flowCpuTime);
float aveFlowCpuTime = 0.f;
if (appTimerUpdateStats(&ptr->flowTimerCPU, flowCpuTime, 60.f, &aveFlowCpuTime))
{
printf("Average Flow CPU time = %f ms\n", 1000.f * aveFlowCpuTime);
}
}
appTimerBegin(&ptr->imguiTimerCPU);
// render imgui
if (swapchainTexture)
{
NvFlowTextureTransient* textureTransient = ptr->compute.contextInterface.registerTextureAsTransient(context, swapchainTexture);
editorGlfw_newFrame(ptr, deltaTime);
editorImgui_update(&ptr->imgui, ptr, &ptr->compute, &ptr->flow);
editorImgui_render(&ptr->imgui, context, offscreenColorTransient, textureTransient, ptr->windowWidth, ptr->windowHeight);
if (ptr->captureEnabled)
{
ptr->frameCaptureInterface.capture(context, ptr->frameCapture, ptr->windowWidth, ptr->windowHeight, textureTransient);
}
ptr->frameCaptureInterface.update(context, ptr->frameCapture);
}
appTimerEnd(&ptr->imguiTimerCPU);
// report results
{
float imguiCpuTime = 0.f;
appTimerGetResults(&ptr->imguiTimerCPU, &imguiCpuTime);
float aveImguiCpuTime = 0.f;
if (appTimerUpdateStats(&ptr->imguiTimerCPU, imguiCpuTime, 60.f, &aveImguiCpuTime))
{
printf("Average Imgui CPU time = %f ms\n", 1000.f * aveImguiCpuTime);
}
}
appTimerBegin(&ptr->presentTimerCPU);
NvFlowUint64 flushedFrameID = 0llu;
if (!ptr->headless)
{
int deviceReset = ptr->compute.loader.deviceInterface.presentSwapchain(ptr->compute.swapchain, ptr->compute.vsync, &flushedFrameID);
if (deviceReset)
{
editorCompute_logPrint(eNvFlowLogLevel_error, "Device Reset!!!");
return 1;
}
}
else
{
ptr->compute.loader.deviceInterface.flush(ptr->compute.deviceQueue, &flushedFrameID, nullptr, nullptr);
}
appTimerEnd(&ptr->presentTimerCPU);
// report results
{
float presentCpuTime = 0.f;
appTimerGetResults(&ptr->presentTimerCPU, &presentCpuTime);
float avePresentCpuTime = 0.f;
if (appTimerUpdateStats(&ptr->presentTimerCPU, presentCpuTime, 60.f, &avePresentCpuTime))
{
printf("Average Present CPU time = %f ms\n", 1000.f * avePresentCpuTime);
}
}
ptr->compute.loader.deviceInterface.waitForFrame(ptr->compute.deviceQueue, flushedFrameID);
// allow benchmark to request exit
if (!ptr->compute.benchmarkShouldRun)
{
ptr->shouldRun = false;
}
if (!ptr->headless)
{
if (editorGlfw_processEvents(ptr))
{
return 1;
}
}
if (!ptr->shouldRun)
{
editorCompute_logPrint(eNvFlowLogLevel_info, "ShouldRun == false");
return 1;
}
return 0;
}
void destroy(App* ptr)
{
NvFlowContext* context = ptr->compute.loader.deviceInterface.getContext(ptr->compute.deviceQueue);
NvFlowLogPrint_t logPrint = ptr->compute.contextInterface.getLogPrint(context);
// destroy profiling
{
appTimerDestroy(&ptr->flowTimerCPU);
appTimerDestroy(&ptr->imguiTimerCPU);
appTimerDestroy(&ptr->presentTimerCPU);
if (ptr->compute.perflog)
{
ptr->compute.loader.deviceInterface.disableProfiler(context);
fclose(ptr->compute.perflog);
ptr->compute.perflog = nullptr;
}
}
// destroy grid
{
editorFlow_destroy(&ptr->compute, &ptr->flow);
}
// destroy frame capture
{
ptr->frameCaptureInterface.destroy(context, ptr->frameCapture);
logPrint(eNvFlowLogLevel_info, "Destroyed Frame Capture");
}
// destroy shape renderer
{
ptr->shapeRendererInterface.destroy(context, ptr->shapeRenderer);
logPrint(eNvFlowLogLevel_info, "Destroyed Shape Renderer");
}
// destroy imgui
if (!ptr->headless)
{
editorImgui_destroy(&ptr->imgui, context);
}
// destroy graphics
{
NvFlowCameraDestroy(ptr->camera);
editorCompute_destroy(&ptr->compute);
}
// destroy GLFW
if (!ptr->headless)
{
editorGlfw_destroy(ptr);
}
}
int main(int argc, char** argv)
{
App app = {};
for (int argIdx = 0; argIdx < argc; argIdx++)
{
if (strcmp(argv[argIdx], "--headless") == 0)
{
app.compute.headless = NV_FLOW_TRUE;
}
else if (strcmp(argv[argIdx], "--vulkan") == 0)
{
app.compute.contextApi = eNvFlowContextApi_vulkan;
}
else if (strcmp(argv[argIdx], "--cpu") == 0)
{
app.compute.contextApi = eNvFlowContextApi_cpu;
}
else if (strcmp(argv[argIdx], "--threads") == 0)
{
argIdx++;
if (argIdx < argc)
{
app.compute.threadCount = atoi(argv[argIdx]);
}
}
else if (strcmp(argv[argIdx], "-o") == 0)
{
argIdx++;
if (argIdx < argc)
{
app.compute.outputFilename = argv[argIdx];
}
}
else if (strcmp(argv[argIdx], "--benchmark") == 0)
{
argIdx++;
if (argIdx < argc)
{
app.compute.benchmarkFrameCount = atoi(argv[argIdx]);
}
}
else if (strcmp(argv[argIdx], "--maxlocations") == 0)
{
argIdx++;
if (argIdx < argc)
{
app.flow.targetMaxLocations = atoi(argv[argIdx]);
}
}
else if (strcmp(argv[argIdx], "--cellsize") == 0)
{
argIdx++;
if (argIdx < argc)
{
app.flow.cellsizeOverride = (float)atof(argv[argIdx]);
}
}
else if (strcmp(argv[argIdx], "--smallblocks") == 0)
{
app.flow.smallBlocksOverride = NV_FLOW_TRUE;
}
else if (strcmp(argv[argIdx], "--simonly") == 0)
{
app.flow.simonly = NV_FLOW_TRUE;
}
else if (strcmp(argv[argIdx], "--stage") == 0)
{
argIdx++;
if (argIdx < argc)
{
app.flow.cmdStage = argv[argIdx];
}
}
else if (strcmp(argv[argIdx], "--standalone") == 0)
{
return testStandaloneMode();
}
}
const char* apiStrs[eNvFlowContextApi_count] = { "Abstract", "Vulkan", "D3D12", "CPU" };
printf("Configuration:\n"
"api(%s)\n"
"threadCount(%d)\n"
"outputFilename(%s)\n"
"benchmarkFrames(%d)\n"
"cellsizeOverride(%f)\n"
"smallBlocksOverride(%d)\n"
"simonly(%d)\n"
"cmdStage(%s)\n"
"maxLocations(%d)\n",
apiStrs[app.compute.contextApi],
app.compute.threadCount,
app.compute.outputFilename ? app.compute.outputFilename : "unset",
app.compute.benchmarkFrameCount,
app.flow.cellsizeOverride,
app.flow.smallBlocksOverride,
app.flow.simonly,
app.flow.cmdStage,
app.flow.targetMaxLocations
);
if (init(&app))
{
return 1;
}
while (!update(&app))
{
}
destroy(&app);
return 0;
}
#ifdef NV_FLOW_DEBUG_ALLOC
#include <stdio.h>
#include <atomic>
std::atomic_int32_t allocCount(0u);
void* operator new(std::size_t sz)
{
if (sz == 0u) sz = 1u;
allocCount++;
return std::malloc(sz);
}
void operator delete(void* ptr)
{
std::free(ptr);
int32_t count = allocCount.fetch_sub(1) - 1;
printf("NvFlowEditor.cpp free() refCount = %d\n", count);
}
void* operator new[](std::size_t sz)
{
if (sz == 0u) sz = 1u;
allocCount++;
return std::malloc(sz);
}
void operator delete[](void* ptr)
{
std::free(ptr);
int32_t count = allocCount.fetch_sub(1) - 1;
printf("NvFlowEditor.cpp free() refCount = %d\n", count);
}
#endif
|
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/Test.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <math.h>
#include "imgui.h"
#include "Loader.h"
#include "ImguiRenderer.h"
#include "ShapeRenderer.h"
#include "FrameCapture.h"
#include "NvFlowArray.h"
#include "NvFlowUploadBuffer.h"
#include "Camera.h"
#include "Timer.h"
#include "NvFlowDatabase.h"
struct NvFlowDatabasePrim
{
NvFlowDatabasePrim* parent;
const char* path;
const char* name;
};
NV_FLOW_INLINE NvFlowDatabasePrim* createPrim(
NvFlowDatabaseContext* context,
NvFlowUint64 version,
NvFlowDatabasePrim* parent,
const char* displayTypename,
const char* path,
const char* name)
{
auto prim = new NvFlowDatabasePrim();
prim->parent = parent;
prim->path = path;
prim->name = name;
printf("Create prim: displayTypename(%s), path(%s) name(%s)\n", displayTypename, path, name);
return prim;
}
NV_FLOW_INLINE void updatePrim(
NvFlowDatabaseContext* context,
NvFlowUint64 version,
NvFlowUint64 minActiveVersion,
NvFlowDatabasePrim* prim)
{
}
NV_FLOW_INLINE void markDestroyedPrim(NvFlowDatabaseContext* context, NvFlowDatabasePrim* prim)
{
printf("MarkDestroyed prim: path(%s) name(%s)\n", prim->path, prim->name);
}
NV_FLOW_INLINE void destroyPrim(NvFlowDatabaseContext* context, NvFlowDatabasePrim* prim)
{
printf("Destroy prim: path(%s) name(%s)\n", prim->path, prim->name);
delete prim;
}
struct NvFlowDatabaseValue
{
NvFlowArray<NvFlowUint8> data;
NvFlowUint64 version;
NvFlowUint64 lastUsed;
};
struct NvFlowDatabaseAttr
{
NvFlowRingBufferPointer<NvFlowDatabaseValue*> values;
};
NV_FLOW_INLINE NvFlowDatabaseValue* copyArray(
NvFlowUint64 version,
NvFlowUint64 minActiveVersion,
NvFlowDatabaseAttr* attr,
const NvFlowReflectData* reflectData,
NvFlowUint8* mappedData)
{
auto value = attr->values.allocateBackPointer();
//printf("Creating %s %p!!! version(%llu) minActiveVersion(%llu) active(%llu) free(%llu)\n",
// reflectData->name, value, version, minActiveVersion,
// attr->values.activeCount(), attr->values.freeCount());
value->version = version;
value->lastUsed = version;
value->data.size = 0u;
NvFlowUint8** pData = (NvFlowUint8**)(mappedData + reflectData->dataOffset);
NvFlowUint64* pArraySize = (NvFlowUint64*)(mappedData + reflectData->arraySizeOffset);
const NvFlowUint8* srcData = (*pData);
NvFlowUint64 srcSizeInBytes = reflectData->dataType->elementSize * (*pArraySize);
value->data.reserve(srcSizeInBytes);
value->data.size = srcSizeInBytes;
if (srcData)
{
//printf("Memcpy %p to %p of %llu bytes\n", srcData, value->data.data, srcSizeInBytes);
memcpy(value->data.data, srcData, srcSizeInBytes);
}
else
{
memset(value->data.data, 0, srcSizeInBytes);
}
// override to owned copy
*pData = value->data.data;
return value;
}
NV_FLOW_INLINE NvFlowDatabaseAttr* createAttr(
NvFlowDatabaseContext* context,
NvFlowUint64 version,
NvFlowDatabasePrim* prim,
const NvFlowReflectData* reflectData,
NvFlowUint8* mappedData)
{
auto attr = new NvFlowDatabaseAttr();
if (reflectData->reflectMode & eNvFlowReflectMode_array)
{
copyArray(version, version, attr, reflectData, mappedData);
}
if (reflectData->dataType->dataType == eNvFlowType_float &&
strcmp(reflectData->name, "colorScale") == 0)
{
float* pColorScale = (float*)(mappedData + reflectData->dataOffset);
*pColorScale = 1.f;
}
return attr;
}
NV_FLOW_INLINE void updateAttr(
NvFlowDatabaseContext* context,
NvFlowUint64 version,
NvFlowUint64 minActiveVersion,
NvFlowDatabaseAttr* attr,
const NvFlowReflectData* reflectData,
NvFlowUint8* mappedData)
{
if (reflectData->reflectMode & eNvFlowReflectMode_array)
{
while (attr->values.activeCount() > 1u && attr->values.front()->lastUsed < minActiveVersion)
{
//printf("Popping %s version %llu lastUsed %llu\n", reflectData->name, attr->values.front()->version, attr->values.front()->lastUsed);
attr->values.popFront();
}
#if 0
for (NvFlowUint64 idx = 0u; idx < attr->values.activeCount() + attr->values.freeCount(); idx++)
{
auto ptr = attr->values[idx - attr->values.freeCount()];
if (idx < attr->values.freeCount())
{
printf("free element [%llu] version %llu lastUsed %llu\n", idx, ptr->version, ptr->lastUsed);
}
else
{
printf("element [%llu] version %llu lastUsed %llu\n", idx, ptr->version, ptr->lastUsed);
}
}
#endif
// Copy each frame to test recycling
if (attr->values.activeCount() > 0u && attr->values.back()->version != version)
{
copyArray(version, minActiveVersion, attr, reflectData, mappedData);
}
if (attr->values.activeCount() > 0u)
{
attr->values.back()->lastUsed = version;
}
while (attr->values.activeCount() > 0u && attr->values.front()->lastUsed < minActiveVersion)
{
//printf("Popping %s version %llu lastUsed %llu\n", reflectData->name, attr->values.front()->version, attr->values.front()->lastUsed);
attr->values.popFront();
}
}
}
NV_FLOW_INLINE void markDestroyedAttr(NvFlowDatabaseContext* context, NvFlowDatabaseAttr* attr)
{
}
NV_FLOW_INLINE void destroyAttr(NvFlowDatabaseContext* context, NvFlowDatabaseAttr* attr)
{
delete attr;
}
static const NvFlowDatabaseInterface iface = {
createPrim, updatePrim, markDestroyedPrim, destroyPrim,
createAttr, updateAttr, markDestroyedAttr, destroyAttr
};
void testDatabase()
{
NvFlowDatabase versioned = {};
auto type = versioned.createType(&NvFlowGridSimulateLayerParams_NvFlowReflectDataType, "FlowSimulate");
NvFlowUint64 version = 64u;
auto v0 = versioned.createInstance<&iface>(nullptr, version, type, "root/", "test0");
auto v1 = versioned.createInstance<&iface>(nullptr, version, type, "root/", "test1");
auto v2 = versioned.createInstance<&iface>(nullptr, version, type, "root/", "test2");
for (NvFlowUint64 updateIdx = 0u; updateIdx < 4096u; updateIdx++)
{
versioned.update<&iface>(nullptr, version, version - 6u);
if (updateIdx == 64u)
{
versioned.markInstanceForDestroy<&iface>(nullptr, v2);
}
NvFlowDatabaseSnapshot snapshot = {};
versioned.getSnapshot(&snapshot, version);
auto ptr = (NvFlowGridSimulateLayerParams*)snapshot.typeSnapshots[0].instanceDatas[0];
version++;
}
versioned.update<&iface>(nullptr, version, ~0llu);
versioned.destroy<&iface>(nullptr);
}
void testArray()
{
NvFlowArrayPointer<int*> testArray;
testArray.allocateBackPointer();
testArray.allocateBackPointer();
testArray.allocateBackPointer();
testArray.size = 0u;
testArray.reserve(64u);
testArray.allocateBackPointer();
testArray.allocateBackPointer();
testArray.allocateBackPointer();
testArray.allocateBackPointer();
testArray.allocateBackPointer();
testArray.allocateBackPointer();
}
|
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/ImguiRenderer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
struct NvFlowImguiRenderer;
struct NvFlowImguiRendererInterface
{
NV_FLOW_REFLECT_INTERFACE();
NvFlowImguiRenderer*(NV_FLOW_ABI* create)(
NvFlowContextInterface* contextInterface,
NvFlowContext* context,
unsigned char* pixels,
int texWidth,
int texHeight
);
void(NV_FLOW_ABI* destroy)(NvFlowContext* context, NvFlowImguiRenderer* renderer);
void(NV_FLOW_ABI* render)(NvFlowContext* context, NvFlowImguiRenderer* renderer, ImDrawData* drawData, NvFlowUint width, NvFlowUint height, NvFlowTextureTransient* colorIn, NvFlowTextureTransient* colorOut);
};
#define NV_FLOW_REFLECT_TYPE NvFlowImguiRendererInterface
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_FUNCTION_POINTER(create, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroy, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(render, 0, 0)
NV_FLOW_REFLECT_END(0)
NV_FLOW_REFLECT_INTERFACE_IMPL()
#undef NV_FLOW_REFLECT_TYPE
NvFlowImguiRendererInterface* NvFlowGetImguiRendererInterface(); |
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/EditorCommon.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <math.h>
#include "imgui.h"
#include "Loader.h"
#include "ImguiRenderer.h"
#include "ShapeRenderer.h"
#include "FrameCapture.h"
#include "NvFlowArray.h"
#include "NvFlowString.h"
#include "NvFlowUploadBuffer.h"
#include "Camera.h"
#include "Timer.h"
#include "NvFlowDatabase.h"
#include "NvFlowStringHash.h"
// Editor stage API
struct EditorFlow;
void editorFlow_clearStage(EditorFlow* ptr);
void editorFlow_definePrim(EditorFlow* ptr, const char* type, const char* path, const char* name);
void editorFlow_setAttribute(EditorFlow* ptr, const char* primPath, const char* name, const void* data, NvFlowUint64 sizeInBytes);
void editorFlow_setAttributeFloat(EditorFlow* ptr, const char* primPath, const char* name, float value);
void editorFlow_setAttributeInt(EditorFlow* ptr, const char* primPath, const char* name, int value);
void editorFlow_setAttributeUint(EditorFlow* ptr, const char* primPath, const char* name, NvFlowUint value);
void editorFlow_setAttributeBool(EditorFlow* ptr, const char* primPath, const char* name, NvFlowBool32 value);
void editorFlow_setAttributeFloat3(EditorFlow* ptr, const char* primPath, const char* name, NvFlowFloat3 value);
void editorFlow_setAttributeFloat3Array(EditorFlow* ptr, const char* primPath, const char* name, const NvFlowFloat3* values, NvFlowUint64 elementCount);
void editorFlow_setAttributeFloat4Array(EditorFlow* ptr, const char* primPath, const char* name, const NvFlowFloat4* values, NvFlowUint64 elementCount);
void editorFlow_setAttributeIntArray(EditorFlow* ptr, const char* primPath, const char* name, const int* values, NvFlowUint64 elementCount);
// Builtin Scenes
struct EditorFlowStage
{
const char* stageName;
void*(*init)(EditorFlow* ptr);
void(*update)(EditorFlow* ptr, void* userdata, double time, float deltaTime);
void(*destroy)(EditorFlow* ptr, void* userdata);
};
void editorFlowStage_getBuiltinStages(const EditorFlowStage*** pStages, NvFlowUint64* pStageCount);
void editorFlowStage_applyOverrides(EditorFlow* ptr, float cellsizeOverride, NvFlowBool32 smallBlocksOverride);
// Editor subsystems
struct App;
void printError(const char* str, void* userdata);
struct EditorCompute
{
// compute config
NvFlowContextApi contextApi = eNvFlowContextApi_vulkan;
NvFlowUint threadCount = 0u;
NvFlowBool32 headless = NV_FLOW_FALSE;
NvFlowBool32 vsync = NV_FLOW_TRUE;
// loader/compute foundation
void* nvFlowModule = nullptr;
void* nvFlowExtModule = nullptr;
NvFlowLoader loader = {};
NvFlowContextInterface contextInterface = {};
NvFlowDeviceManager* deviceManager = nullptr;
NvFlowDevice* device = nullptr;
NvFlowDeviceQueue* deviceQueue = nullptr;
NvFlowSwapchain* swapchain = nullptr;
// benchmarking
FILE* perflog = nullptr;
NvFlowArray<const char*> statEntries_label;
NvFlowArray<NvFlowBool32> statEntries_active;
NvFlowArray<float> statEntries_cpuDeltaTime_sum;
NvFlowArray<float> statEntries_cpuDeltaTime_count;
NvFlowArray<float> statEntries_gpuDeltaTime_sum;
NvFlowArray<float> statEntries_gpuDeltaTime_count;
NvFlowArray<const char*> statOut_label;
NvFlowArray<float> statOut_cpu;
NvFlowArray<float> statOut_gpu;
const char* outputFilename = "benchmark.csv";
FILE* outputFile = nullptr;
NvFlowUint benchmarkFrameCount = 0u;
NvFlowUint benchmarkFrameID = 0u;
bool benchmarkShouldRun = true;
NvFlowUint benchmarkActiveBlockCount = 0u;
AppTimer benchmarkTimerCPU = {};
};
void editorCompute_init(EditorCompute* ptr, const NvFlowSwapchainDesc* swapchainDesc, NvFlowBool32 headless);
void editorCompute_destroy(EditorCompute* ptr);
void editorCompute_reportEntries(void* userdata, NvFlowUint64 captureID, NvFlowUint numEntries, NvFlowProfilerEntry* entries);
void editorCompute_logPrint(NvFlowLogLevel level, const char* format, ...);
struct EditorFlowCommand
{
const char* cmd;
const char* path;
const char* name;
const char* type;
const NvFlowUint8* data;
NvFlowUint64 dataSize;
};
struct EditorFlow
{
// flow editor config
NvFlowUint maxLocations = 4096u;
NvFlowUint targetMaxLocations = 4096u;
NvFlowBool32 simonly = NV_FLOW_FALSE;
NvFlowBool32 smallBlocksOverride = NV_FLOW_FALSE;
float cellsizeOverride = 0.f;
const char* cmdStage = nullptr;
NvFlowArray<const EditorFlowStage*> stages;
NvFlowUint64 targetStageIdx = 0llu;
const EditorFlowStage* currentStage = nullptr;
void* stageUserdata = nullptr;
// active state
double absoluteSimTime = 0.0;
double animationTime = 0.0;
NvFlowUint activeBlockCount = 0u;
NvFlowUint3 activeBlockDim = { 0u, 0u, 0u };
NvFlowUint activeBlockCountIsosurface = 0u;
NvFlowUint3 activeBlockDimIsosurface = { 32u, 16u, 16u };
// flow grid
NvFlowGrid* grid = nullptr;
NvFlowGridParamsNamed* gridParamsServer = nullptr;
NvFlowGridParamsNamed* gridParamsClient = nullptr;
NvFlowGridParams* gridParams = nullptr;
NvFlowDatabase gridParamsSet;
NvFlowArray<const char*> typenames;
NvFlowArray<const char*> displayTypenames;
NvFlowArray<const NvFlowReflectDataType*> dataTypes;
NvFlowArray<NvFlowDatabaseType*> types;
NvFlowArray<NvFlowDatabaseInstance*> abstractParamsList;
// dynamic grid params
NvFlowGridParamsDesc gridParamsDesc = {};
NvFlowGridParams* clientGridParams = nullptr;
NvFlowGridParamsSnapshot* paramsSnapshot = nullptr;
NvFlowArray<EditorFlowCommand> commands;
NvFlowStringPool* commandStringPool = nullptr;
NvFlowStringHashTable<NvFlowDatabasePrim*> primMap;
};
void editorFlow_init(EditorCompute* ctx, EditorFlow* ptr);
void editorFlow_presimulate(EditorCompute* ctx, EditorFlow* ptr, float deltaTime, NvFlowBool32 isPaused);
void editorFlow_simulate(EditorCompute* ctx, EditorFlow* ptr, float deltaTime, NvFlowBool32 isPaused);
void editorFlow_offscreen(EditorCompute* ctx, EditorFlow* ptr);
void editorFlow_render(EditorCompute* ctx, EditorFlow* ptr,
NvFlowTextureTransient** colorFrontTransient,
NvFlowTextureTransient* offscreenDepthTransient,
NvFlowUint windowWidth,
NvFlowUint windowHeight,
const NvFlowFloat4x4* view,
const NvFlowFloat4x4* projection
);
void editorFlow_unmap(EditorCompute* ctx, EditorFlow* ptr);
void editorFlow_destroy(EditorCompute* ctx, EditorFlow* ptr);
struct EditorImgui
{
NvFlowImguiRendererInterface imguiRendererInterface = {};
NvFlowImguiRenderer* imguiRenderer = nullptr;
};
void editorImgui_init(EditorImgui* ptr, NvFlowContextInterface* contextInterface, NvFlowContext* context);
void editorImgui_update(
EditorImgui* ptr,
App* app,
EditorCompute* compute,
EditorFlow* flow
);
void editorImgui_render(
EditorImgui* ptr,
NvFlowContext* context,
NvFlowTextureTransient* colorIn,
NvFlowTextureTransient* colorOut,
NvFlowUint windowWidth,
NvFlowUint windowHeight
);
void editorImgui_destroy(EditorImgui* ptr, NvFlowContext* context);
struct App
{
NvFlowUint windowWidth = 1280u;
NvFlowUint windowHeight = 800u;
NvFlowUint windowWidthOld = 1280u;
NvFlowUint windowHeightOld = 800u;
GLFWwindow* window = nullptr;
NvFlowBool32 headless = NV_FLOW_FALSE;
NvFlowBool32 isPaused = NV_FLOW_FALSE;
NvFlowBool32 overlayEnabled = NV_FLOW_FALSE;
NvFlowBool32 editorEnabled = NV_FLOW_TRUE;
NvFlowBool32 sphereEnabled = NV_FLOW_FALSE;
NvFlowBool32 captureEnabled = NV_FLOW_FALSE;
int fullscreenState = 0;
NvFlowBool32 shouldRun = NV_FLOW_TRUE;
int mouseX = 0;
int mouseY = 0;
int mouseYInv = 0;
NvFlowBool32 mouseJustPressed[5u];
NvFlowShapeRendererInterface shapeRendererInterface = {};
NvFlowShapeRenderer* shapeRenderer = nullptr;
NvFlowFrameCaptureInterface frameCaptureInterface = {};
NvFlowFrameCapture* frameCapture = nullptr;
EditorImgui imgui = {};
EditorCompute compute = {};
EditorFlow flow = {};
NvFlowCamera* camera = nullptr;
AppTimer flowTimerCPU = {};
AppTimer imguiTimerCPU = {};
AppTimer presentTimerCPU = {};
};
int editorGlfw_init(App* ptr);
void editorGlfw_getSwapchainDesc(App* ptr, NvFlowSwapchainDesc* outDesc);
void editorGlfw_newFrame(App* ptr, float deltaTime);
int editorGlfw_processEvents(App* ptr);
void editorGlfw_destroy(App* ptr);
#if !defined(_WIN32)
NV_FLOW_INLINE void fopen_s(FILE** streamptr, const char* filename, const char* mode)
{
*streamptr = fopen(filename, mode);
}
#endif
|
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/FrameCapture.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowContext.h"
struct NvFlowFrameCapture;
struct NvFlowFrameCaptureInterface
{
NV_FLOW_REFLECT_INTERFACE();
NvFlowFrameCapture*(NV_FLOW_ABI* create)(NvFlowContextInterface* contextInterface, NvFlowContext* context);
void(NV_FLOW_ABI* destroy)(NvFlowContext* context, NvFlowFrameCapture* frameCapture);
void(NV_FLOW_ABI* capture)(NvFlowContext* context, NvFlowFrameCapture* frameCapture, NvFlowUint width, NvFlowUint height, NvFlowTextureTransient* texture);
void(NV_FLOW_ABI* update)(NvFlowContext* context, NvFlowFrameCapture* frameCapture);
};
#define NV_FLOW_REFLECT_TYPE NvFlowFrameCaptureInterface
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_FUNCTION_POINTER(create, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroy, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(capture, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(update, 0, 0)
NV_FLOW_REFLECT_END(0)
NV_FLOW_REFLECT_INTERFACE_IMPL()
#undef NV_FLOW_REFLECT_TYPE
NvFlowFrameCaptureInterface* NvFlowGetFrameCaptureInterface(); |
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/StandaloneTest.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include "NvFlowLoader.h"
struct FlowStandaloneInstance;
struct FlowStandaloneBuffer;
struct FlowStandaloneSemaphore;
struct FlowStandaloneOutput
{
FlowStandaloneBuffer* temperatureNanoVdb;
FlowStandaloneBuffer* fuelNanoVdb;
FlowStandaloneBuffer* burnNanoVdb;
FlowStandaloneBuffer* smokeNanoVdb;
FlowStandaloneBuffer* velocityNanoVdb;
FlowStandaloneBuffer* divergenceNanoVdb;
uint64_t currentFrame;
uint64_t readbackFrame;
uint8_t* temperatureNanoVdbReadback;
uint64_t temperatureNanoVdbReadbackSize;
uint8_t* fuelNanoVdbReadback;
uint64_t fuelNanoVdbReadbackSize;
uint8_t* burnNanoVdbReadback;
uint64_t burnNanoVdbReadbackSize;
uint8_t* smokeNanoVdbReadback;
uint64_t smokeNanoVdbReadbackSize;
uint8_t* velocityNanoVdbReadback;
uint64_t velocityNanoVdbReadbackSize;
uint8_t* divergenceNanoVdbReadback;
uint64_t divergenceNanoVdbReadbackSize;
};
struct FlowStandaloneInstance
{
NvFlowLoader loader = {};
NvFlowContextInterface contextInterface = {};
NvFlowDeviceManager* deviceManager = nullptr;
NvFlowDevice* device = nullptr;
NvFlowDeviceQueue* deviceQueue = nullptr;
NvFlowGrid* grid = nullptr;
NvFlowGridParamsNamed* gridParamsNamed = nullptr;
NvFlowBuffer* temperatureNanoVdb = nullptr;
NvFlowBuffer* fuelNanoVdb = nullptr;
NvFlowBuffer* burnNanoVdb = nullptr;
NvFlowBuffer* smokeNanoVdb = nullptr;
NvFlowBuffer* velocityNanoVdb = nullptr;
NvFlowBuffer* divergenceNanoVdb = nullptr;
bool invalid = false;
};
static void flowLoaderError(const char* str, void* userdata)
{
printf("omni.flow.usd failed to load Flow library!!!\n%s\n", str);
}
static void logPrint(NvFlowLogLevel level, const char* format, ...)
{
va_list args;
va_start(args, format);
char buf[256u];
buf[0u] = '\0';
const char* prefix = "Unknown";
if (level == eNvFlowLogLevel_error)
{
vsnprintf(buf, 256u, format, args);
printf("FlowError: %s\n", buf);
}
else if (level == eNvFlowLogLevel_warning)
{
vsnprintf(buf, 256u, format, args);
printf("FlowWarn: %s\n", buf);
}
else if (level == eNvFlowLogLevel_info)
{
vsnprintf(buf, 256u, format, args);
printf("FlowInfo: %s\n", buf);
}
va_end(args);
}
bool flowStandaloneInitInstance(FlowStandaloneInstance* ptr, uint32_t deviceIdx, bool cudaInteropEnabled, uint32_t maxBlocks)
{
NvFlowLoaderInit(&ptr->loader, flowLoaderError, nullptr);
if (!ptr->loader.module_nvflow || !ptr->loader.module_nvflowext)
{
printf("FlowStandaloneInstance init() failed!!!\n");
return false;
}
// initialize graphics
{
NvFlowBool32 validation = NV_FLOW_TRUE;
ptr->deviceManager = ptr->loader.deviceInterface.createDeviceManager(validation, nullptr, 0u);
NvFlowDeviceDesc deviceDesc = {};
deviceDesc.deviceIndex = deviceIdx;
deviceDesc.enableExternalUsage = cudaInteropEnabled;
deviceDesc.logPrint = logPrint;
ptr->device = ptr->loader.deviceInterface.createDevice(ptr->deviceManager, &deviceDesc);
ptr->deviceQueue = ptr->loader.deviceInterface.getDeviceQueue(ptr->device);
NvFlowContextInterface_duplicate(&ptr->contextInterface, ptr->loader.deviceInterface.getContextInterface(ptr->deviceQueue));
}
NvFlowContext* context = ptr->loader.deviceInterface.getContext(ptr->deviceQueue);
// initialize grid
{
NvFlowGridDesc gridDesc = NvFlowGridDesc_default;
if (maxBlocks > 0u)
{
gridDesc.maxLocations = maxBlocks;
}
ptr->grid = ptr->loader.gridInterface.createGrid(&ptr->contextInterface, context, &ptr->loader.opList, &ptr->loader.extOpList, &gridDesc);
ptr->gridParamsNamed = ptr->loader.gridParamsInterface.createGridParamsNamed("flowUsd");
}
return true;
}
FlowStandaloneInstance* flowStandaloneCreateInstance(uint32_t deviceIdx, bool cudaInteropEnabled, uint32_t maxBlocks)
{
auto ptr = new FlowStandaloneInstance();
if (!flowStandaloneInitInstance(ptr, deviceIdx, cudaInteropEnabled, maxBlocks))
{
delete ptr;
return nullptr;
}
return ptr;
}
void flowStandaloneDestroyBuffers(FlowStandaloneInstance* ptr)
{
NvFlowContext* context = ptr->loader.deviceInterface.getContext(ptr->deviceQueue);
// release old acquires
if (ptr->temperatureNanoVdb)
{
ptr->contextInterface.destroyBuffer(context, ptr->temperatureNanoVdb);
ptr->temperatureNanoVdb = nullptr;
}
if (ptr->fuelNanoVdb)
{
ptr->contextInterface.destroyBuffer(context, ptr->fuelNanoVdb);
ptr->fuelNanoVdb = nullptr;
}
if (ptr->burnNanoVdb)
{
ptr->contextInterface.destroyBuffer(context, ptr->burnNanoVdb);
ptr->burnNanoVdb = nullptr;
}
if (ptr->smokeNanoVdb)
{
ptr->contextInterface.destroyBuffer(context, ptr->smokeNanoVdb);
ptr->smokeNanoVdb = nullptr;
}
if (ptr->velocityNanoVdb)
{
ptr->contextInterface.destroyBuffer(context, ptr->velocityNanoVdb);
ptr->velocityNanoVdb = nullptr;
}
if (ptr->velocityNanoVdb)
{
ptr->contextInterface.destroyBuffer(context, ptr->velocityNanoVdb);
ptr->velocityNanoVdb = nullptr;
}
}
void flowStandaloneDestroyInstance(FlowStandaloneInstance* ptr)
{
// wait idle
{
ptr->loader.deviceInterface.waitIdle(ptr->deviceQueue);
}
flowStandaloneDestroyBuffers(ptr);
// destroy grid
{
NvFlowContext* context = ptr->loader.deviceInterface.getContext(ptr->deviceQueue);
ptr->loader.gridInterface.destroyGrid(context, ptr->grid);
ptr->loader.gridParamsInterface.destroyGridParamsNamed(ptr->gridParamsNamed);
}
// wait idle
{
NvFlowUint64 flushedFrameID = 0u;
ptr->loader.deviceInterface.flush(ptr->deviceQueue, &flushedFrameID, nullptr, nullptr);
ptr->loader.deviceInterface.waitIdle(ptr->deviceQueue);
}
// destroy graphics
{
ptr->loader.deviceInterface.destroyDevice(ptr->deviceManager, ptr->device);
ptr->loader.deviceInterface.destroyDeviceManager(ptr->deviceManager);
}
NvFlowLoaderDestroy(&ptr->loader);
delete ptr;
}
void flowStandaloneUpdateInstance(FlowStandaloneInstance* ptr, double absoluteSimTime, FlowStandaloneOutput* pOutput, bool cpuWait, FlowStandaloneSemaphore* waitSemaphore, FlowStandaloneSemaphore* signalSemaphore)
{
FlowStandaloneOutput output = {};
NvFlowGridRenderData renderData = {};
if (ptr->invalid)
{
if (pOutput)
{
*pOutput = output;
}
return;
}
NvFlowBufferAcquire* temperatureNanoVdbAcquire = nullptr;
NvFlowBufferAcquire* fuelNanoVdbAcquire = nullptr;
NvFlowBufferAcquire* burnNanoVdbAcquire = nullptr;
NvFlowBufferAcquire* smokeNanoVdbAcquire = nullptr;
NvFlowBufferAcquire* velocityNanoVdbAcquire = nullptr;
NvFlowBufferAcquire* divergenceNanoVdbAcquire = nullptr;
NvFlowContext* context = ptr->loader.deviceInterface.getContext(ptr->deviceQueue);
NvFlowGridParams* gridParams = ptr->loader.gridParamsInterface.mapGridParamsNamed(ptr->gridParamsNamed);
NvFlowGridParamsDesc gridParamsDesc = {};
NvFlowGridParamsSnapshot* paramsSnapshot = ptr->loader.gridParamsInterface.getParamsSnapshot(gridParams, absoluteSimTime, 0llu);
if (ptr->loader.gridParamsInterface.mapParamsDesc(gridParams, paramsSnapshot, &gridParamsDesc))
{
ptr->loader.gridInterface.simulate(
context,
ptr->grid,
&gridParamsDesc,
NV_FLOW_FALSE
);
//ptr->loader.gridInterface.offscreen(context, ptr->grid, &gridParamsDesc);
ptr->loader.gridInterface.getRenderData(context, ptr->grid, &renderData);
if (renderData.nanoVdb.temperatureNanoVdb)
{
temperatureNanoVdbAcquire = ptr->contextInterface.enqueueAcquireBuffer(context, renderData.nanoVdb.temperatureNanoVdb);
}
if (renderData.nanoVdb.fuelNanoVdb)
{
fuelNanoVdbAcquire = ptr->contextInterface.enqueueAcquireBuffer(context, renderData.nanoVdb.fuelNanoVdb);
}
if (renderData.nanoVdb.burnNanoVdb)
{
burnNanoVdbAcquire = ptr->contextInterface.enqueueAcquireBuffer(context, renderData.nanoVdb.burnNanoVdb);
}
if (renderData.nanoVdb.smokeNanoVdb)
{
smokeNanoVdbAcquire = ptr->contextInterface.enqueueAcquireBuffer(context, renderData.nanoVdb.smokeNanoVdb);
}
if (renderData.nanoVdb.velocityNanoVdb)
{
velocityNanoVdbAcquire = ptr->contextInterface.enqueueAcquireBuffer(context, renderData.nanoVdb.velocityNanoVdb);
}
if (renderData.nanoVdb.divergenceNanoVdb)
{
divergenceNanoVdbAcquire = ptr->contextInterface.enqueueAcquireBuffer(context, renderData.nanoVdb.divergenceNanoVdb);
}
ptr->loader.gridParamsInterface.unmapParamsDesc(gridParams, paramsSnapshot);
}
NvFlowUint64 flushedFrameID = 0llu;
int deviceReset = ptr->loader.deviceInterface.flush(ptr->deviceQueue, &flushedFrameID, (NvFlowDeviceSemaphore*)waitSemaphore, (NvFlowDeviceSemaphore*)signalSemaphore);
if (deviceReset)
{
printf("FlowStandalone device reset!\n");
ptr->invalid = true;
}
if (cpuWait)
{
ptr->loader.deviceInterface.waitForFrame(ptr->deviceQueue, flushedFrameID);
}
NvFlowUint64 lastCompletedFrame = ptr->contextInterface.getLastFrameCompleted(context);
flowStandaloneDestroyBuffers(ptr);
if (temperatureNanoVdbAcquire)
{
if (!ptr->contextInterface.getAcquiredBuffer(context, temperatureNanoVdbAcquire, &ptr->temperatureNanoVdb))
{
printf("Failed to acquire temperature buffer!!!\n");
}
}
if (fuelNanoVdbAcquire)
{
if (!ptr->contextInterface.getAcquiredBuffer(context, fuelNanoVdbAcquire, &ptr->fuelNanoVdb))
{
printf("Failed to acquire fuel buffer!!!\n");
}
}
if (burnNanoVdbAcquire)
{
if (!ptr->contextInterface.getAcquiredBuffer(context, burnNanoVdbAcquire, &ptr->burnNanoVdb))
{
printf("Failed to acquire burn buffer!!!\n");
}
}
if (smokeNanoVdbAcquire)
{
if (!ptr->contextInterface.getAcquiredBuffer(context, smokeNanoVdbAcquire, &ptr->smokeNanoVdb))
{
printf("Failed to acquire smoke buffer!!!\n");
}
}
if (velocityNanoVdbAcquire)
{
if (!ptr->contextInterface.getAcquiredBuffer(context, velocityNanoVdbAcquire, &ptr->velocityNanoVdb))
{
printf("Failed to acquire velocity buffer!!!\n");
}
}
if (divergenceNanoVdbAcquire)
{
if (!ptr->contextInterface.getAcquiredBuffer(context, divergenceNanoVdbAcquire, &ptr->divergenceNanoVdb))
{
printf("Failed to acquire divergence buffer!!!\n");
}
}
output.temperatureNanoVdb = (FlowStandaloneBuffer*)ptr->temperatureNanoVdb;
output.fuelNanoVdb = (FlowStandaloneBuffer*)ptr->fuelNanoVdb;
output.burnNanoVdb = (FlowStandaloneBuffer*)ptr->burnNanoVdb;
output.smokeNanoVdb = (FlowStandaloneBuffer*)ptr->smokeNanoVdb;
output.velocityNanoVdb = (FlowStandaloneBuffer*)ptr->velocityNanoVdb;
output.divergenceNanoVdb = (FlowStandaloneBuffer*)ptr->divergenceNanoVdb;
// pick latest readback version safe to access
if (renderData.nanoVdb.readbackCount > 0u)
{
for (NvFlowUint64 idx = renderData.nanoVdb.readbackCount - 1u; idx < renderData.nanoVdb.readbackCount; idx--)
{
const auto readback = renderData.nanoVdb.readbacks + idx;
if (lastCompletedFrame >= readback->globalFrameCompleted)
{
output.currentFrame = flushedFrameID;
output.readbackFrame = lastCompletedFrame;
output.temperatureNanoVdbReadback = readback->temperatureNanoVdbReadback;
output.temperatureNanoVdbReadbackSize = readback->temperatureNanoVdbReadbackSize;
output.fuelNanoVdbReadback = readback->fuelNanoVdbReadback;
output.fuelNanoVdbReadbackSize = readback->fuelNanoVdbReadbackSize;
output.burnNanoVdbReadback = readback->burnNanoVdbReadback;
output.burnNanoVdbReadbackSize = readback->burnNanoVdbReadbackSize;
output.smokeNanoVdbReadback = readback->smokeNanoVdbReadback;
output.smokeNanoVdbReadbackSize = readback->smokeNanoVdbReadbackSize;
output.velocityNanoVdbReadback = readback->velocityNanoVdbReadback;
output.velocityNanoVdbReadbackSize = readback->velocityNanoVdbReadbackSize;
output.divergenceNanoVdbReadback = readback->divergenceNanoVdbReadback;
output.divergenceNanoVdbReadbackSize = readback->divergenceNanoVdbReadbackSize;
break;
}
}
}
if (pOutput)
{
*pOutput = output;
}
}
void flowStandaloneGetBufferExternalHandle(FlowStandaloneInstance* ptr, FlowStandaloneBuffer* buffer, void* dstHandle, uint64_t dstHandleSize, NvFlowUint64* pBufferSizeInBytes)
{
auto bufferFlow = (NvFlowBuffer*)buffer;
NvFlowContext* context = ptr->loader.deviceInterface.getContext(ptr->deviceQueue);
ptr->loader.deviceInterface.getBufferExternalHandle(context, bufferFlow, dstHandle, dstHandleSize, pBufferSizeInBytes);
}
void flowStandaloneCloseBufferExternalHandle(FlowStandaloneInstance* ptr, FlowStandaloneBuffer* buffer, const void* srcHandle, uint64_t srcHandleSize)
{
auto bufferFlow = (NvFlowBuffer*)buffer;
NvFlowContext* context = ptr->loader.deviceInterface.getContext(ptr->deviceQueue);
ptr->loader.deviceInterface.closeBufferExternalHandle(context, bufferFlow, srcHandle, srcHandleSize);
}
FlowStandaloneSemaphore* flowStandaloneCreateSemaphore(FlowStandaloneInstance* ptr)
{
return (FlowStandaloneSemaphore*)ptr->loader.deviceInterface.createSemaphore(ptr->device);
}
void flowStandaloneDestroySemaphore(FlowStandaloneInstance* ptr, FlowStandaloneSemaphore* semaphore)
{
auto semaphoreFlow = (NvFlowDeviceSemaphore*)semaphore;
ptr->loader.deviceInterface.destroySemaphore(semaphoreFlow);
}
void flowStandaloneGetSemaphoreExternalHandle(FlowStandaloneInstance* ptr, FlowStandaloneSemaphore* semaphore, void* dstHandle, uint64_t dstHandleSize)
{
auto semaphoreFlow = (NvFlowDeviceSemaphore*)semaphore;
ptr->loader.deviceInterface.getSemaphoreExternalHandle(semaphoreFlow, dstHandle, dstHandleSize);
}
void flowStandaloneCloseSemaphoreExternalHandle(FlowStandaloneInstance* ptr, FlowStandaloneSemaphore* semaphore, const void* srcHandle, uint64_t srcHandleSize)
{
auto semaphoreFlow = (NvFlowDeviceSemaphore*)semaphore;
ptr->loader.deviceInterface.closeSemaphoreExternalHandle(semaphoreFlow, srcHandle, srcHandleSize);
}
/// Test
int testStandaloneMode()
{
FlowStandaloneInstance* ptr = flowStandaloneCreateInstance(0u, false, 0u);
NvFlowGridParamsNamed* paramSrcNamed = ptr->loader.gridParamsInterface.createGridParamsNamed("flowUsd");
NvFlowGridParams* paramSrc = ptr->loader.gridParamsInterface.mapGridParamsNamed(paramSrcNamed);
for (uint32_t idx = 0u; idx < 500; idx++)
{
static NvFlowGridSimulateLayerParams testSimulate = NvFlowGridSimulateLayerParams_default;
static NvFlowGridEmitterSphereParams testSpheres = NvFlowEmitterSphereParams_default;
static NvFlowGridOffscreenLayerParams testOffscreen = NvFlowGridOffscreenLayerParams_default;
static NvFlowGridRenderLayerParams testRender = NvFlowGridRenderLayerParams_default;
testSimulate.nanoVdbExport.enabled = NV_FLOW_TRUE;
testSimulate.nanoVdbExport.readbackEnabled = NV_FLOW_TRUE;
static NvFlowGridSimulateLayerParams* pTestSimulate = &testSimulate;
static NvFlowGridEmitterSphereParams* pTestSpheres = &testSpheres;
static NvFlowGridOffscreenLayerParams* pTestOffscreen = &testOffscreen;
static NvFlowGridRenderLayerParams* pTestRender = &testRender;
static NvFlowUint64 version = 1u;
static NvFlowDatabaseTypeSnapshot typeSnapshots[4u] = {
{version, &NvFlowGridSimulateLayerParams_NvFlowReflectDataType, (NvFlowUint8**)&pTestSimulate, 1u},
{version, &NvFlowGridEmitterSphereParams_NvFlowReflectDataType, (NvFlowUint8**)&pTestSpheres, 1u},
{version, &NvFlowGridOffscreenLayerParams_NvFlowReflectDataType, (NvFlowUint8**)&pTestOffscreen, 1u},
{version, &NvFlowGridRenderLayerParams_NvFlowReflectDataType, (NvFlowUint8**)&pTestRender, 1u}
};
static NvFlowDatabaseSnapshot snapshot = {
version,
typeSnapshots,
4u
};
static NvFlowGridParamsDescSnapshot gridParamsDescSnapshot = { snapshot, 0.0, 1.f / 60.f, NV_FLOW_FALSE, nullptr, 0u };
ptr->loader.gridParamsInterface.commitParams(paramSrc, &gridParamsDescSnapshot);
FlowStandaloneOutput output = {};
flowStandaloneUpdateInstance(ptr, (double)idx, &output, true, nullptr, nullptr);
printf("Standalone instance smoke size = %d\n", (uint32_t)output.smokeNanoVdbReadbackSize);
}
ptr->loader.gridParamsInterface.destroyGridParamsNamed(paramSrcNamed);
flowStandaloneDestroyInstance(ptr);
return 0;
}
|
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/Timer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowTypes.h"
#if defined(_WIN32)
#include <Windows.h>
#else
#include <time.h>
#endif
struct AppTimer
{
NvFlowUint64 freq;
NvFlowUint64 begin;
NvFlowUint64 end;
NvFlowUint state;
float statTimeAccum;
float statTimeCount;
};
NV_FLOW_INLINE void appTimerInit(AppTimer* ptr)
{
ptr->freq = 1ull;
ptr->begin = 0ull;
ptr->end = 0ull;
ptr->state = 0u;
ptr->statTimeAccum = 0.f;
ptr->statTimeCount = 0.f;
}
NV_FLOW_INLINE void appTimerDestroy(AppTimer* ptr)
{
// NOP
}
NV_FLOW_INLINE void appTimerBegin(AppTimer* ptr)
{
if (ptr->state == 0u)
{
#if defined(_WIN32)
LARGE_INTEGER tmpCpuFreq = {};
QueryPerformanceFrequency(&tmpCpuFreq);
ptr->freq = tmpCpuFreq.QuadPart;
LARGE_INTEGER tmpCpuTime = {};
QueryPerformanceCounter(&tmpCpuTime);
ptr->begin = tmpCpuTime.QuadPart;
#else
ptr->freq = 1E9;
timespec timeValue = {};
clock_gettime(CLOCK_MONOTONIC, &timeValue);
ptr->begin = 1E9 * NvFlowUint64(timeValue.tv_sec) + NvFlowUint64(timeValue.tv_nsec);
#endif
ptr->state = 1u;
}
}
NV_FLOW_INLINE void appTimerEnd(AppTimer* ptr)
{
if (ptr->state == 1u)
{
#if defined(_WIN32)
LARGE_INTEGER tmpCpuTime = {};
QueryPerformanceCounter(&tmpCpuTime);
ptr->end = tmpCpuTime.QuadPart;
#else
timespec timeValue = {};
clock_gettime(CLOCK_MONOTONIC, &timeValue);
ptr->end = 1E9 * NvFlowUint64(timeValue.tv_sec) + NvFlowUint64(timeValue.tv_nsec);
#endif
ptr->state = 0u;
}
}
NV_FLOW_INLINE NvFlowBool32 appTimerGetResults(AppTimer* ptr, float* deltaTime)
{
if (ptr->state == 0u)
{
*deltaTime = (float)(((double)(ptr->end - ptr->begin) / (double)(ptr->freq)));
return NV_FLOW_TRUE;
}
return NV_FLOW_FALSE;
}
NV_FLOW_INLINE NvFlowBool32 appTimerUpdateStats(AppTimer* ptr, float deltaTime, float sampleCount, float* pAverageTime)
{
ptr->statTimeAccum += deltaTime;
ptr->statTimeCount += 1.f;
if (ptr->statTimeCount > sampleCount)
{
*pAverageTime = ptr->statTimeAccum / ptr->statTimeCount;
ptr->statTimeAccum = 0.f;
ptr->statTimeCount = 0.f;
return NV_FLOW_TRUE;
}
return NV_FLOW_FALSE;
} |
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/ShapeRenderer.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include "NvFlowLoader.h"
#include "ShapeRenderer.h"
#include "NvFlowUploadBuffer.h"
#include "NvFlowDynamicBuffer.h"
#include "NvFlowMath.h"
#include "shaders/ShapeParams.h"
#include "shaders/ShapeCS.hlsl.h"
namespace NvFlowShapeRendererDefault
{
struct Renderer
{
NvFlowContextInterface contextInterface = {};
ShapeCS_Pipeline shapeCS = {};
NvFlowUploadBuffer spherePositionBuffer = {};
NvFlowUploadBuffer constantBuffer = {};
};
NV_FLOW_CAST_PAIR(NvFlowShapeRenderer, Renderer)
NvFlowShapeRenderer* create(NvFlowContextInterface* contextInterface, NvFlowContext* context)
{
auto ptr = new Renderer();
NvFlowContextInterface_duplicate(&ptr->contextInterface, contextInterface);
ShapeCS_init(&ptr->contextInterface, context, &ptr->shapeCS);
NvFlowBufferUsageFlags bufferUsage = eNvFlowBufferUsage_structuredBuffer | eNvFlowBufferUsage_bufferCopySrc;
NvFlowUploadBuffer_init(&ptr->contextInterface, context, &ptr->spherePositionBuffer, bufferUsage, eNvFlowFormat_unknown, sizeof(NvFlowFloat4));
NvFlowUploadBuffer_init(&ptr->contextInterface, context, &ptr->constantBuffer, eNvFlowBufferUsage_constantBuffer, eNvFlowFormat_unknown, 0u);
return cast(ptr);
}
void destroy(NvFlowContext* context, NvFlowShapeRenderer* renderer)
{
auto ptr = cast(renderer);
NvFlowUploadBuffer_destroy(context, &ptr->spherePositionBuffer);
NvFlowUploadBuffer_destroy(context, &ptr->constantBuffer);
ShapeCS_destroy(context, &ptr->shapeCS);
delete ptr;
}
void render(
NvFlowContext* context,
NvFlowShapeRenderer* renderer, const NvFlowShapeRendererParams* params,
const NvFlowFloat4x4* view,
const NvFlowFloat4x4* projection,
NvFlowUint textureWidth,
NvFlowUint textureHeight,
NvFlowTextureTransient* depthOut,
NvFlowTextureTransient* colorOut
)
{
auto ptr = cast(renderer);
using namespace NvFlowMath;
NvFlowFloat4x4 projectionInv = matrixInverse(*projection);
NvFlowFloat4x4 viewInv = matrixInverse(*view);
FrustumRays frustumRays = {};
computeFrustumRays(&frustumRays, viewInv, projectionInv);
NvFlowUint64 numBytesSpherePositions = (params->numSpheres + 1u) * sizeof(NvFlowFloat4);
auto mappedSpherePos = (NvFlowFloat4*)NvFlowUploadBuffer_map(context, &ptr->spherePositionBuffer, numBytesSpherePositions);
for (NvFlowUint idx = 0u; idx < params->numSpheres; idx++)
{
mappedSpherePos[idx] = params->spherePositionRadius[idx];
}
NvFlowBufferTransient* spherePositionRadiusTransient = NvFlowUploadBuffer_unmap(context, &ptr->spherePositionBuffer);
auto mapped = (ShapeRendererParams*)NvFlowUploadBuffer_map(context, &ptr->constantBuffer, sizeof(ShapeRendererParams));
mapped->projection = NvFlowMath::matrixTranspose(*projection);
mapped->view = NvFlowMath::matrixTranspose(*view);
mapped->projectionInv = NvFlowMath::matrixTranspose(projectionInv);
mapped->viewInv = NvFlowMath::matrixTranspose(viewInv);
mapped->rayDir00 = frustumRays.rayDir00;
mapped->rayDir10 = frustumRays.rayDir10;
mapped->rayDir01 = frustumRays.rayDir01;
mapped->rayDir11 = frustumRays.rayDir11;
mapped->rayOrigin00 = frustumRays.rayOrigin00;
mapped->rayOrigin10 = frustumRays.rayOrigin10;
mapped->rayOrigin01 = frustumRays.rayOrigin01;
mapped->rayOrigin11 = frustumRays.rayOrigin11;
mapped->width = float(textureWidth);
mapped->height = float(textureHeight);
mapped->widthInv = 1.f / float(textureWidth);
mapped->heightInv = 1.f / float(textureHeight);
mapped->numSpheres = params->numSpheres;
mapped->clearDepth = 1.f - frustumRays.nearZ;
mapped->isReverseZ = frustumRays.nearZ > 0.5f ? 1u : 0u;
mapped->pad3 = 0u;
mapped->clearColor = NvFlowFloat4{ 0.f, 0.f, 0.f, 1.f };
NvFlowBufferTransient* paramsInTransient = NvFlowUploadBuffer_unmap(context, &ptr->constantBuffer);
// render
{
NvFlowUint3 gridDim = {
(textureWidth + 7u) / 8u,
(textureHeight + 7u) / 8u,
1u
};
ShapeCS_PassParams passParams = {};
passParams.paramsIn = paramsInTransient;
passParams.spherePositionRadiusIn = spherePositionRadiusTransient;
passParams.depthOut = depthOut;
passParams.colorOut = colorOut;
ShapeCS_addPassCompute(context, &ptr->shapeCS, gridDim, &passParams);
}
}
}
NvFlowShapeRendererInterface* NvFlowGetShapeRendererInterface()
{
using namespace NvFlowShapeRendererDefault;
static NvFlowShapeRendererInterface iface = { NV_FLOW_REFLECT_INTERFACE_INIT(NvFlowShapeRendererInterface) };
iface.create = create;
iface.destroy = destroy;
iface.render = render;
return &iface;
} |
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/FrameCapture.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include "FrameCapture.h"
#include "NvFlowDynamicBuffer.h"
#include <stdio.h>
#if !defined(_WIN32)
NV_FLOW_INLINE void fopen_s(FILE** streamptr, const char* filename, const char* mode)
{
*streamptr = fopen(filename, mode);
}
#endif
namespace NvFlowFrameCaptureDefault
{
struct BitmapHeader
{
char headerField0, headerField1;
unsigned int size;
unsigned short reserved1;
unsigned short reserved2;
unsigned int offset;
unsigned int headerSize;
unsigned int width;
unsigned int height;
unsigned short colorPlanes;
unsigned short bitsPerPixel;
unsigned int compressionMethod;
unsigned int imageSize;
unsigned int hRes;
unsigned int vRes;
unsigned int numColors;
unsigned int numImportantColors;
};
struct FrameCaptureBuffer
{
NvFlowBool32 isActive;
NvFlowBuffer* buffer = nullptr;
NvFlowUint64 bufferSize = 0llu;
NvFlowUint64 rowPitch = 0llu;
NvFlowUint width;
NvFlowUint height;
NvFlowUint64 completedFence = 0llu;
};
struct FrameCapture
{
NvFlowContextInterface contextInterface = {};
NvFlowArray<FrameCaptureBuffer> buffers;
NvFlowUint64 captureFrameID = 0llu;
};
NV_FLOW_CAST_PAIR(NvFlowFrameCapture, FrameCapture)
NvFlowFrameCapture* create(NvFlowContextInterface* contextInterface, NvFlowContext* context)
{
auto ptr = new FrameCapture();
NvFlowContextInterface_duplicate(&ptr->contextInterface, contextInterface);
return cast(ptr);
}
void destroy(NvFlowContext* context, NvFlowFrameCapture* renderer)
{
auto ptr = cast(renderer);
for (NvFlowUint idx = 0u; idx < ptr->buffers.size; idx++)
{
ptr->contextInterface.destroyBuffer(context, ptr->buffers[idx].buffer);
ptr->buffers[idx].buffer = nullptr;
}
delete ptr;
}
void capture(NvFlowContext* context, NvFlowFrameCapture* frameCapture, NvFlowUint width, NvFlowUint height, NvFlowTextureTransient* texture)
{
auto ptr = cast(frameCapture);
// Note: assume bgra8
NvFlowUint rowPitch = width * sizeof(NvFlowUint);
rowPitch = 256u * ((rowPitch + 255u) / 256u);
NvFlowUint64 minBufferSize = rowPitch * height;
FrameCaptureBuffer* captureBuffer = nullptr;
for (NvFlowUint idx = 0u; idx < ptr->buffers.size; idx++)
{
if (!ptr->buffers[idx].isActive)
{
captureBuffer = &ptr->buffers[idx];
break;
}
}
if (!captureBuffer)
{
captureBuffer = &ptr->buffers[ptr->buffers.allocateBack()];
}
if (captureBuffer->bufferSize < minBufferSize)
{
if (captureBuffer->buffer)
{
ptr->contextInterface.destroyBuffer(context, captureBuffer->buffer);
captureBuffer->buffer = nullptr;
captureBuffer->bufferSize = 0llu;
}
NvFlowBufferDesc bufDesc = {};
bufDesc.format = eNvFlowFormat_unknown;
bufDesc.usageFlags = eNvFlowBufferUsage_bufferCopyDst;
bufDesc.structureStride = 0u;
bufDesc.sizeInBytes = 65536u;
while (bufDesc.sizeInBytes < minBufferSize)
{
bufDesc.sizeInBytes *= 2u;
}
captureBuffer->bufferSize = bufDesc.sizeInBytes;
captureBuffer->buffer = ptr->contextInterface.createBuffer(context, eNvFlowMemoryType_readback, &bufDesc);
}
captureBuffer->rowPitch = rowPitch;
captureBuffer->width = width;
captureBuffer->height = height;
NvFlowPassCopyTextureToBufferParams copyParams = {};
copyParams.bufferOffset = 0llu;
copyParams.bufferRowPitch = rowPitch;
copyParams.bufferDepthPitch = height * rowPitch;
copyParams.textureMipLevel = 0;
copyParams.textureOffset = NvFlowUint3{ 0u, 0u, 0u };
copyParams.textureExtent = NvFlowUint3{ width, height, 1u };
copyParams.src = texture;
copyParams.dst = ptr->contextInterface.registerBufferAsTransient(context, captureBuffer->buffer);
copyParams.debugLabel = "FrameCapture";
ptr->contextInterface.addPassCopyTextureToBuffer(context, ©Params);
captureBuffer->isActive = NV_FLOW_TRUE;
captureBuffer->completedFence = ptr->contextInterface.getCurrentFrame(context);
}
void update(NvFlowContext* context, NvFlowFrameCapture* frameCapture)
{
auto ptr = cast(frameCapture);
NvFlowUint64 minFence = ~0llu;
FrameCaptureBuffer* captureBuffer = nullptr;
for (NvFlowUint idx = 0u; idx < ptr->buffers.size; idx++)
{
if (ptr->buffers[idx].isActive)
{
if (ptr->buffers[idx].completedFence < minFence)
{
minFence = ptr->buffers[idx].completedFence;
captureBuffer = &ptr->buffers[idx];
}
}
}
if (!captureBuffer)
{
return;
}
if (minFence > ptr->contextInterface.getLastFrameCompleted(context))
{
return;
}
NvFlowUint8* mappedData = (NvFlowUint8*)ptr->contextInterface.mapBuffer(context, captureBuffer->buffer);
char buf[80] = {};
snprintf(buf, 80, "capture%lld.bmp", ptr->captureFrameID);
FILE* file = nullptr;
fopen_s(&file, buf, "wb");
if (file)
{
BitmapHeader header = {};
const NvFlowUint bitsPerPixel = 32;
const NvFlowUint bytesPerPixel = bitsPerPixel / 8;
const NvFlowUint imagesize = captureBuffer->width * captureBuffer->height * bytesPerPixel;
header.headerField0 = 'B';
header.headerField1 = 'M';
header.size = 54 + imagesize;
header.reserved1 = 0;
header.reserved2 = 0;
header.offset = 54;
header.headerSize = 40;
header.width = captureBuffer->width;
header.height = captureBuffer->height;
header.colorPlanes = 1;
header.bitsPerPixel = bitsPerPixel;
header.compressionMethod = 0;
header.imageSize = imagesize;
header.hRes = 2000;
header.vRes = 2000;
header.numColors = 0;
header.numImportantColors = 0;
fwrite(&header.headerField0, 1, 1, file);
fwrite(&header.headerField1, 1, 1, file);
fwrite(&header.size, 4, 1, file);
fwrite(&header.reserved1, 2, 1, file);
fwrite(&header.reserved2, 2, 1, file);
fwrite(&header.offset, 4, 1, file);
fwrite(&header.headerSize, 4, 1, file);
fwrite(&header.width, 4, 1, file);
fwrite(&header.height, 4, 1, file);
fwrite(&header.colorPlanes, 2, 1, file);
fwrite(&header.bitsPerPixel, 2, 1, file);
fwrite(&header.compressionMethod, 4, 1, file);
fwrite(&header.imageSize, 4, 1, file);
fwrite(&header.hRes, 4, 1, file);
fwrite(&header.vRes, 4, 1, file);
fwrite(&header.numColors, 4, 1, file);
fwrite(&header.numImportantColors, 4, 1, file);
if (header.compressionMethod == 0)
{
for (NvFlowUint rowIdx = 0u; rowIdx < header.height; rowIdx++)
{
unsigned char* srcData = mappedData + (header.height - 1u - rowIdx) * captureBuffer->rowPitch;
fwrite(srcData, 1, header.width * bytesPerPixel, file);
}
}
fclose(file);
}
ptr->contextInterface.unmapBuffer(context, captureBuffer->buffer);
captureBuffer->isActive = NV_FLOW_FALSE;
captureBuffer->completedFence = ~0llu;
ptr->captureFrameID++;
}
}
NvFlowFrameCaptureInterface* NvFlowGetFrameCaptureInterface()
{
using namespace NvFlowFrameCaptureDefault;
static NvFlowFrameCaptureInterface iface = { NV_FLOW_REFLECT_INTERFACE_INIT(NvFlowFrameCaptureInterface) };
iface.create = create;
iface.destroy = destroy;
iface.capture = capture;
iface.update = update;
return &iface;
} |
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/Camera.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowTypes.h"
struct NvFlowCamera;
/// ********************* Camera *******************
enum NvFlowCameraAction
{
eNvFlowCameraAction_unknown = 0,
eNvFlowCameraAction_down = 1,
eNvFlowCameraAction_up = 2,
eNvFlowCameraAction_maxEnum = 0x7FFFFFFF
};
enum NvFlowCameraMouseButton
{
eNvFlowCameraMouseButton_unknown = 0,
eNvFlowCameraMouseButton_left = 1,
eNvFlowCameraMouseButton_middle = 2,
eNvFlowCameraMouseButton_right = 3,
eNvFlowCameraMouseButton_maxEnum = 0x7FFFFFFF
};
enum NvFlowCameraKey
{
eNvFlowCameraKey_unknown = 0,
eNvFlowCameraKey_up = 1,
eNvFlowCameraKey_down = 2,
eNvFlowCameraKey_left = 3,
eNvFlowCameraKey_right = 4,
eNvFlowCameraKey_maxEnum = 0x7FFFFFFF
};
struct NvFlowCameraState
{
NvFlowFloat3 position;
NvFlowFloat3 eyeDirection;
NvFlowFloat3 eyeUp;
float eyeDistanceFromPosition;
};
struct NvFlowCameraConfig
{
NvFlowBool32 isProjectionRH;
NvFlowBool32 isOrthographic;
NvFlowBool32 isReverseZ;
float nearPlane;
float farPlane;
float fovAngleY;
float orthographicY;
float panRate;
float tiltRate;
float zoomRate;
float keyTranslationRate;
};
NV_FLOW_API NvFlowCamera* NvFlowCameraCreate(int winw, int winh);
NV_FLOW_API void NvFlowCameraDestroy(NvFlowCamera* camera);
NV_FLOW_API void NvFlowCameraGetDefaultState(NvFlowCameraState* state, bool yUp);
NV_FLOW_API void NvFlowCameraGetDefaultConfig(NvFlowCameraConfig* config);
NV_FLOW_API void NvFlowCameraGetState(NvFlowCamera* camera, NvFlowCameraState* state);
NV_FLOW_API void NvFlowCameraSetState(NvFlowCamera* camera, const NvFlowCameraState* state);
NV_FLOW_API void NvFlowCameraGetConfig(NvFlowCamera* camera, NvFlowCameraConfig* config);
NV_FLOW_API void NvFlowCameraSetConfig(NvFlowCamera* camera, const NvFlowCameraConfig* config);
NV_FLOW_API void NvFlowCameraGetView(NvFlowCamera* camera, NvFlowFloat4x4* view);
NV_FLOW_API void NvFlowCameraGetProjection(NvFlowCamera* camera, NvFlowFloat4x4* projection, float aspectWidth, float aspectHeight);
NV_FLOW_API void NvFlowCameraMouseUpdate(NvFlowCamera* camera, NvFlowCameraMouseButton button, NvFlowCameraAction action, int mouseX, int mouseY, int winw, int winh);
NV_FLOW_API void NvFlowCameraKeyUpdate(NvFlowCamera* camera, NvFlowCameraKey key, NvFlowCameraAction action);
NV_FLOW_API void NvFlowCameraAnimationTick(NvFlowCamera* camera, float deltaTime); |
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/EditorImgui.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include "EditorCommon.h"
void setStyle_NvidiaDark()
{
ImGui::StyleColorsDark();
ImGuiStyle& s = ImGui::GetStyle();
s.FrameRounding = 4.0f;
// Settings
s.WindowPadding = ImVec2(8.0f, 8.0f);
s.PopupRounding = 4.0f;
s.FramePadding = ImVec2(8.0f, 4.0f);
s.ItemSpacing = ImVec2(6.0f, 6.0f);
s.ItemInnerSpacing = ImVec2(4.0f, 4.0f);
s.TouchExtraPadding = ImVec2(0.0f, 0.0f);
s.IndentSpacing = 21.0f;
s.ScrollbarSize = 16.0f;
s.GrabMinSize = 8.0f;
// BorderSize
s.WindowBorderSize = 1.0f;
s.ChildBorderSize = 1.0f;
s.PopupBorderSize = 1.0f;
s.FrameBorderSize = 0.0f;
s.TabBorderSize = 0.0f;
// Rounding
s.WindowRounding = 4.0f;
s.ChildRounding = 4.0f;
s.FrameRounding = 4.0f;
s.ScrollbarRounding = 4.0f;
s.GrabRounding = 4.0f;
s.TabRounding = 4.0f;
// Alignment
s.WindowTitleAlign = ImVec2(0.5f, 0.5f);
s.ButtonTextAlign = ImVec2(0.48f, 0.5f);
s.DisplaySafeAreaPadding = ImVec2(3.0f, 3.0f);
// Colors
s.Colors[::ImGuiCol_Text] = ImVec4(0.89f, 0.89f, 0.89f, 1.00f);
s.Colors[::ImGuiCol_Text] = ImVec4(0.89f, 0.89f, 0.89f, 1.00f);
s.Colors[::ImGuiCol_TextDisabled] = ImVec4(0.43f, 0.43f, 0.43f, 1.00f);
s.Colors[::ImGuiCol_WindowBg] = ImVec4(0.26f, 0.26f, 0.26f, 1.00f);
s.Colors[::ImGuiCol_ChildBg] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f);
s.Colors[::ImGuiCol_PopupBg] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f);
s.Colors[::ImGuiCol_Border] = ImVec4(0.29f, 0.29f, 0.29f, 1.00f);
s.Colors[::ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
s.Colors[::ImGuiCol_FrameBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
s.Colors[::ImGuiCol_FrameBgHovered] = ImVec4(0.29f, 0.29f, 0.29f, 1.00f);
s.Colors[::ImGuiCol_FrameBgActive] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
s.Colors[::ImGuiCol_TitleBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
s.Colors[::ImGuiCol_TitleBgActive] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f);
s.Colors[::ImGuiCol_TitleBgCollapsed] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f);
s.Colors[::ImGuiCol_MenuBarBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f);
s.Colors[::ImGuiCol_ScrollbarBg] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
s.Colors[::ImGuiCol_ScrollbarGrab] = ImVec4(0.51f, 0.50f, 0.50f, 1.00f);
s.Colors[::ImGuiCol_ScrollbarGrabHovered] = ImVec4(1.00f, 0.99f, 0.99f, 0.58f);
s.Colors[::ImGuiCol_ScrollbarGrabActive] = ImVec4(0.47f, 0.53f, 0.54f, 0.76f);
s.Colors[::ImGuiCol_CheckMark] = ImVec4(0.89f, 0.89f, 0.89f, 1.00f);
s.Colors[::ImGuiCol_SliderGrab] = ImVec4(0.59f, 0.59f, 0.59f, 1.00f);
s.Colors[::ImGuiCol_SliderGrabActive] = ImVec4(0.47f, 0.53f, 0.54f, 0.76f);
s.Colors[::ImGuiCol_Button] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
s.Colors[::ImGuiCol_ButtonHovered] = ImVec4(0.59f, 0.59f, 0.59f, 1.00f);
s.Colors[::ImGuiCol_ButtonActive] = ImVec4(0.47f, 0.53f, 0.54f, 0.76f);
s.Colors[::ImGuiCol_Header] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
s.Colors[::ImGuiCol_HeaderHovered] = ImVec4(0.22f, 0.22f, 0.22f, 1.00f);
s.Colors[::ImGuiCol_HeaderActive] = ImVec4(0.30f, 0.30f, 0.30f, 1.00f);
s.Colors[::ImGuiCol_Separator] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
s.Colors[::ImGuiCol_SeparatorHovered] = ImVec4(0.23f, 0.44f, 0.69f, 1.00f);
s.Colors[::ImGuiCol_SeparatorActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
s.Colors[::ImGuiCol_ResizeGrip] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
s.Colors[::ImGuiCol_ResizeGripHovered] = ImVec4(0.23f, 0.44f, 0.69f, 1.00f);
s.Colors[::ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
s.Colors[::ImGuiCol_Tab] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
s.Colors[::ImGuiCol_TabHovered] = ImVec4(0.6f, 0.6f, 0.6f, 0.58f);
s.Colors[::ImGuiCol_TabActive] = ImVec4(0.35f, 0.35f, 0.35f, 1.00f);
s.Colors[::ImGuiCol_TabUnfocused] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
s.Colors[::ImGuiCol_TabUnfocusedActive] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f);
//s.Colors[::ImGuiCol_DockingPreview] = ImVec4(0.26f, 0.59f, 0.98f, 0.70f);
//s.Colors[::ImGuiCol_DockingEmptyBg] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f);
s.Colors[::ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f);
s.Colors[::ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);
s.Colors[::ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
s.Colors[::ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
s.Colors[::ImGuiCol_TextSelectedBg] = ImVec4(0.97f, 0.97f, 0.97f, 0.19f);
s.Colors[::ImGuiCol_DragDropTarget] = ImVec4(0.38f, 0.62f, 0.80f, 1.0f);
s.Colors[::ImGuiCol_NavHighlight] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
s.Colors[::ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
s.Colors[::ImGuiCol_NavWindowingDimBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
s.Colors[::ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f);
//s.ScaleAllSizes(1.2f);
}
void editorImgui_init(EditorImgui* ptr, NvFlowContextInterface* contextInterface, NvFlowContext* context)
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
setStyle_NvidiaDark();
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;
unsigned char* pixels = nullptr;
int texWidth = 0;
int texHeight = 0;
io.Fonts->GetTexDataAsRGBA32(&pixels, &texWidth, &texHeight);
NvFlowImguiRendererInterface_duplicate(&ptr->imguiRendererInterface, NvFlowGetImguiRendererInterface());
ptr->imguiRenderer = ptr->imguiRendererInterface.create(contextInterface, context, pixels, texWidth, texHeight);
editorCompute_logPrint(eNvFlowLogLevel_info, "Initialized Imgui Renderer");
}
void editorValue(NvFlowUint8* data, const NvFlowReflectData reflectData, NvFlowReflectProcess_t processReflect, void* userdata)
{
/*if (reflectData.reflectHints & eNvFlowReflectHint_noEdit)
{
// NOP
}
else */if (reflectData.dataType->dataType == eNvFlowType_struct)
{
char buf[64];
buf[63] = '\0';
snprintf(buf, 64, "%s::%s", NvFlowReflectTrimPrefix(reflectData.dataType->structTypename), reflectData.name);
bool isVisible = ImGui::TreeNode(buf);
if (isVisible)
{
if (reflectData.dataType->childReflectDatas)
{
processReflect(data + reflectData.dataOffset, reflectData.dataType, userdata);
}
ImGui::TreePop();
}
}
else if (reflectData.dataType->dataType == eNvFlowType_int)
{
ImGui::SliderInt(reflectData.name, (int*)(data + reflectData.dataOffset), -10, 10);
}
else if (reflectData.dataType->dataType == eNvFlowType_int2)
{
ImGui::SliderInt2(reflectData.name, (int*)(data + reflectData.dataOffset), -10, 10);
}
else if (reflectData.dataType->dataType == eNvFlowType_int3)
{
ImGui::SliderInt3(reflectData.name, (int*)(data + reflectData.dataOffset), -10, 10);
}
else if (reflectData.dataType->dataType == eNvFlowType_int4)
{
ImGui::SliderInt4(reflectData.name, (int*)(data + reflectData.dataOffset), -10, 10);
}
else if (reflectData.dataType->dataType == eNvFlowType_uint)
{
ImGui::SliderInt(reflectData.name, (int*)(data + reflectData.dataOffset), 0, 20);
}
else if (reflectData.dataType->dataType == eNvFlowType_uint64)
{
ImGui::SliderInt(reflectData.name, (int*)(data + reflectData.dataOffset), 0, 20);
}
else if (reflectData.dataType->dataType == eNvFlowType_uint2)
{
ImGui::SliderInt2(reflectData.name, (int*)(data + reflectData.dataOffset), 0, 20);
}
else if (reflectData.dataType->dataType == eNvFlowType_uint3)
{
ImGui::SliderInt3(reflectData.name, (int*)(data + reflectData.dataOffset), 0, 20);
}
else if (reflectData.dataType->dataType == eNvFlowType_uint4)
{
ImGui::SliderInt4(reflectData.name, (int*)(data + reflectData.dataOffset), 0, 20);
}
else if (reflectData.dataType->dataType == eNvFlowType_float)
{
ImGui::SliderFloat(reflectData.name, (float*)(data + reflectData.dataOffset), -10.f, 10.f);
}
else if (reflectData.dataType->dataType == eNvFlowType_float2)
{
ImGui::SliderFloat2(reflectData.name, (float*)(data + reflectData.dataOffset), -10.f, 10.f);
}
else if (reflectData.dataType->dataType == eNvFlowType_float3)
{
ImGui::SliderFloat3(reflectData.name, (float*)(data + reflectData.dataOffset), -10.f, 10.f);
}
else if (reflectData.dataType->dataType == eNvFlowType_float4)
{
ImGui::SliderFloat4(reflectData.name, (float*)(data + reflectData.dataOffset), -10.f, 10.f);
}
else if (reflectData.dataType->dataType == eNvFlowType_float4x4)
{
bool isVisible = ImGui::TreeNode(reflectData.name);
if (isVisible)
{
NvFlowFloat4x4* pMat = (NvFlowFloat4x4*)(data + reflectData.dataOffset);
ImGui::SliderFloat4("x", &pMat->x.x, -10.f, 10.f);
ImGui::SliderFloat4("y", &pMat->y.x, -10.f, 10.f);
ImGui::SliderFloat4("z", &pMat->z.x, -10.f, 10.f);
ImGui::SliderFloat4("w", &pMat->w.x, -10.f, 10.f);
ImGui::TreePop();
}
}
else if (reflectData.dataType->dataType == eNvFlowType_bool32)
{
ImGui::Checkbox(reflectData.name, (bool*)(data + reflectData.dataOffset));
}
else
{
ImGui::Text("%s", reflectData.name);
}
}
void editorProcess(NvFlowUint8* data, const NvFlowReflectDataType* dataType, void* userdata)
{
for (NvFlowUint idx = 0; idx < dataType->childReflectDataCount; idx++)
{
const NvFlowReflectData reflectData = dataType->childReflectDatas[idx];
if (reflectData.reflectMode & eNvFlowReflectMode_array)
{
bool isVisible = ImGui::TreeNode(reflectData.name);
if (isVisible)
{
NvFlowUint64 numElements = *(NvFlowUint64*)(data + reflectData.arraySizeOffset);
unsigned char* arrayData = *(unsigned char**)(data + reflectData.dataOffset);
char buf[16];
buf[15] = '\0';
for (NvFlowUint arrayIdx = 0u; arrayIdx < numElements; arrayIdx++)
{
snprintf(buf, 16, "%d", arrayIdx);
NvFlowReflectData reflectDataAtIndex = reflectData;
reflectDataAtIndex.name = buf;
reflectDataAtIndex.dataOffset = arrayIdx * reflectData.dataType->elementSize;
editorValue(arrayData, reflectDataAtIndex, editorProcess, userdata);
}
ImGui::TreePop();
}
}
else
{
editorValue(data, reflectData, editorProcess, userdata);
}
}
};
void editorImgui_update(
EditorImgui* ptr,
App* app,
EditorCompute* compute,
EditorFlow* flow
)
{
if (app->overlayEnabled)
{
//static bool show_demo_window = true;
//ImGui::ShowDemoWindow(&show_demo_window);
float overlayHeight = 512.f;
float overlayWidth = 384.f;
ImGui::SetNextWindowPos(ImVec2(16, 16), ImGuiCond_Always);
ImGui::SetNextWindowSize(ImVec2(overlayWidth, overlayHeight), ImGuiCond_Always);
ImGui::Begin("Overlay");
ImGui::Text("Active Blocks: %d\n", flow->activeBlockCount);
ImGui::Text("Active Cells: %d\n", flow->activeBlockCount * flow->activeBlockDim.x * flow->activeBlockDim.y * flow->activeBlockDim.z);
if (flow->activeBlockCountIsosurface > 0u)
{
ImGui::Text("Active Isosurface Blocks: %d\n", flow->activeBlockCountIsosurface);
ImGui::Text("Active Isosurface Cells: %d\n", flow->activeBlockCountIsosurface * flow->activeBlockDimIsosurface.x * flow->activeBlockDimIsosurface.y * flow->activeBlockDimIsosurface.z);
}
for (NvFlowUint statIdx = 0u; statIdx < app->compute.statOut_label.size; statIdx++)
{
ImGui::Text("%s cpu(%03f) gpu(%03f)\n", app->compute.statOut_label[statIdx], app->compute.statOut_cpu[statIdx], app->compute.statOut_gpu[statIdx]);
}
ImGui::End();
}
if (app->editorEnabled)
{
float editorHeight = 512.f;
float editorWidth = 384.f;
float border = 16.f;
ImGui::SetNextWindowPos(ImVec2(((float)app->windowWidth) - editorWidth - border, border), ImGuiCond_Once);
ImGui::SetNextWindowSize(ImVec2(editorWidth, editorHeight), ImGuiCond_Once);
ImGui::Begin("Editor");
if (ImGui::TreeNode("Settings"))
{
if (ImGui::Button(app->isPaused ? "Play" : "Pause"))
{
app->isPaused ^= NV_FLOW_TRUE;
}
ImGui::DragInt("maxLocations", (int*)&flow->targetMaxLocations, 1.f, 0, 300000);
ImGui::Checkbox("Profile Window", (bool*)(&app->overlayEnabled));
ImGui::Checkbox("Capture Enabled", (bool*)(&app->captureEnabled));
ImGui::Checkbox("Sphere Enabled", (bool*)(&app->sphereEnabled));
ImGui::TreePop();
}
if (ImGui::TreeNode("Stage Selection"))
{
for (NvFlowUint64 idx = 0u; idx < flow->stages.size; idx++)
{
bool isActive = flow->currentStage == flow->stages[idx];
if (ImGui::RadioButton(flow->stages[idx]->stageName, isActive))
{
flow->targetStageIdx = idx;
}
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Stage Properties"))
{
flow->abstractParamsList.size = 0u;
NvFlowUint64 abstractParamsListCount = 0u;
flow->gridParamsSet.enumerateActiveInstances(nullptr, &abstractParamsListCount);
flow->abstractParamsList.reserve(abstractParamsListCount);
flow->abstractParamsList.size = abstractParamsListCount;
flow->gridParamsSet.enumerateActiveInstances(flow->abstractParamsList.data, &abstractParamsListCount);
flow->abstractParamsList.size = abstractParamsListCount;
NvFlowUint64 stagingVersion = 0llu;
NvFlowUint64 minActiveVersion = 0llu;
compute->loader.gridParamsInterface.getVersion(flow->gridParams, &stagingVersion, &minActiveVersion);
for (NvFlowUint idx = 0u; idx < flow->abstractParamsList.size; idx++)
{
char buf[64];
buf[63] = '\0';
snprintf(buf, 64, "%s::%s", flow->abstractParamsList[idx]->displayTypename.get(), flow->abstractParamsList[idx]->name.get());
bool isVisible = ImGui::TreeNode(buf);
if (isVisible)
{
flow->abstractParamsList[idx]->process(stagingVersion, editorProcess, ptr);
ImGui::TreePop();
}
}
ImGui::TreePop();
}
ImGui::End();
}
}
void editorImgui_render(
EditorImgui* ptr,
NvFlowContext* context,
NvFlowTextureTransient* colorIn,
NvFlowTextureTransient* colorOut,
NvFlowUint windowWidth,
NvFlowUint windowHeight
)
{
ImGui::Render();
auto drawData = ImGui::GetDrawData();
ptr->imguiRendererInterface.render(context, ptr->imguiRenderer, drawData, windowWidth, windowHeight, colorIn, colorOut);
}
void editorImgui_destroy(EditorImgui* ptr, NvFlowContext* context)
{
ptr->imguiRendererInterface.destroy(context, ptr->imguiRenderer);
ImGui::DestroyContext();
editorCompute_logPrint(eNvFlowLogLevel_info, "Destroyed Imgui Renderer");
}
|
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/EditorFlowStages.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include "EditorCommon.h"
void editorFlowStage_applyOverrides(EditorFlow* ptr, float cellsizeOverride, NvFlowBool32 smallBlocksOverride)
{
// by default, override colorScale
editorFlow_setAttributeFloat(ptr, "offscreen/colormap", "colorScale", 1.f);
if (cellsizeOverride > 0.f)
{
editorFlow_setAttributeFloat(ptr, "simulate", "densityCellSize", cellsizeOverride);
}
if (smallBlocksOverride)
{
editorFlow_setAttributeBool(ptr, "simulate", "enableSmallBlocks", NV_FLOW_TRUE);
}
}
void* editorFlowStage_sphere_init(EditorFlow* ptr)
{
editorFlow_definePrim(ptr, "FlowSimulate", "simulate", "simulate");
editorFlow_definePrim(ptr, "FlowOffscreen", "offscreen", "offscreen");
editorFlow_definePrim(ptr, "FlowRender", "render", "render");
editorFlow_definePrim(ptr, "FlowEmitterSphere", "emitter", "emitter");
return nullptr;
}
static const EditorFlowStage editorFlowStage_sphere = { "sphere", editorFlowStage_sphere_init, nullptr, nullptr };
void* editorFlowStage_box_init(EditorFlow* ptr)
{
editorFlow_definePrim(ptr, "FlowSimulate", "simulate", "simulate");
editorFlow_definePrim(ptr, "FlowOffscreen", "offscreen", "offscreen");
editorFlow_definePrim(ptr, "FlowRender", "render", "render");
editorFlow_definePrim(ptr, "FlowEmitterBox", "emitter", "emitter");
return nullptr;
}
static const EditorFlowStage editorFlowStage_box = { "box", editorFlowStage_box_init, nullptr, nullptr };
void* editorFlowStage_point_init(EditorFlow* ptr)
{
editorFlow_definePrim(ptr, "FlowSimulate", "simulate", "simulate");
editorFlow_definePrim(ptr, "FlowOffscreen", "offscreen", "offscreen");
editorFlow_definePrim(ptr, "FlowRender", "render", "render");
editorFlow_definePrim(ptr, "FlowEmitterPoint", "emitter", "emitter");
editorFlow_setAttributeFloat(ptr, "simulate/advection/velocity", "secondOrderBlendFactor", 0.5f);
editorFlow_setAttributeFloat(ptr, "simulate/advection/temperature", "secondOrderBlendFactor", 0.5f);
editorFlow_setAttributeFloat(ptr, "simulate/advection/fuel", "secondOrderBlendFactor", 0.5f);
editorFlow_setAttributeFloat(ptr, "simulate/advection/smoke", "secondOrderBlendFactor", 0.5f);
editorFlow_setAttributeBool(ptr, "offscreen/debugVolume", "enableSpeedAsTemperature", NV_FLOW_TRUE);
editorFlow_setAttributeFloat(ptr, "render/rayMarch", "attenuation", 0.5f);
editorFlow_setAttributeBool(ptr, "render/rayMarch", "enableRawMode", NV_FLOW_TRUE);
return nullptr;
}
void editorFlowStage_point_update(EditorFlow* ptr, void* userdata, double time, float deltaTime)
{
float timef = (float)time;
static NvFlowFloat3 positions[64u];
for (int j = 0; j < 4; j++)
{
for (int i = 0; i < 16; i++)
{
positions[j * 16 + i].x = 20.f * (float(j) + 1.f) * cosf(6.28f * (float(i) + 0.33f * float(j) + 0.5f + timef) / 16.f);
positions[j * 16 + i].y = 20.f * (float(j) + 1.f) * sinf(6.28f * (float(i) + 0.33f * float(j) + 0.5f + timef) / 16.f);
positions[j * 16 + i].z = 0.f;
}
}
editorFlow_setAttributeFloat3Array(ptr, "emitter", "pointPositions", positions, 64u);
}
static const EditorFlowStage editorFlowStage_point = { "point", editorFlowStage_point_init, editorFlowStage_point_update, nullptr };
void* editorFlowStage_mesh_init(EditorFlow* ptr)
{
editorFlow_definePrim(ptr, "FlowSimulate", "simulate", "simulate");
editorFlow_definePrim(ptr, "FlowOffscreen", "offscreen", "offscreen");
editorFlow_definePrim(ptr, "FlowRender", "render", "render");
editorFlow_definePrim(ptr, "FlowEmitterMesh", "emitter", "emitter");
static const NvFlowUint instanceCount = 1u; // 768u;
static const int faceCountCount = 6;
static const int faceIndexCount = 24;
static const int positionCount = 8;
/*static*/ int faceCounts[instanceCount * faceCountCount] = { 4, 4, 4, 4, 4, 4 };
/*static */int faceIndices[instanceCount * faceIndexCount] = { 0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5 };
/*static */const NvFlowFloat3 positions[positionCount] = {
{-5.f, -5.f, -5.f}, {5.f, -5.f, -5.f}, {-5.f, -5.f, 5.f}, {5.f, -5.f, 5.f}, {-5.f, 5.f, -5.f}, {5.f, 5.f, -5.f}, {5.f, 5.f, 5.f}, {-5.f, 5.f, 5.f}
};
for (int instance = 1; instance < instanceCount; instance++)
{
for (int faceCountIdx = 0u; faceCountIdx < faceCountCount; faceCountIdx++)
{
faceCounts[faceCountCount * instance + faceCountIdx] = faceCounts[faceCountIdx];
}
for (int faceIndicesIdx = 0u; faceIndicesIdx < faceIndexCount; faceIndicesIdx++)
{
faceIndices[faceIndexCount * instance + faceIndicesIdx] = faceIndices[faceIndicesIdx];
}
}
editorFlow_setAttributeIntArray(ptr, "emitter", "meshFaceVertexCounts", faceCounts, instanceCount * faceCountCount);
editorFlow_setAttributeIntArray(ptr, "emitter", "meshFaceVertexIndices", faceIndices, instanceCount * faceIndexCount);
editorFlow_setAttributeFloat3Array(ptr, "emitter", "meshPositions", positions, positionCount);
return nullptr;
}
static const EditorFlowStage editorFlowStage_mesh = { "mesh", editorFlowStage_mesh_init, nullptr, nullptr };
void* editorFlowStage_texture_init(EditorFlow* ptr)
{
editorFlow_definePrim(ptr, "FlowSimulate", "simulate", "simulate");
editorFlow_definePrim(ptr, "FlowOffscreen", "offscreen", "offscreen");
editorFlow_definePrim(ptr, "FlowRender", "render", "render");
static const NvFlowUint textureDim = 256u;
static float velocities[textureDim][textureDim][textureDim][3];
for (NvFlowUint k = 0; k < textureDim; k++)
{
for (NvFlowUint j = 0; j < textureDim; j++)
{
for (NvFlowUint i = 0; i < textureDim; i++)
{
float u = (float(i) + 0.5f) / float(textureDim);
float v = (float(j) + 0.5f) / float(textureDim);
float vx = 200.f * v - 100.f;
float vy = -200.f * u + 100.f;
velocities[k][j][i][0] = vx;
velocities[k][j][i][1] = vy;
velocities[k][j][i][2] = 20.f;
}
}
}
NvFlowFloat3* texVel = (NvFlowFloat3*)&velocities[0][0][0][0];
NvFlowUint64 texVelCount = textureDim * textureDim * textureDim;
editorFlow_definePrim(ptr, "FlowEmitterTexture", "emitter", "emitter");
editorFlow_setAttributeFloat3(ptr, "emitter", "halfSize", NvFlowFloat3{ 50.f, 50.f, 50.f });
editorFlow_setAttributeFloat(ptr, "emitter", "coupleRateVelocity", 50.f);
editorFlow_setAttributeBool(ptr, "emitter", "applyPostPressure", NV_FLOW_TRUE);
editorFlow_setAttributeFloat(ptr, "emitter", "coupleRateTemperature", 0.f);
editorFlow_setAttributeFloat(ptr, "emitter", "coupleRateFuel", 0.f);
editorFlow_setAttributeFloat(ptr, "emitter", "coupleRateBurn", 0.f);
editorFlow_setAttributeFloat(ptr, "emitter", "coupleRateSmoke", 0.f);
editorFlow_setAttributeFloat3(ptr, "emitter", "velocity", NvFlowFloat3{ 0.f, 0.f, 0.f });
editorFlow_setAttributeUint(ptr, "emitter", "textureWidth", textureDim);
editorFlow_setAttributeUint(ptr, "emitter", "textureHeight", textureDim);
editorFlow_setAttributeUint(ptr, "emitter", "textureDepth", textureDim);
editorFlow_setAttributeFloat3Array(ptr, "emitter", "textureVelocities", texVel, texVelCount);
editorFlow_definePrim(ptr, "FlowEmitterSphere", "emitterSphere", "emitterSphere");
editorFlow_setAttributeFloat3(ptr, "emitterSphere", "position", NvFlowFloat3{ 10.f, 0.f, -40.f });
editorFlow_setAttributeFloat(ptr, "emitterSphere", "radius", 5.f);
editorFlow_setAttributeFloat(ptr, "emitterSphere", "coupleRateTemperature", 10.f);
editorFlow_setAttributeFloat(ptr, "emitterSphere", "coupleRateFuel", 10.f);
return nullptr;
}
static const EditorFlowStage editorFlowStage_texture = { "texture", editorFlowStage_texture_init, nullptr, nullptr };
void* editorFlowStage_nanovdb_init(EditorFlow* ptr)
{
editorFlow_definePrim(ptr, "FlowSimulate", "simulate", "simulate");
editorFlow_definePrim(ptr, "FlowOffscreen", "offscreen", "offscreen");
editorFlow_definePrim(ptr, "FlowRender", "render", "render");
editorFlow_definePrim(ptr, "FlowEmitterNanoVdb", "emitter", "emitter");
return nullptr;
}
static const EditorFlowStage editorFlowStage_nanovdb = { "nanovdb", editorFlowStage_nanovdb_init, nullptr, nullptr };
struct EditorFlowStageIsosurface
{
NvFlowArray<NvFlowFloat3> positionFloat3;
NvFlowArray<NvFlowFloat4> anisotropyE1;
NvFlowArray<NvFlowFloat4> anisotropyE2;
NvFlowArray<NvFlowFloat4> anisotropyE3;
};
void* editorFlowStage_isosurface_init(EditorFlow* ptr)
{
auto* state = new EditorFlowStageIsosurface();
editorFlow_definePrim(ptr, "FlowIsosurface", "isosurface", "isosurface");
for (NvFlowUint idx = 0u; idx < 128u; idx++)
{
state->positionFloat3.pushBack(NvFlowFloat3{ 0.f, 0.f, 0.f });
state->anisotropyE1.pushBack(NvFlowFloat4{ 1.f, 0.f, 0.f, 4.f });
state->anisotropyE2.pushBack(NvFlowFloat4{ 0.f, 1.f, 0.f, 4.f });
state->anisotropyE3.pushBack(NvFlowFloat4{ 0.f, 0.f, 1.f, 4.f });
}
editorFlow_setAttributeFloat3Array(ptr, "isosurface/ellipsoidRaster", "positionFloat3s", state->positionFloat3.data, state->positionFloat3.size);
editorFlow_setAttributeFloat4Array(ptr, "isosurface/ellipsoidRaster", "anisotropyE1s", state->anisotropyE1.data, state->anisotropyE1.size);
editorFlow_setAttributeFloat4Array(ptr, "isosurface/ellipsoidRaster", "anisotropyE2s", state->anisotropyE2.data, state->anisotropyE2.size);
editorFlow_setAttributeFloat4Array(ptr, "isosurface/ellipsoidRaster", "anisotropyE3s", state->anisotropyE3.data, state->anisotropyE3.size);
return state;
}
void editorFlowStage_isosurface_update(EditorFlow* ptr, void* userdata, double time, float deltaTime)
{
auto* state = (EditorFlowStageIsosurface*)userdata;
// loop at 4 seconds
double timeScaled = 0.25f * time;
float timeLooped = 4.f * (float)(timeScaled - floor(timeScaled));
float animT = 4.f * timeLooped;
for (NvFlowUint idx = 0u; idx < state->positionFloat3.size; idx++)
{
float theta = 6.28f * float(idx) / float(state->positionFloat3.size);
state->positionFloat3[idx].x = 4.f * cosf(theta + 0.1f * animT) * animT;
state->positionFloat3[idx].y = 4.f * sinf(theta + 0.1f * animT) * animT;
state->positionFloat3[idx].z = -32.f * (1.f / 64.f) * (animT - 8.f) * (animT - 8.f) + 32.f;
}
editorFlow_setAttributeFloat3Array(ptr, "isosurface/ellipsoidRaster", "positionFloat3s", state->positionFloat3.data, state->positionFloat3.size);
}
void editorFlowStage_isosurface_destroy(EditorFlow* ptr, void* userdata)
{
auto* state = (EditorFlowStageIsosurface*)userdata;
delete state;
}
static const EditorFlowStage editorFlowStage_isosurface = { "isosurface", editorFlowStage_isosurface_init, editorFlowStage_isosurface_update, editorFlowStage_isosurface_destroy };
void* editorFlowStage_init_manySpheres(EditorFlow* ptr)
{
editorFlow_definePrim(ptr, "FlowSimulate", "simulate", "simulate");
editorFlow_definePrim(ptr, "FlowOffscreen", "offscreen", "offscreen");
editorFlow_definePrim(ptr, "FlowRender", "render", "render");
for (int j = 0; j < 4; j++)
{
for (int i = 0; i < 16; i++)
{
char name[80u];
snprintf(name, 80u, "emitter_%d_%d", j, i);
NvFlowFloat3 pos = {};
pos.x = 20.f * (float(j) + 1.f) * cosf(6.28f * (float(i) + 0.33f * float(j) + 0.5f) / 16.f);
pos.y = 20.f * (float(j) + 1.f) * sinf(6.28f * (float(i) + 0.33f * float(j) + 0.5f) / 16.f);
pos.z = 0.f;
editorFlow_definePrim(ptr, "FlowEmitterSphere", name, name);
editorFlow_setAttributeFloat3(ptr, name, "position", pos);
}
}
return nullptr;
}
static const EditorFlowStage editorFlowStage_manySpheres = { "manySpheres", editorFlowStage_init_manySpheres, nullptr, nullptr };
static const EditorFlowStage* gEditorFlowStage_builtinStages[] = {
&editorFlowStage_sphere,
&editorFlowStage_box,
&editorFlowStage_point,
&editorFlowStage_mesh,
&editorFlowStage_texture,
&editorFlowStage_nanovdb,
//&editorFlowStage_isosurface,
&editorFlowStage_manySpheres
};
void editorFlowStage_getBuiltinStages(const EditorFlowStage*** pStages, NvFlowUint64* pStageCount)
{
*pStages = gEditorFlowStage_builtinStages;
*pStageCount = sizeof(gEditorFlowStage_builtinStages) / sizeof(EditorFlowStage*);
}
|
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/Camera.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include "Camera.h"
#include "NvFlowMath.h"
struct NvFlowCamera
{
// Settings
NvFlowCameraConfig config = {};
// Camera state
NvFlowCameraState state = {};
// Mouse state
int mouseXprev = 0;
int mouseYprev = 0;
NvFlowBool32 rotationActive = false;
NvFlowBool32 zoomActive = false;
NvFlowBool32 translateActive = false;
NvFlowUint keyTranslateActiveMask = 0u;
};
void NvFlowCamera_computeRotationBasis(NvFlowCamera* ptr, NvFlowFloat4* pXAxis, NvFlowFloat4* pYAxis, NvFlowFloat4* pZAxis)
{
using namespace NvFlowMath;
NvFlowFloat4 zAxis = vector3Normalize(make_float4(ptr->state.eyeDirection, 0.f));
// RH Z is negative going into screen, so reverse eyeDirectionVector, after building basis
if (ptr->config.isProjectionRH)
{
zAxis.x = -zAxis.x;
zAxis.y = -zAxis.y;
zAxis.z = -zAxis.z;
}
NvFlowFloat4 yAxis = make_float4(ptr->state.eyeUp, 0.f);
// force yAxis to orthogonal
yAxis = vector3Normalize(yAxis - vector3Dot(zAxis, yAxis) * zAxis);
// generate third basis vector
NvFlowFloat4 xAxis = vector3Cross(yAxis, zAxis);
if (pXAxis)
{
*pXAxis = xAxis;
}
if (pYAxis)
{
*pYAxis = yAxis;
}
if (pZAxis)
{
*pZAxis = zAxis;
}
}
NvFlowCamera* NvFlowCameraCreate(int winw, int winh)
{
auto ptr = new NvFlowCamera();
NvFlowCameraGetDefaultState(&ptr->state, false);
NvFlowCameraGetDefaultConfig(&ptr->config);
return ptr;
}
void NvFlowCameraDestroy(NvFlowCamera* ptr)
{
delete ptr;
}
void NvFlowCameraGetDefaultState(NvFlowCameraState* ptr, bool yUp)
{
ptr->position = { 0.f, 0.f, 0.f };
if (yUp)
{
ptr->eyeDirection = { 0.f, 0.f, 1.f };
ptr->eyeUp = { 0.f, 1.f, 0.f };
}
else
{
ptr->eyeDirection = { 0.f, 1.f, 0.f };
ptr->eyeUp = { 0.f, 0.f, 1.f };
}
ptr->eyeDistanceFromPosition = -700.f;
}
void NvFlowCameraGetDefaultConfig(NvFlowCameraConfig* ptr)
{
using namespace NvFlowMath;
ptr->isProjectionRH = NV_FLOW_TRUE;
ptr->isOrthographic = NV_FLOW_FALSE;
ptr->isReverseZ = NV_FLOW_TRUE;
ptr->nearPlane = 0.1f;
ptr->farPlane = INFINITY;
ptr->fovAngleY = pi / 4.f;
ptr->orthographicY = 500.f;
ptr->panRate = 1.f;
ptr->tiltRate = 1.f;
ptr->zoomRate = 1.f;
ptr->keyTranslationRate = 800.f;
}
void NvFlowCameraGetState(NvFlowCamera* ptr, NvFlowCameraState* state)
{
*state = ptr->state;
}
void NvFlowCameraSetState(NvFlowCamera* ptr, const NvFlowCameraState* state)
{
ptr->state = *state;
}
void NvFlowCameraGetConfig(NvFlowCamera* ptr, NvFlowCameraConfig* config)
{
*config = ptr->config;
}
void NvFlowCameraSetConfig(NvFlowCamera* ptr, const NvFlowCameraConfig* config)
{
ptr->config = *config;
}
void NvFlowCameraGetView(NvFlowCamera* ptr, NvFlowFloat4x4* viewMatrix)
{
using namespace NvFlowMath;
auto state = &ptr->state;
float eyeDistanceWithDepth = state->eyeDistanceFromPosition;
NvFlowFloat3 eyePosition = state->position;
eyePosition.x -= state->eyeDirection.x * state->eyeDistanceFromPosition;
eyePosition.y -= state->eyeDirection.y * state->eyeDistanceFromPosition;
eyePosition.z -= state->eyeDirection.z * state->eyeDistanceFromPosition;
NvFlowFloat4x4 translate = matrixTranslation(eyePosition.x, eyePosition.y, eyePosition.z);
// derive rotation from eyeDirection, eyeUp vectors
NvFlowFloat4x4 rotation = {};
{
NvFlowFloat4 zAxis = {};
NvFlowFloat4 xAxis = {};
NvFlowFloat4 yAxis = {};
NvFlowCamera_computeRotationBasis(ptr, &xAxis, &yAxis, &zAxis);
rotation = NvFlowFloat4x4{
xAxis.x, yAxis.x, zAxis.x, 0.f,
xAxis.y, yAxis.y, zAxis.y, 0.f,
xAxis.z, yAxis.z, zAxis.z, 0.f,
0.f, 0.f, 0.f, 1.f
};
}
NvFlowFloat4x4 view = matrixMultiply(translate, rotation);
*viewMatrix = view;
}
void NvFlowCameraGetProjection(NvFlowCamera* ptr, NvFlowFloat4x4* projMatrix, float aspectWidth, float aspectHeight)
{
using namespace NvFlowMath;
float aspectRatio = aspectWidth / aspectHeight;
NvFlowFloat4x4 projection = {};
if (ptr->config.isOrthographic)
{
if (ptr->config.isProjectionRH)
{
if (ptr->config.isReverseZ)
{
projection = matrixOrthographicRH(ptr->config.orthographicY * aspectRatio, ptr->config.orthographicY, ptr->config.farPlane, ptr->config.nearPlane);
}
else
{
projection = matrixOrthographicRH(ptr->config.orthographicY * aspectRatio, ptr->config.orthographicY, ptr->config.nearPlane, ptr->config.farPlane);
}
*projMatrix = projection;
}
else
{
if (ptr->config.isReverseZ)
{
projection = matrixOrthographicLH(ptr->config.orthographicY * aspectRatio, ptr->config.orthographicY, ptr->config.farPlane, ptr->config.nearPlane);
}
else
{
projection = matrixOrthographicLH(ptr->config.orthographicY * aspectRatio, ptr->config.orthographicY, ptr->config.nearPlane, ptr->config.farPlane);
}
*projMatrix = projection;
}
}
else
{
if (ptr->config.isProjectionRH)
{
if (ptr->config.isReverseZ)
{
projection = matrixPerspectiveFovRH(ptr->config.fovAngleY, aspectRatio, ptr->config.farPlane, ptr->config.nearPlane);
}
else
{
projection = matrixPerspectiveFovRH(ptr->config.fovAngleY, aspectRatio, ptr->config.nearPlane, ptr->config.farPlane);
}
*projMatrix = projection;
}
else
{
if (ptr->config.isReverseZ)
{
projection = matrixPerspectiveFovLH(ptr->config.fovAngleY, aspectRatio, ptr->config.farPlane, ptr->config.nearPlane);
}
else
{
projection = matrixPerspectiveFovLH(ptr->config.fovAngleY, aspectRatio, ptr->config.nearPlane, ptr->config.farPlane);
}
*projMatrix = projection;
}
}
}
void NvFlowCameraMouseUpdate(NvFlowCamera* ptr, NvFlowCameraMouseButton button, NvFlowCameraAction action, int mouseX, int mouseY, int winw, int winh)
{
using namespace NvFlowMath;
// transient mouse state
float rotationDx = 0.f;
float rotationDy = 0.f;
float translateDx = 0.f;
float translateDy = 0.f;
int translateWinW = 1024;
int translateWinH = 1024;
float zoomDy = 0.f;
// process event
if (action == eNvFlowCameraAction_down)
{
if (button == eNvFlowCameraMouseButton_left)
{
ptr->rotationActive = true;
rotationDx = 0.f;
rotationDy = 0.f;
}
else if (button == eNvFlowCameraMouseButton_middle)
{
ptr->translateActive = true;
translateDx = 0.f;
translateDy = 0.f;
}
else if (button == eNvFlowCameraMouseButton_right)
{
ptr->zoomActive = true;
zoomDy = 0.f;
}
}
else if (action == eNvFlowCameraAction_up)
{
if (button == eNvFlowCameraMouseButton_left)
{
ptr->rotationActive = false;
rotationDx = 0.f;
rotationDy = 0.f;
}
else if (button == eNvFlowCameraMouseButton_middle)
{
ptr->translateActive = false;
translateDx = 0.f;
translateDy = 0.f;
}
else if (button == eNvFlowCameraMouseButton_right)
{
ptr->zoomActive = false;
zoomDy = 0.f;
}
}
else if (action == eNvFlowCameraAction_unknown)
{
if (ptr->rotationActive)
{
int dx = +(mouseX - ptr->mouseXprev);
int dy = +(mouseY - ptr->mouseYprev);
rotationDx = float(dx) * 2.f * 3.14f / (winw);
rotationDy = float(dy) * 2.f * 3.14f / (winh);
}
if (ptr->translateActive)
{
float dx = float(mouseX - ptr->mouseXprev);
float dy = -float(mouseY - ptr->mouseYprev);
translateDx = dx * 2.f / (winw);
translateDy = dy * 2.f / (winh);
translateWinW = winw;
translateWinH = winh;
}
if (ptr->zoomActive)
{
float dy = -float(mouseY - ptr->mouseYprev);
zoomDy = dy * 3.14f / float(winh);
}
}
// keep current mouse position for next previous
ptr->mouseXprev = mouseX;
ptr->mouseYprev = mouseY;
// apply rotation
if (rotationDx != 0.f || rotationDy != 0.f)
{
float dx = rotationDx;
float dy = rotationDy;
if (ptr->config.isProjectionRH)
{
dx = -dx;
dy = -dy;
}
float rotTilt = ptr->config.tiltRate * float(dy);
float rotPan = ptr->config.panRate * float(dx);
const float eyeDotLimit = 0.99f;
// tilt
{
NvFlowFloat4 eyeDirection4 = make_float4(ptr->state.eyeDirection, 0.f);
NvFlowFloat4 rotVec = {};
NvFlowCamera_computeRotationBasis(ptr, &rotVec, nullptr, nullptr);
const float angle = rotTilt;
NvFlowFloat4x4 dtilt = matrixRotationAxis(rotVec, angle);
eyeDirection4 = vector4Transform(eyeDirection4, dtilt);
// make sure eye direction stays normalized
eyeDirection4 = vector3Normalize(eyeDirection4);
// check dot of eyeDirection and eyeUp, and avoid commit if value is very low
float eyeDot = fabsf(
eyeDirection4.x * ptr->state.eyeUp.x +
eyeDirection4.y * ptr->state.eyeUp.y +
eyeDirection4.z * ptr->state.eyeUp.z
);
if (eyeDot < eyeDotLimit)
{
ptr->state.eyeDirection = float4_to_float3(eyeDirection4);
}
}
// pan
{
NvFlowFloat4 eyeDirection4 = make_float4(ptr->state.eyeDirection, 0.f);
NvFlowFloat4 rotVec = make_float4(ptr->state.eyeUp, 0.f);
const float angle = rotPan;
NvFlowFloat4x4 dpan = matrixRotationAxis(rotVec, angle);
eyeDirection4 = vector4Transform(eyeDirection4, dpan);
// make sure eye direction stays normalized
eyeDirection4 = vector3Normalize(eyeDirection4);
ptr->state.eyeDirection = float4_to_float3(eyeDirection4);
}
}
// apply translation
if (translateDx != 0.f || translateDy != 0.f)
{
// goal here is to apply an NDC offset, to the position value in world space
NvFlowFloat4x4 projection = {};
NvFlowCameraGetProjection(ptr, &projection, float(translateWinW), float(translateWinH));
NvFlowFloat4x4 view = {};
NvFlowCameraGetView(ptr, &view);
// project position to NDC
NvFlowFloat4 positionNDC = make_float4(ptr->state.position, 1.f);
positionNDC = vector4Transform(positionNDC, view);
positionNDC = vector4Transform(positionNDC, projection);
// normalize
if (positionNDC.w > 0.f)
{
positionNDC = positionNDC / vectorSplatW(positionNDC);
}
// offset using mouse data
positionNDC.x += translateDx;
positionNDC.y += translateDy;
// move back to world space
NvFlowFloat4x4 projViewInverse = matrixInverse(
matrixMultiply(view, projection)
);
NvFlowFloat4 positionWorld = vector4Transform(positionNDC, projViewInverse);
// normalize
if (positionWorld.w > 0.f)
{
positionWorld = positionWorld / vectorSplatW(positionWorld);
}
// commit update
ptr->state.position = float4_to_float3(positionWorld);
}
// apply zoom
if (zoomDy != 0.f)
{
ptr->state.eyeDistanceFromPosition *= (1.f + ptr->config.zoomRate * zoomDy);
}
}
void NvFlowCameraKeyUpdate(NvFlowCamera* ptr, NvFlowCameraKey key, NvFlowCameraAction action)
{
if (action == eNvFlowCameraAction_down)
{
if (key == eNvFlowCameraKey_up)
{
ptr->keyTranslateActiveMask |= 2u;
}
if (key == eNvFlowCameraKey_down)
{
ptr->keyTranslateActiveMask |= 4u;
}
if (key == eNvFlowCameraKey_left)
{
ptr->keyTranslateActiveMask |= 8u;
}
if (key == eNvFlowCameraKey_right)
{
ptr->keyTranslateActiveMask |= 16u;
}
}
else if (action == eNvFlowCameraAction_up)
{
if (key == eNvFlowCameraKey_up)
{
ptr->keyTranslateActiveMask &= ~2u;
}
if (key == eNvFlowCameraKey_down)
{
ptr->keyTranslateActiveMask &= ~4u;
}
if (key == eNvFlowCameraKey_left)
{
ptr->keyTranslateActiveMask &= ~8u;
}
if (key == eNvFlowCameraKey_right)
{
ptr->keyTranslateActiveMask &= ~16u;
}
}
}
void NvFlowCameraAnimationTick(NvFlowCamera* ptr, float deltaTime)
{
using namespace NvFlowMath;
float x = 0.f;
float y = 0.f;
float z = 0.f;
float rate = ptr->config.keyTranslationRate * deltaTime;
if (ptr->keyTranslateActiveMask & 2u)
{
z += -rate;
}
if (ptr->keyTranslateActiveMask & 4u)
{
z += +rate;
}
if (ptr->keyTranslateActiveMask & 8)
{
x += +rate;
}
if (ptr->keyTranslateActiveMask & 16)
{
x += -rate;
}
if (ptr->keyTranslateActiveMask)
{
ptr->state.position.x += ptr->state.eyeDirection.x * z;
ptr->state.position.y += ptr->state.eyeDirection.y * z;
ptr->state.position.z += ptr->state.eyeDirection.z * z;
// compute xaxis
NvFlowFloat4 xAxis{};
NvFlowCamera_computeRotationBasis(ptr, &xAxis, nullptr, nullptr);
ptr->state.position.x += xAxis.x * x;
ptr->state.position.y += xAxis.y * x;
ptr->state.position.z += xAxis.z * x;
}
} |
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/EditorCompute.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include "EditorCommon.h"
void editorCompute_init(EditorCompute* ptr, const NvFlowSwapchainDesc* swapchainDesc, NvFlowBool32 headless)
{
ptr->headless = headless;
// initialize benchmarking if enabled
if (ptr->benchmarkFrameCount)
{
ptr->vsync = NV_FLOW_FALSE;
appTimerInit(&ptr->benchmarkTimerCPU);
appTimerBegin(&ptr->benchmarkTimerCPU);
fopen_s(&ptr->outputFile, ptr->outputFilename, "w");
fprintf(ptr->outputFile, "FrameID, FrameTime, CPUTime, GPUTime, ActiveBlockCount\n");
}
NvFlowLoaderInitDeviceAPI(&ptr->loader, printError, nullptr, ptr->contextApi);
NvFlowBool32 validation = NV_FLOW_TRUE;
ptr->deviceManager = ptr->loader.deviceInterface.createDeviceManager(validation, nullptr, ptr->threadCount);
NvFlowDeviceDesc deviceDesc = {};
deviceDesc.deviceIndex = 0u;
deviceDesc.enableExternalUsage = NV_FLOW_TRUE;
deviceDesc.logPrint = editorCompute_logPrint;
ptr->device = ptr->loader.deviceInterface.createDevice(ptr->deviceManager, &deviceDesc);
ptr->deviceQueue = ptr->loader.deviceInterface.getDeviceQueue(ptr->device);
if (!ptr->headless)
{
ptr->swapchain = ptr->loader.deviceInterface.createSwapchain(ptr->deviceQueue, swapchainDesc);
}
NvFlowContextInterface_duplicate(&ptr->contextInterface, ptr->loader.deviceInterface.getContextInterface(ptr->deviceQueue));
// testing external semaphore
NvFlowUint64 testHandle = 0u;
NvFlowDeviceSemaphore* testSemaphore = ptr->loader.deviceInterface.createSemaphore(ptr->device);
ptr->loader.deviceInterface.getSemaphoreExternalHandle(testSemaphore, &testHandle, sizeof(testHandle));
printf("Test semaphore handle = %llu\n", testHandle);
ptr->loader.deviceInterface.closeSemaphoreExternalHandle(testSemaphore, &testHandle, sizeof(testHandle));
ptr->loader.deviceInterface.destroySemaphore(testSemaphore);
}
void editorCompute_destroy(EditorCompute* ptr)
{
if (ptr->swapchain)
{
ptr->loader.deviceInterface.destroySwapchain(ptr->swapchain);
}
ptr->loader.deviceInterface.destroyDevice(ptr->deviceManager, ptr->device);
ptr->loader.deviceInterface.destroyDeviceManager(ptr->deviceManager);
NvFlowLoaderDestroy(&ptr->loader);
// destroy benchmarking if enabled
if (ptr->benchmarkFrameCount)
{
appTimerEnd(&ptr->benchmarkTimerCPU);
fclose(ptr->outputFile);
}
}
void editorCompute_reportEntries(void* userdata, NvFlowUint64 captureID, NvFlowUint numEntries, NvFlowProfilerEntry* entries)
{
EditorCompute* ptr = (EditorCompute*)userdata;
if (ptr->benchmarkFrameCount)
{
appTimerEnd(&ptr->benchmarkTimerCPU);
float deltaTime = 0.f;
appTimerGetResults(&ptr->benchmarkTimerCPU, &deltaTime);
float cpuSum = 0.f;
float gpuSum = 0.f;
for (NvFlowUint entryIdx = 0u; entryIdx < numEntries; entryIdx++)
{
cpuSum += entries[entryIdx].cpuDeltaTime;
gpuSum += entries[entryIdx].gpuDeltaTime;
}
if (ptr->outputFile && ptr->benchmarkFrameID > 0u)
{
fprintf(ptr->outputFile, "%d, %f, %f, %f, %d\n", ptr->benchmarkFrameID, 1000.f * deltaTime, 1000.f * cpuSum, 1000.f * gpuSum, ptr->benchmarkActiveBlockCount);
}
ptr->benchmarkFrameID++;
if (ptr->benchmarkFrameID > ptr->benchmarkFrameCount)
{
ptr->benchmarkShouldRun = false;
}
appTimerBegin(&ptr->benchmarkTimerCPU);
}
// reset active mask
for (NvFlowUint entryIdx = 0u; entryIdx < ptr->statEntries_active.size; entryIdx++)
{
ptr->statEntries_active[entryIdx] = NV_FLOW_FALSE;
}
NvFlowUint minInactiveEntry = 0u;
for (NvFlowUint profEntryIdx = 0u; profEntryIdx < numEntries; profEntryIdx++)
{
const NvFlowProfilerEntry profEntry = entries[profEntryIdx];
// update minInactiveEntry
for (; minInactiveEntry < ptr->statEntries_active.size; minInactiveEntry++)
{
if (!ptr->statEntries_active[minInactiveEntry])
{
break;
}
}
// search for matching label
NvFlowUint64 entryIdx = minInactiveEntry;
for (; entryIdx < ptr->statEntries_label.size; entryIdx++)
{
if (!ptr->statEntries_active[entryIdx] && strcmp(profEntry.label, ptr->statEntries_label[entryIdx]) == 0)
{
break;
}
}
// allocate new if needed
if (entryIdx >= ptr->statEntries_label.size)
{
entryIdx = ptr->statEntries_label.size;
ptr->statEntries_label.pushBack(profEntry.label);
ptr->statEntries_active.pushBack(NV_FLOW_FALSE);
ptr->statEntries_cpuDeltaTime_sum.pushBack(0.f);
ptr->statEntries_cpuDeltaTime_count.pushBack(0.f);
ptr->statEntries_gpuDeltaTime_sum.pushBack(0.f);
ptr->statEntries_gpuDeltaTime_count.pushBack(0.f);
}
// update entry
{
ptr->statEntries_active[entryIdx] = NV_FLOW_TRUE;
ptr->statEntries_cpuDeltaTime_sum[entryIdx] += profEntry.cpuDeltaTime;
ptr->statEntries_cpuDeltaTime_count[entryIdx] += 1.f;
ptr->statEntries_gpuDeltaTime_sum[entryIdx] += profEntry.gpuDeltaTime;
ptr->statEntries_gpuDeltaTime_count[entryIdx] += 1.f;
}
}
// subsample by default, to avoid a massive log
if ((captureID % 15) == 0)
{
ptr->statOut_label.size = 0u;
ptr->statOut_cpu.size = 0u;
ptr->statOut_gpu.size = 0u;
ptr->statOut_label.pushBack("Total");
ptr->statOut_cpu.pushBack(0.f);
ptr->statOut_gpu.pushBack(0.f);
float cpuSum = 0.f;
float gpuSum = 0.f;
fprintf(ptr->perflog, "\nFrame[%lld] : label cpuTimeMS gpuTimeMS\n", captureID);
for (NvFlowUint entryIdx = 0u; entryIdx < ptr->statEntries_label.size; entryIdx++)
{
const char* label = ptr->statEntries_label[entryIdx];
float cpuDeltaTime = ptr->statEntries_cpuDeltaTime_sum[entryIdx] / ptr->statEntries_cpuDeltaTime_count[entryIdx];
float gpuDeltaTime = ptr->statEntries_gpuDeltaTime_sum[entryIdx] / ptr->statEntries_gpuDeltaTime_count[entryIdx];
fprintf(ptr->perflog, "%s, %f, %f\n", label, 1000.f * cpuDeltaTime, 1000.f * gpuDeltaTime);
ptr->statOut_label.pushBack(label);
ptr->statOut_cpu.pushBack(1000.f * cpuDeltaTime);
ptr->statOut_gpu.pushBack(1000.f * gpuDeltaTime);
cpuSum += cpuDeltaTime;
gpuSum += gpuDeltaTime;
}
ptr->statOut_cpu[0] = 1000.f * cpuSum;
ptr->statOut_gpu[0] = 1000.f * gpuSum;
// reset stats
ptr->statEntries_label.size = 0u;
ptr->statEntries_active.size = 0u;
ptr->statEntries_cpuDeltaTime_sum.size = 0u;
ptr->statEntries_cpuDeltaTime_count.size = 0u;
ptr->statEntries_gpuDeltaTime_sum.size = 0u;
ptr->statEntries_gpuDeltaTime_count.size = 0u;
}
}
void editorCompute_logPrint(NvFlowLogLevel level, const char* format, ...)
{
va_list args;
va_start(args, format);
const char* prefix = "Unknown";
if (level == eNvFlowLogLevel_error)
{
prefix = "Error";
}
else if (level == eNvFlowLogLevel_warning)
{
prefix = "Warning";
}
else if (level == eNvFlowLogLevel_info)
{
prefix = "Info";
}
printf("%s: ", prefix);
vprintf(format, args);
printf("\n");
va_end(args);
}
|
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/TestC.c | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#define NV_FLOW_CPU 1
#include "NvFlowExt.h"
#include "shaders/NvFlowRayMarchParams.h" |
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/Loader.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#define GLFW_DLL
#if defined(_WIN32)
#define GLFW_EXPOSE_NATIVE_WIN32
#else
#define GLFW_EXPOSE_NATIVE_X11
#endif
#include <GLFW/glfw3.h>
#include <GLFW/glfw3native.h>
#define NV_FLOW_SWAPCHAIN_DESC 1
#include "NvFlowLoader.h"
#define GLFW_PTR(X) decltype(&X) p_##X = nullptr
#define GLFW_PTR_LOAD(X) ptr->p_##X = (decltype(&X))GlfwLoader_loadFunction(ptr, #X)
struct GlfwLoader
{
void* module = nullptr;
GLFW_PTR(glfwInit);
GLFW_PTR(glfwWindowHint);
GLFW_PTR(glfwCreateWindow);
GLFW_PTR(glfwGetPrimaryMonitor);
GLFW_PTR(glfwGetVideoMode);
GLFW_PTR(glfwSetWindowUserPointer);
GLFW_PTR(glfwSetWindowPos);
GLFW_PTR(glfwSetWindowSizeCallback);
GLFW_PTR(glfwSetKeyCallback);
GLFW_PTR(glfwSetCharCallback);
GLFW_PTR(glfwSetMouseButtonCallback);
GLFW_PTR(glfwSetCursorPosCallback);
GLFW_PTR(glfwSetScrollCallback);
#if defined(_WIN32)
GLFW_PTR(glfwGetWin32Window);
#else
GLFW_PTR(glfwGetX11Display);
GLFW_PTR(glfwGetX11Window);
#endif
GLFW_PTR(glfwDestroyWindow);
GLFW_PTR(glfwTerminate);
GLFW_PTR(glfwPollEvents);
GLFW_PTR(glfwWindowShouldClose);
GLFW_PTR(glfwGetWindowUserPointer);
GLFW_PTR(glfwSetWindowMonitor);
GLFW_PTR(glfwGetMouseButton);
};
inline void* GlfwLoader_loadFunction(GlfwLoader* ptr, const char* name)
{
return NvFlowGetProcAddress(ptr->module, name);
}
inline void GlfwLoader_init(GlfwLoader* ptr)
{
#if defined(__aarch64__)
ptr->module = NvFlowLoadLibrary("glfw3.dll", "libglfw_aarch64.so.3.3");
#else
ptr->module = NvFlowLoadLibrary("glfw3.dll", "libglfw.so.3");
#endif
GLFW_PTR_LOAD(glfwInit);
GLFW_PTR_LOAD(glfwWindowHint);
GLFW_PTR_LOAD(glfwCreateWindow);
GLFW_PTR_LOAD(glfwGetPrimaryMonitor);
GLFW_PTR_LOAD(glfwGetVideoMode);
GLFW_PTR_LOAD(glfwSetWindowUserPointer);
GLFW_PTR_LOAD(glfwSetWindowPos);
GLFW_PTR_LOAD(glfwSetWindowSizeCallback);
GLFW_PTR_LOAD(glfwSetKeyCallback);
GLFW_PTR_LOAD(glfwSetCharCallback);
GLFW_PTR_LOAD(glfwSetMouseButtonCallback);
GLFW_PTR_LOAD(glfwSetCursorPosCallback);
GLFW_PTR_LOAD(glfwSetScrollCallback);
#if defined(_WIN32)
GLFW_PTR_LOAD(glfwGetWin32Window);
#else
GLFW_PTR_LOAD(glfwGetX11Display);
GLFW_PTR_LOAD(glfwGetX11Window);
#endif
GLFW_PTR_LOAD(glfwDestroyWindow);
GLFW_PTR_LOAD(glfwTerminate);
GLFW_PTR_LOAD(glfwPollEvents);
GLFW_PTR_LOAD(glfwWindowShouldClose);
GLFW_PTR_LOAD(glfwGetWindowUserPointer);
GLFW_PTR_LOAD(glfwSetWindowMonitor);
GLFW_PTR_LOAD(glfwGetMouseButton);
}
inline void GlfwLoader_destroy(GlfwLoader* ptr)
{
NvFlowFreeLibrary(ptr->module);
}
|
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/EditorFlow.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include "EditorCommon.h"
struct NvFlowDatabasePrim
{
NvFlowDatabasePrim* parent;
const char* path;
const char* name;
NvFlowStringHashTable<NvFlowDatabaseAttr*> attrMap;
};
NV_FLOW_INLINE NvFlowDatabasePrim* createPrim(
NvFlowDatabaseContext* context,
NvFlowUint64 version,
NvFlowDatabasePrim* parent,
const char* displayTypename,
const char* path,
const char* name)
{
auto prim = new NvFlowDatabasePrim();
prim->parent = parent;
prim->path = path;
prim->name = name;
//printf("Create prim: displayTypename(%s), path(%s) name(%s)\n", displayTypename, path, name);
// register prim
EditorFlow* ptr = (EditorFlow*)context;
NvFlowBool32 success = NV_FLOW_FALSE;
ptr->primMap.insert(path, NvFlowStringHashFNV(path), prim, &success);
if (!success)
{
editorCompute_logPrint(eNvFlowLogLevel_warning, "Prim register failed, existing prim at path %s", path);
}
return prim;
}
NV_FLOW_INLINE void updatePrim(
NvFlowDatabaseContext* context,
NvFlowUint64 version,
NvFlowUint64 minActiveVersion,
NvFlowDatabasePrim* prim)
{
}
NV_FLOW_INLINE void markDestroyedPrim(NvFlowDatabaseContext* context, NvFlowDatabasePrim* prim)
{
// unregister prim
EditorFlow* ptr = (EditorFlow*)context;
if (!ptr->primMap.erase(prim->path, NvFlowStringHashFNV(prim->path)))
{
editorCompute_logPrint(eNvFlowLogLevel_warning, "Prim unregister failed, prim not registered %s", prim->path);
}
//printf("MarkDestroyed prim: path(%s) name(%s)\n", prim->path, prim->name);
}
NV_FLOW_INLINE void destroyPrim(NvFlowDatabaseContext* context, NvFlowDatabasePrim* prim)
{
//printf("Destroy prim: path(%s) name(%s)\n", prim->path, prim->name);
delete prim;
}
struct NvFlowDatabaseValue
{
NvFlowArray<NvFlowUint8> data;
NvFlowUint64 version;
NvFlowUint64 lastUsed;
};
struct NvFlowDatabaseAttr
{
NvFlowDatabasePrim* prim = nullptr;
NvFlowRingBufferPointer<NvFlowDatabaseValue*> values;
const char* name = nullptr;
NvFlowUint64 commandIdx = ~0llu;
};
NV_FLOW_INLINE NvFlowDatabaseValue* copyArray(
NvFlowUint64 version,
NvFlowUint64 minActiveVersion,
NvFlowDatabaseAttr* attr,
const NvFlowReflectData* reflectData,
NvFlowUint8* mappedData,
const void* srcData,
NvFlowUint64 srcDataSizeInBytes
)
{
auto value = attr->values.allocateBackPointer();
value->version = version;
value->lastUsed = version;
value->data.size = 0u;
NvFlowUint8** pData = (NvFlowUint8**)(mappedData + reflectData->dataOffset);
NvFlowUint64* pArraySize = (NvFlowUint64*)(mappedData + reflectData->arraySizeOffset);
value->data.reserve(srcDataSizeInBytes);
value->data.size = srcDataSizeInBytes;
if (srcData)
{
memcpy(value->data.data, srcData, srcDataSizeInBytes);
}
else
{
memset(value->data.data, 0, srcDataSizeInBytes);
}
// override to owned copy
*pData = value->data.data;
*pArraySize = srcDataSizeInBytes / reflectData->dataType->elementSize;
if (reflectData->reflectMode == eNvFlowReflectMode_arrayVersioned)
{
NvFlowUint64* pVersion = (NvFlowUint64*)(mappedData + reflectData->versionOffset);
// aligning array version to commit version, convenient by not required
*pVersion = version;
}
return value;
}
NV_FLOW_INLINE NvFlowDatabaseAttr* createAttr(
NvFlowDatabaseContext* context,
NvFlowUint64 version,
NvFlowDatabasePrim* prim,
const NvFlowReflectData* reflectData,
NvFlowUint8* mappedData)
{
auto attr = new NvFlowDatabaseAttr();
attr->prim = prim;
attr->name = reflectData->name;
// make copy of any read only arrays to allow in place edit
if (reflectData->reflectMode == eNvFlowReflectMode_array ||
reflectData->reflectMode == eNvFlowReflectMode_arrayVersioned)
{
NvFlowUint8** pData = (NvFlowUint8**)(mappedData + reflectData->dataOffset);
NvFlowUint64* pArraySize = (NvFlowUint64*)(mappedData + reflectData->arraySizeOffset);
NvFlowUint8* data = *pData;
NvFlowUint64 arraySizeInBytes = (*pArraySize) * reflectData->dataType->elementSize;
copyArray(version, version, attr, reflectData, mappedData, data, arraySizeInBytes);
}
// register attribute
EditorFlow* ptr = (EditorFlow*)context;
NvFlowBool32 success = NV_FLOW_FALSE;
prim->attrMap.insert(attr->name, NvFlowStringHashFNV(attr->name), attr, &success);
if (!success)
{
editorCompute_logPrint(eNvFlowLogLevel_warning, "Attribute register failed, existing attribute with name %s", reflectData->name);
}
return attr;
}
NV_FLOW_INLINE void updateAttr(
NvFlowDatabaseContext* context,
NvFlowUint64 version,
NvFlowUint64 minActiveVersion,
NvFlowDatabaseAttr* attr,
const NvFlowReflectData* reflectData,
NvFlowUint8* mappedData)
{
EditorFlow* ptr = (EditorFlow*)context;
// recycle before update to maximum chance of reuse
if (reflectData->reflectMode == eNvFlowReflectMode_array ||
reflectData->reflectMode == eNvFlowReflectMode_arrayVersioned)
{
// leave 1 to allow copy/migrate
while (attr->values.activeCount() > 1u && attr->values.front()->lastUsed < minActiveVersion)
{
//printf("Popping %s version %llu lastUsed %llu\n", reflectData->name, attr->values.front()->version, attr->values.front()->lastUsed);
attr->values.popFront();
}
}
if (attr->commandIdx < ptr->commands.size)
{
EditorFlowCommand* cmd = &ptr->commands[attr->commandIdx];
if (reflectData->reflectMode == eNvFlowReflectMode_value ||
reflectData->reflectMode == eNvFlowReflectMode_valueVersioned)
{
if (reflectData->dataType->elementSize == cmd->dataSize)
{
memcpy(mappedData + reflectData->dataOffset, cmd->data, cmd->dataSize);
}
}
else if (reflectData->reflectMode == eNvFlowReflectMode_array ||
reflectData->reflectMode == eNvFlowReflectMode_arrayVersioned)
{
copyArray(version, minActiveVersion, attr, reflectData, mappedData, cmd->data, cmd->dataSize);
}
// invalidate command
attr->commandIdx = ~0llu;
}
// free at end, in case new array allows old to free
if (reflectData->reflectMode == eNvFlowReflectMode_array ||
reflectData->reflectMode == eNvFlowReflectMode_arrayVersioned)
{
if (attr->values.activeCount() > 0u)
{
attr->values.back()->lastUsed = version;
}
// leave 1 to allow copy/migrate
while (attr->values.activeCount() > 1u && attr->values.front()->lastUsed < minActiveVersion)
{
//printf("Popping %s version %llu lastUsed %llu\n", reflectData->name, attr->values.front()->version, attr->values.front()->lastUsed);
attr->values.popFront();
}
}
}
NV_FLOW_INLINE void markDestroyedAttr(NvFlowDatabaseContext* context, NvFlowDatabaseAttr* attr)
{
// unregister attribute
EditorFlow* ptr = (EditorFlow*)context;
if (!attr->prim->attrMap.erase(attr->name, NvFlowStringHashFNV(attr->name)))
{
editorCompute_logPrint(eNvFlowLogLevel_warning, "Attribute unregister failed, attribute not registered %s", attr->name);
}
}
NV_FLOW_INLINE void destroyAttr(NvFlowDatabaseContext* context, NvFlowDatabaseAttr* attr)
{
delete attr;
}
static const NvFlowDatabaseInterface iface = {
createPrim, updatePrim, markDestroyedPrim, destroyPrim,
createAttr, updateAttr, markDestroyedAttr, destroyAttr
};
void editorFlow_init(EditorCompute* ctx, EditorFlow* ptr)
{
NvFlowContext* context = ctx->loader.deviceInterface.getContext(ctx->deviceQueue);
ptr->commandStringPool = NvFlowStringPoolCreate();
NvFlowGridDesc gridDesc = NvFlowGridDesc_default;
ptr->maxLocations = ptr->targetMaxLocations;
gridDesc.maxLocations = ptr->maxLocations;
ptr->grid = ctx->loader.gridInterface.createGrid(&ctx->contextInterface, context, &ctx->loader.opList, &ctx->loader.extOpList, &gridDesc);
ptr->gridParamsServer = ctx->loader.gridParamsInterface.createGridParamsNamed(nullptr);
ptr->gridParamsClient = ctx->loader.gridParamsInterface.createGridParamsNamed(nullptr);
ptr->gridParams = ctx->loader.gridParamsInterface.mapGridParamsNamed(ptr->gridParamsServer);
//ptr->loader.gridInterface.setResourceMinLifetime(context, ptr->grid, 0u);
editorCompute_logPrint(eNvFlowLogLevel_info, "Initialized Flow Grid");
NvFlowUint64 typeCount = 0u;
ctx->loader.gridParamsInterface.enumerateParamTypes(ptr->gridParams, nullptr, nullptr, nullptr, &typeCount);
ptr->typenames.reserve(typeCount);
ptr->typenames.size = typeCount;
ptr->displayTypenames.reserve(typeCount);
ptr->displayTypenames.size = typeCount;
ptr->dataTypes.reserve(typeCount);
ptr->dataTypes.size = typeCount;
ctx->loader.gridParamsInterface.enumerateParamTypes(ptr->gridParams, ptr->typenames.data, ptr->displayTypenames.data, ptr->dataTypes.data, &typeCount);
// register types
ptr->types.size = 0u;
for (NvFlowUint64 typeIdx = 0u; typeIdx < ptr->dataTypes.size; typeIdx++)
{
ptr->types.pushBack(ptr->gridParamsSet.createType(ptr->dataTypes[typeIdx], ptr->displayTypenames[typeIdx]));
}
const EditorFlowStage** builtinStages = nullptr;
NvFlowUint64 builtinStageCount = 0u;
editorFlowStage_getBuiltinStages(&builtinStages, &builtinStageCount);
for (NvFlowUint idx = 0u; idx < builtinStageCount; idx++)
{
ptr->stages.pushBack(builtinStages[idx]);
}
// command line stage selection
if (ptr->cmdStage)
{
for (NvFlowUint64 idx = 0u; idx < ptr->stages.size; idx++)
{
if (strcmp(ptr->stages[idx]->stageName, ptr->cmdStage) == 0)
{
ptr->targetStageIdx = idx;
}
}
}
if (ptr->stages.size > 0u)
{
ptr->targetStageIdx = ptr->targetStageIdx % ptr->stages.size;
const EditorFlowStage* targetStage = ptr->stages[ptr->targetStageIdx];
ptr->currentStage = targetStage;
ptr->stageUserdata = ptr->currentStage->init(ptr);
editorFlowStage_applyOverrides(ptr, ptr->cellsizeOverride, ptr->smallBlocksOverride);
}
}
void editorFlow_presimulate(EditorCompute* ctx, EditorFlow* ptr, float deltaTime, NvFlowBool32 isPaused)
{
NvFlowGridParamsDesc nullGridParamsDesc = {};
ptr->gridParamsDesc = nullGridParamsDesc;
ptr->absoluteSimTime += deltaTime;
float simDeltaTime = isPaused ? 0.f : deltaTime;
ptr->animationTime += simDeltaTime;
NvFlowBool32 globalForceClear = NV_FLOW_FALSE;
if (ptr->stages.size > 0u)
{
ptr->targetStageIdx = ptr->targetStageIdx % ptr->stages.size;
const EditorFlowStage* targetStage = ptr->stages[ptr->targetStageIdx];
if (ptr->currentStage != targetStage)
{
if (ptr->currentStage)
{
if (ptr->currentStage->destroy)
{
ptr->currentStage->destroy(ptr, ptr->stageUserdata);
ptr->stageUserdata = nullptr;
}
}
editorFlow_clearStage(ptr);
globalForceClear = NV_FLOW_TRUE;
ptr->currentStage = targetStage;
ptr->stageUserdata = ptr->currentStage->init(ptr);
editorFlowStage_applyOverrides(ptr, ptr->cellsizeOverride, ptr->smallBlocksOverride);
}
}
if (ptr->currentStage)
{
if (ptr->currentStage->update)
{
ptr->currentStage->update(ptr, ptr->stageUserdata, ptr->animationTime, simDeltaTime);
}
}
//auto testParams = ptr->loader.gridParamsInterface.createAbstractParams(ptr->gridParams, 0u, "test");
NvFlowUint64 stagingVersion = 0llu;
NvFlowUint64 minActiveVersion = 0llu;
ctx->loader.gridParamsInterface.getVersion(ptr->gridParams, &stagingVersion, &minActiveVersion);
// process commands
for (NvFlowUint64 idx = 0u; idx < ptr->commands.size; idx++)
{
EditorFlowCommand* cmd = &ptr->commands[idx];
if (strcmp(cmd->cmd, "clearStage") == 0)
{
ptr->gridParamsSet.markAllInstancesForDestroy<&iface>((NvFlowDatabaseContext*)ptr);
}
else if (strcmp(cmd->cmd, "definePrim") == 0)
{
NvFlowUint64 typenameIdx = 0u;
for (; typenameIdx < ptr->typenames.size; typenameIdx++)
{
if (NvFlowReflectStringCompare(ptr->displayTypenames[typenameIdx], cmd->type) == 0 ||
NvFlowReflectStringCompare(ptr->typenames[typenameIdx], cmd->type) == 0)
{
break;
}
}
if (typenameIdx < ptr->typenames.size)
{
ptr->gridParamsSet.createInstance<&iface>((NvFlowDatabaseContext*)ptr, stagingVersion, ptr->types[typenameIdx], cmd->path, cmd->name);
}
else
{
editorCompute_logPrint(eNvFlowLogLevel_warning, "definePrim(%s, %s) failed, type not recognized", cmd->type, cmd->path);
}
}
else if (strcmp(cmd->cmd, "setAttribute") == 0)
{
NvFlowBool32 success = NV_FLOW_FALSE;
NvFlowUint64 primFindIdx = ptr->primMap.find(cmd->path, NvFlowStringHashFNV(cmd->path));
if (primFindIdx != ~0llu)
{
NvFlowDatabasePrim* prim = ptr->primMap.values[primFindIdx];
NvFlowUint64 attrFindIdx = prim->attrMap.find(cmd->name, NvFlowStringHashFNV(cmd->name));
if (attrFindIdx != ~0llu)
{
NvFlowDatabaseAttr* attr = prim->attrMap.values[attrFindIdx];
attr->commandIdx = idx;
success = NV_FLOW_TRUE;
}
}
if (!success)
{
editorCompute_logPrint(eNvFlowLogLevel_warning,
"setAttribute(%s, %s) failed, attribute does not exist.",
cmd->path, cmd->name
);
}
}
}
ptr->gridParamsSet.update<&iface>((NvFlowDatabaseContext*)ptr, stagingVersion, minActiveVersion);
// reset command queue
ptr->commands.size = 0u;
NvFlowStringPoolReset(ptr->commandStringPool);
NvFlowGridParamsDescSnapshot snapshot = {};
ptr->gridParamsSet.getSnapshot(&snapshot.snapshot, stagingVersion);
snapshot.absoluteSimTime = ptr->absoluteSimTime;
snapshot.deltaTime = simDeltaTime;
snapshot.globalForceClear = globalForceClear;
ctx->loader.gridParamsInterface.commitParams(ptr->gridParams, &snapshot);
ptr->clientGridParams = ctx->loader.gridParamsInterface.mapGridParamsNamed(ptr->gridParamsClient);
ptr->paramsSnapshot = ctx->loader.gridParamsInterface.getParamsSnapshot(ptr->clientGridParams, ptr->absoluteSimTime, 0llu);
if (!ctx->loader.gridParamsInterface.mapParamsDesc(ptr->clientGridParams, ptr->paramsSnapshot, &ptr->gridParamsDesc))
{
printf("GridParams map failed!!!!!!!!!\n");
}
}
void editorFlow_simulate(EditorCompute* ctx, EditorFlow* ptr, float deltaTime, NvFlowBool32 isPaused)
{
NvFlowContext* context = ctx->loader.deviceInterface.getContext(ctx->deviceQueue);
{
if (ptr->maxLocations != ptr->targetMaxLocations)
{
ptr->maxLocations = ptr->targetMaxLocations;
NvFlowGridDesc gridDesc = NvFlowGridDesc_default;
gridDesc.maxLocations = ptr->maxLocations;
ctx->loader.gridInterface.resetGrid(
context,
ptr->grid,
&gridDesc
);
}
ctx->loader.gridInterface.simulate(
context,
ptr->grid,
&ptr->gridParamsDesc,
NV_FLOW_FALSE
);
NvFlowDatabaseSnapshot databaseSnapshot = {};
if (ptr->gridParamsDesc.snapshotCount > 0u)
{
databaseSnapshot = ptr->gridParamsDesc.snapshots[ptr->gridParamsDesc.snapshotCount - 1u].snapshot;
}
NV_FLOW_DATABASE_SNAPSHOT_FIND_TYPE_ARRAY(&databaseSnapshot, NvFlowGridSimulateLayerParams)
ptr->activeBlockCount = ctx->loader.gridInterface.getActiveBlockCount(ptr->grid);
ctx->benchmarkActiveBlockCount = ptr->activeBlockCount;
ptr->activeBlockDim = { 32u, 16u, 16u };
for (NvFlowUint64 layerParamIdx = 0u; layerParamIdx < NvFlowGridSimulateLayerParams_elementCount; layerParamIdx++)
{
if (NvFlowGridSimulateLayerParams_elements[layerParamIdx]->enableSmallBlocks)
{
ptr->activeBlockDim = { 16u, 8u, 8u };
}
}
ctx->loader.gridInterface.updateIsosurface(
context,
ptr->grid,
&ptr->gridParamsDesc
);
ptr->activeBlockCountIsosurface = ctx->loader.gridInterface.getActiveBlockCountIsosurface(ptr->grid);
}
// test grid export
{
NvFlowGridRenderData renderData = {};
ctx->loader.gridInterface.getRenderData(context, ptr->grid, &renderData);
static int writeFrame = 0;
writeFrame++;
if (writeFrame % 1000 == 999)
{
if (renderData.nanoVdb.readbackCount > 0u)
{
NvFlowUint64 lastGlobalFrameCompleted = ctx->contextInterface.getLastGlobalFrameCompleted(context);
NvFlowSparseNanoVdbExportReadback* readback = &renderData.nanoVdb.readbacks[0u];
if (readback->globalFrameCompleted <= lastGlobalFrameCompleted && readback->smokeNanoVdbReadback)
{
const char* path = "../../../data/capture0.nvdb.raw";
FILE* file = nullptr;
fopen_s(&file, path, "wb");
if (file)
{
printf("Writing out capture0.nvdb.raw...\n");
fwrite(readback->smokeNanoVdbReadback, 1u, readback->smokeNanoVdbReadbackSize, file);
fclose(file);
}
}
}
}
}
}
void editorFlow_offscreen(EditorCompute* ctx, EditorFlow* ptr)
{
NvFlowContext* context = ctx->loader.deviceInterface.getContext(ctx->deviceQueue);
ctx->loader.gridInterface.offscreen(
context,
ptr->grid,
&ptr->gridParamsDesc
);
}
void editorFlow_render(
EditorCompute* ctx,
EditorFlow* ptr,
NvFlowTextureTransient** colorFrontTransient,
NvFlowTextureTransient* offscreenDepthTransient,
NvFlowUint windowWidth,
NvFlowUint windowHeight,
const NvFlowFloat4x4* view,
const NvFlowFloat4x4* projection
)
{
NvFlowContext* context = ctx->loader.deviceInterface.getContext(ctx->deviceQueue);
ctx->loader.gridInterface.render(
context,
ptr->grid,
&ptr->gridParamsDesc,
view,
projection,
projection,
windowWidth,
windowHeight,
windowWidth,
windowHeight,
1.f,
offscreenDepthTransient,
eNvFlowFormat_r16g16b16a16_float,
*colorFrontTransient,
colorFrontTransient
);
ctx->loader.gridInterface.renderIsosurface(
context,
ptr->grid,
&ptr->gridParamsDesc,
view,
projection,
projection,
windowWidth,
windowHeight,
windowWidth,
windowHeight,
1.f,
offscreenDepthTransient,
eNvFlowFormat_r16g16b16a16_float,
*colorFrontTransient,
colorFrontTransient
);
}
void editorFlow_unmap(EditorCompute* ctx, EditorFlow* ptr)
{
ctx->loader.gridParamsInterface.unmapParamsDesc(ptr->clientGridParams, ptr->paramsSnapshot);
// invalidate mapped gridParamsDesc
NvFlowGridParamsDesc nullGridParamsDesc = {};
ptr->gridParamsDesc = nullGridParamsDesc;
}
void editorFlow_destroy(EditorCompute* ctx, EditorFlow* ptr)
{
NvFlowContext* context = ctx->loader.deviceInterface.getContext(ctx->deviceQueue);
if (ptr->currentStage)
{
if (ptr->currentStage->destroy)
{
ptr->currentStage->destroy(ptr, ptr->stageUserdata);
ptr->stageUserdata = nullptr;
}
}
ctx->loader.gridInterface.destroyGrid(context, ptr->grid);
ctx->loader.gridParamsInterface.destroyGridParamsNamed(ptr->gridParamsServer);
ctx->loader.gridParamsInterface.destroyGridParamsNamed(ptr->gridParamsClient);
ptr->gridParamsSet.markAllInstancesForDestroy<&iface>((NvFlowDatabaseContext*)ptr);
ptr->gridParamsSet.destroy<&iface>((NvFlowDatabaseContext*)ptr);
if (ptr->primMap.keyCount > 0u)
{
editorCompute_logPrint(eNvFlowLogLevel_warning, "Warning primMap not fully unregistered");
}
NvFlowStringPoolDestroy(ptr->commandStringPool);
editorCompute_logPrint(eNvFlowLogLevel_info, "Destroyed Grid");
}
void editorFlow_clearStage(EditorFlow* ptr)
{
EditorFlowCommand command = {};
command.cmd = "clearStage";
ptr->commands.pushBack(command);
}
void editorFlow_definePrim(EditorFlow* ptr, const char* type, const char* path, const char* name)
{
EditorFlowCommand command = {};
command.cmd = "definePrim";
command.path = NvFlowStringDup(ptr->commandStringPool, path);
command.name = NvFlowStringDup(ptr->commandStringPool, name);
command.type = NvFlowStringDup(ptr->commandStringPool, type);
ptr->commands.pushBack(command);
}
void editorFlow_setAttribute(EditorFlow* ptr, const char* primPath, const char* name, const void* data, NvFlowUint64 sizeInBytes)
{
char* commandData = NvFlowStringPoolAllocate(ptr->commandStringPool, sizeInBytes);
memcpy(commandData, data, sizeInBytes);
EditorFlowCommand command = {};
command.cmd = "setAttribute";
command.path = NvFlowStringDup(ptr->commandStringPool, primPath);
command.name = NvFlowStringDup(ptr->commandStringPool, name);
command.data = (NvFlowUint8*)commandData;
command.dataSize = sizeInBytes;
ptr->commands.pushBack(command);
}
void editorFlow_setAttributeFloat(EditorFlow* ptr, const char* primPath, const char* name, float value)
{
editorFlow_setAttribute(ptr, primPath, name, &value, sizeof(float));
}
void editorFlow_setAttributeInt(EditorFlow* ptr, const char* primPath, const char* name, int value)
{
editorFlow_setAttribute(ptr, primPath, name, &value, sizeof(int));
}
void editorFlow_setAttributeUint(EditorFlow* ptr, const char* primPath, const char* name, NvFlowUint value)
{
editorFlow_setAttribute(ptr, primPath, name, &value, sizeof(unsigned int));
}
void editorFlow_setAttributeBool(EditorFlow* ptr, const char* primPath, const char* name, NvFlowBool32 value)
{
editorFlow_setAttribute(ptr, primPath, name, &value, sizeof(NvFlowBool32));
}
void editorFlow_setAttributeFloat3(EditorFlow* ptr, const char* primPath, const char* name, NvFlowFloat3 value)
{
editorFlow_setAttribute(ptr, primPath, name, &value, sizeof(NvFlowFloat3));
}
void editorFlow_setAttributeFloat3Array(EditorFlow* ptr, const char* primPath, const char* name, const NvFlowFloat3* values, NvFlowUint64 elementCount)
{
editorFlow_setAttribute(ptr, primPath, name, values, elementCount * sizeof(NvFlowFloat3));
}
void editorFlow_setAttributeFloat4Array(EditorFlow* ptr, const char* primPath, const char* name, const NvFlowFloat4* values, NvFlowUint64 elementCount)
{
editorFlow_setAttribute(ptr, primPath, name, values, elementCount * sizeof(NvFlowFloat4));
}
void editorFlow_setAttributeIntArray(EditorFlow* ptr, const char* primPath, const char* name, const int* values, NvFlowUint64 elementCount)
{
editorFlow_setAttribute(ptr, primPath, name, values, elementCount * sizeof(int));
}
|
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/ShapeRenderer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
struct NvFlowShapeRenderer;
struct NvFlowShapeRendererParams
{
NvFlowUint numSpheres;
NvFlowFloat4* spherePositionRadius;
};
struct NvFlowShapeRendererInterface
{
NV_FLOW_REFLECT_INTERFACE();
NvFlowShapeRenderer*(NV_FLOW_ABI* create)(NvFlowContextInterface* contextInterface, NvFlowContext* context);
void(NV_FLOW_ABI* destroy)(NvFlowContext* context, NvFlowShapeRenderer* renderer);
void(NV_FLOW_ABI* render)(
NvFlowContext* context,
NvFlowShapeRenderer* renderer, const NvFlowShapeRendererParams* params,
const NvFlowFloat4x4* view,
const NvFlowFloat4x4* projection,
NvFlowUint textureWidth,
NvFlowUint textureHeight,
NvFlowTextureTransient* depthOut,
NvFlowTextureTransient* colorOut
);
};
#define NV_FLOW_REFLECT_TYPE NvFlowShapeRendererInterface
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_FUNCTION_POINTER(create, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroy, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(render, 0, 0)
NV_FLOW_REFLECT_END(0)
NV_FLOW_REFLECT_INTERFACE_IMPL()
#undef NV_FLOW_REFLECT_TYPE
NvFlowShapeRendererInterface* NvFlowGetShapeRendererInterface(); |
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/EditorGlfw.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include "EditorCommon.h"
GlfwLoader glfwLoader{};
void windowSizeCallback(GLFWwindow* win, int width, int height);
void keyboardCallback(GLFWwindow* win, int key, int scanCode, int action, int modifiers);
void charInputCallback(GLFWwindow* win, uint32_t input);
void mouseMoveCallback(GLFWwindow* win, double mouseX, double mouseY);
void mouseButtonCallback(GLFWwindow* win, int button, int action, int modifiers);
void mouseWheelCallback(GLFWwindow* win, double scrollX, double scrollY);
int editorGlfw_init(App* ptr)
{
GlfwLoader_init(&glfwLoader);
if (!glfwLoader.p_glfwInit)
{
fprintf(stderr, "GLFW binary is missing!\n");
return 1;
}
if (!glfwLoader.p_glfwInit())
{
fprintf(stderr, "Failed to init GLFW\n");
return 1;
}
glfwLoader.p_glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
const char* windowName = "NVIDIA Flow 2 Editor";
ptr->window = glfwLoader.p_glfwCreateWindow((int)ptr->windowWidth, (int)ptr->windowHeight, windowName, nullptr, nullptr);
if (!ptr->window)
{
fprintf(stderr, "Failed to create GLFW window\n");
return 1;
}
GLFWmonitor* monitor = glfwLoader.p_glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwLoader.p_glfwGetVideoMode(monitor);
glfwLoader.p_glfwSetWindowUserPointer(ptr->window, ptr);
glfwLoader.p_glfwSetWindowPos(ptr->window, mode->width / 2 - ((int)ptr->windowWidth) / 2, mode->height / 2 - ((int)ptr->windowHeight) / 2);
glfwLoader.p_glfwSetWindowSizeCallback(ptr->window, windowSizeCallback);
glfwLoader.p_glfwSetKeyCallback(ptr->window, keyboardCallback);
glfwLoader.p_glfwSetCharCallback(ptr->window, charInputCallback);
glfwLoader.p_glfwSetMouseButtonCallback(ptr->window, mouseButtonCallback);
glfwLoader.p_glfwSetCursorPosCallback(ptr->window, mouseMoveCallback);
glfwLoader.p_glfwSetScrollCallback(ptr->window, mouseWheelCallback);
return 0;
}
void editorGlfw_getSwapchainDesc(App* ptr, NvFlowSwapchainDesc* outDesc)
{
NvFlowSwapchainDesc swapchainDesc = {};
swapchainDesc.format = eNvFlowFormat_b8g8r8a8_unorm;
#if defined(_WIN32)
swapchainDesc.hwnd = glfwLoader.p_glfwGetWin32Window(ptr->window);
swapchainDesc.hinstance = (HINSTANCE)GetWindowLongPtr(swapchainDesc.hwnd, GWLP_HINSTANCE);
#else
swapchainDesc.dpy = glfwLoader.p_glfwGetX11Display();
swapchainDesc.window = glfwLoader.p_glfwGetX11Window(ptr->window);
#endif
*outDesc = swapchainDesc;
}
int editorGlfw_processEvents(App* ptr)
{
glfwLoader.p_glfwPollEvents();
if (glfwLoader.p_glfwWindowShouldClose(ptr->window))
{
editorCompute_logPrint(eNvFlowLogLevel_info, "GLFW Close Window.");
return 1;
}
return 0;
}
void editorGlfw_destroy(App* ptr)
{
glfwLoader.p_glfwDestroyWindow(ptr->window);
glfwLoader.p_glfwTerminate();
GlfwLoader_destroy(&glfwLoader);
}
void editorGlfw_newFrame(App* ptr, float deltaTime)
{
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = ImVec2(float(ptr->windowWidth), float(ptr->windowHeight));
io.DeltaTime = deltaTime;
for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
{
io.MouseDown[i] = ptr->mouseJustPressed[i] != 0u || glfwLoader.p_glfwGetMouseButton(ptr->window, i) != 0;
ptr->mouseJustPressed[i] = NV_FLOW_FALSE;
}
io.MousePos.x = (float)ptr->mouseX;
io.MousePos.y = (float)ptr->mouseY;
ImGui::NewFrame();
}
void windowSizeCallback(GLFWwindow* win, int width, int height)
{
auto ptr = (App*)glfwLoader.p_glfwGetWindowUserPointer(win);
// resize
ptr->compute.loader.deviceInterface.resizeSwapchain(ptr->compute.swapchain, (NvFlowUint)width, (NvFlowUint)height);
if (width == 0 || height == 0)
{
return;
}
ptr->windowWidth = width;
ptr->windowHeight = height;
}
void keyboardCallback(GLFWwindow* win, int key, int scanCode, int action, int modifiers)
{
auto ptr = (App*)glfwLoader.p_glfwGetWindowUserPointer(win);
ImGuiIO& io = ImGui::GetIO();
if (!io.WantCaptureKeyboard)
{
if (action == GLFW_PRESS)
{
if (key == GLFW_KEY_ESCAPE)
{
ptr->shouldRun = false;
}
else if (key == GLFW_KEY_H)
{
NvFlowCameraConfig config = {};
NvFlowCameraGetConfig(ptr->camera, &config);
config.isProjectionRH = !config.isProjectionRH;
NvFlowCameraSetConfig(ptr->camera, &config);
}
else if (key == GLFW_KEY_O)
{
NvFlowCameraConfig config = {};
NvFlowCameraGetConfig(ptr->camera, &config);
config.isOrthographic = !config.isOrthographic;
if (config.isOrthographic)
{
config.farPlane = 10000.f;
}
if (!config.isOrthographic && config.isReverseZ)
{
config.farPlane = INFINITY;
}
NvFlowCameraSetConfig(ptr->camera, &config);
}
else if (key == GLFW_KEY_J)
{
NvFlowCameraConfig config = {};
NvFlowCameraGetConfig(ptr->camera, &config);
config.isReverseZ = !config.isReverseZ;
if (config.isReverseZ)
{
config.farPlane = INFINITY;
}
else
{
config.farPlane = 10000.f;
}
if (config.isOrthographic)
{
config.farPlane = 10000.f;
}
NvFlowCameraSetConfig(ptr->camera, &config);
}
else if (key == GLFW_KEY_K)
{
NvFlowCameraState state = {};
NvFlowCameraGetState(ptr->camera, &state);
bool isZup = state.eyeUp.z > 0.5f;
NvFlowCameraGetDefaultState(&state, isZup);
NvFlowCameraSetState(ptr->camera, &state);
}
else if (key == GLFW_KEY_V)
{
ptr->compute.vsync ^= NV_FLOW_TRUE;
}
else if (key == GLFW_KEY_P)
{
ptr->isPaused ^= NV_FLOW_TRUE;
}
else if (key == GLFW_KEY_G)
{
ptr->overlayEnabled ^= NV_FLOW_TRUE;
}
else if (key == GLFW_KEY_E)
{
ptr->editorEnabled ^= NV_FLOW_TRUE;
}
else if (key == GLFW_KEY_C)
{
ptr->captureEnabled ^= NV_FLOW_TRUE;
}
else if (key == GLFW_KEY_F11)
{
if (ptr->fullscreenState == 0)
{
GLFWmonitor* monitor = glfwLoader.p_glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwLoader.p_glfwGetVideoMode(monitor);
ptr->windowWidthOld = ptr->windowWidth;
ptr->windowHeightOld = ptr->windowHeight;
glfwLoader.p_glfwSetWindowMonitor(ptr->window, monitor, 0, 0, mode->width, mode->height, mode->refreshRate);
ptr->fullscreenState = 1;
}
else if (ptr->fullscreenState == 2)
{
glfwLoader.p_glfwSetWindowMonitor(ptr->window, nullptr,
(int)(ptr->windowWidth / 2 - ptr->windowWidthOld / 2),
(int)(ptr->windowHeight / 2 - ptr->windowHeightOld / 2),
(int)(ptr->windowWidthOld), (int)(ptr->windowHeightOld),
GLFW_DONT_CARE
);
ptr->fullscreenState = 3;
}
}
}
else if (action == GLFW_RELEASE)
{
if (key == GLFW_KEY_F11)
{
if (ptr->fullscreenState == 1)
{
ptr->fullscreenState = 2;
}
else if (ptr->fullscreenState == 3)
{
ptr->fullscreenState = 0;
}
}
}
if (!ImGui::GetIO().WantCaptureMouse)
{
NvFlowCameraAction nvfAction = eNvFlowCameraAction_unknown;
if (action == GLFW_PRESS)
{
nvfAction = eNvFlowCameraAction_down;
}
else if (action == GLFW_RELEASE)
{
nvfAction = eNvFlowCameraAction_up;
}
NvFlowCameraKey flowKey = eNvFlowCameraKey_unknown;
if (key == GLFW_KEY_UP)
{
flowKey = eNvFlowCameraKey_up;
}
else if (key == GLFW_KEY_DOWN)
{
flowKey = eNvFlowCameraKey_down;
}
else if (key == GLFW_KEY_LEFT)
{
flowKey = eNvFlowCameraKey_left;
}
else if (key == GLFW_KEY_RIGHT)
{
flowKey = eNvFlowCameraKey_right;
}
NvFlowCameraKeyUpdate(ptr->camera, flowKey, nvfAction);
}
}
// imgui always captures
{
if (action == GLFW_PRESS)
{
io.KeysDown[key] = true;
}
else if (action == GLFW_RELEASE)
{
io.KeysDown[key] = false;
}
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];
io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER];
}
}
void charInputCallback(GLFWwindow* win, uint32_t input)
{
auto ptr = (App*)glfwLoader.p_glfwGetWindowUserPointer(win);
ImGuiIO& io = ImGui::GetIO();
// imgui always captures
{
io.AddInputCharacter(input);
}
}
void mouseMoveCallback(GLFWwindow* win, double mouseX, double mouseY)
{
auto ptr = (App*)glfwLoader.p_glfwGetWindowUserPointer(win);
int x = int(mouseX);
int y = int(mouseY);
ptr->mouseX = x;
ptr->mouseY = y;
ptr->mouseYInv = ptr->windowHeight - 1 - y;
if (!ImGui::GetIO().WantCaptureMouse)
{
NvFlowCameraMouseUpdate(ptr->camera, eNvFlowCameraMouseButton_unknown, eNvFlowCameraAction_unknown, ptr->mouseX, ptr->mouseY, (int)(ptr->windowWidth), (int)(ptr->windowHeight));
}
}
void mouseButtonCallback(GLFWwindow* win, int button, int action, int modifiers)
{
auto ptr = (App*)glfwLoader.p_glfwGetWindowUserPointer(win);
if (!ImGui::GetIO().WantCaptureMouse)
{
NvFlowCameraAction nvfAction = eNvFlowCameraAction_unknown;
if (action == GLFW_PRESS)
{
nvfAction = eNvFlowCameraAction_down;
}
else if (action == GLFW_RELEASE)
{
nvfAction = eNvFlowCameraAction_up;
}
NvFlowCameraMouseButton nvfMouse = eNvFlowCameraMouseButton_unknown;
if (button == GLFW_MOUSE_BUTTON_LEFT)
{
nvfMouse = eNvFlowCameraMouseButton_left;
}
else if (button == GLFW_MOUSE_BUTTON_MIDDLE)
{
nvfMouse = eNvFlowCameraMouseButton_middle;
}
else if (button == GLFW_MOUSE_BUTTON_RIGHT)
{
nvfMouse = eNvFlowCameraMouseButton_right;
}
NvFlowCameraMouseUpdate(ptr->camera, nvfMouse, nvfAction, ptr->mouseX, ptr->mouseY, (int)ptr->windowWidth, (int)ptr->windowHeight);
}
// imgui
if (action == GLFW_PRESS && button >= 0 && button < 5)
{
ptr->mouseJustPressed[button] = NV_FLOW_TRUE;
}
}
void mouseWheelCallback(GLFWwindow* win, double scrollX, double scrollY)
{
auto ptr = (App*)glfwLoader.p_glfwGetWindowUserPointer(win);
// imgui
ImGuiIO& io = ImGui::GetIO();
io.MouseWheelH += (float)scrollX;
io.MouseWheel += (float)scrollY;
}
|
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/ImguiRenderer.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include "imgui.h"
#include "NvFlowLoader.h"
#include "ImguiRenderer.h"
#include "NvFlowUploadBuffer.h"
#include "NvFlowDynamicBuffer.h"
#include "shaders/ImguiParams.h"
#include "shaders/ImguiCS.hlsl.h"
#include "shaders/ImguiBuildCS.hlsl.h"
#include "shaders/ImguiTileCS.hlsl.h"
#include "shaders/ImguiTileCountCS.hlsl.h"
#include "shaders/ImguiTileScanCS.hlsl.h"
namespace NvFlowImguiRendererDefault
{
struct Renderer
{
NvFlowContextInterface contextInterface = {};
ImguiCS_Pipeline imguiCS = {};
ImguiBuildCS_Pipeline imguiBuildCS = {};
ImguiTileCS_Pipeline imguiTileCS = {};
ImguiTileCountCS_Pipeline imguiTileCountCS = {};
ImguiTileScanCS_Pipeline imguiTileScanCS = {};
NvFlowUploadBuffer vertexPosTexCoordBuffer = {};
NvFlowUploadBuffer vertexColorBuffer = {};
NvFlowUploadBuffer indicesBuffer = {};
NvFlowUploadBuffer drawCmdsBuffer = {};
NvFlowUploadBuffer constantBuffer = {};
NvFlowUploadBuffer textureUpload = {};
NvFlowTexture* textureDevice = nullptr;
NvFlowSampler* samplerLinear = nullptr;
NvFlowDynamicBuffer treeBuffer = {};
NvFlowDynamicBuffer tileCountBuffer = {};
NvFlowDynamicBuffer triangleBuffer = {};
NvFlowDynamicBuffer triangleRangeBuffer = {};
NvFlowBuffer* totalCountBuffer = nullptr;
};
NV_FLOW_CAST_PAIR(NvFlowImguiRenderer, Renderer)
NvFlowImguiRenderer* create(
NvFlowContextInterface* contextInterface,
NvFlowContext* context,
unsigned char* pixels,
int texWidth,
int texHeight
)
{
auto ptr = new Renderer();
NvFlowContextInterface_duplicate(&ptr->contextInterface, contextInterface);
ImguiCS_init(&ptr->contextInterface, context, &ptr->imguiCS);
ImguiBuildCS_init(&ptr->contextInterface, context, &ptr->imguiBuildCS);
ImguiTileCS_init(&ptr->contextInterface, context, &ptr->imguiTileCS);
ImguiTileCountCS_init(&ptr->contextInterface, context, &ptr->imguiTileCountCS);
ImguiTileScanCS_init(&ptr->contextInterface, context, &ptr->imguiTileScanCS);
NvFlowBufferUsageFlags bufferUsage = eNvFlowBufferUsage_structuredBuffer | eNvFlowBufferUsage_bufferCopySrc;
NvFlowUploadBuffer_init(&ptr->contextInterface, context, &ptr->vertexPosTexCoordBuffer, bufferUsage, eNvFlowFormat_unknown, sizeof(NvFlowFloat4));
NvFlowUploadBuffer_init(&ptr->contextInterface, context, &ptr->vertexColorBuffer, bufferUsage, eNvFlowFormat_unknown, sizeof(NvFlowUint));
NvFlowUploadBuffer_init(&ptr->contextInterface, context, &ptr->indicesBuffer, bufferUsage, eNvFlowFormat_unknown, sizeof(NvFlowUint));
NvFlowUploadBuffer_init(&ptr->contextInterface, context, &ptr->drawCmdsBuffer, bufferUsage, eNvFlowFormat_unknown, sizeof(ImguiRendererDrawCmd));
NvFlowUploadBuffer_init(&ptr->contextInterface, context, &ptr->constantBuffer, eNvFlowBufferUsage_constantBuffer, eNvFlowFormat_unknown, 0u);
NvFlowUploadBuffer_init(&ptr->contextInterface, context, &ptr->textureUpload, eNvFlowBufferUsage_bufferCopySrc, eNvFlowFormat_unknown, 0u);
NvFlowUint numBytes = NvFlowUint(texWidth * texHeight * 4u * sizeof(unsigned char));
auto mapped = (unsigned char*)NvFlowUploadBuffer_map(context, &ptr->textureUpload, numBytes);
for (NvFlowUint idx = 0u; idx < numBytes; idx++)
{
mapped[idx] = pixels[idx];
}
NvFlowBufferTransient* bufferTransient = NvFlowUploadBuffer_unmap(context, &ptr->textureUpload);
NvFlowTextureDesc texDesc = {};
texDesc.textureType = eNvFlowTextureType_2d;
texDesc.usageFlags = eNvFlowTextureUsage_textureCopyDst | eNvFlowTextureUsage_texture;
texDesc.format = eNvFlowFormat_r8g8b8a8_unorm;
texDesc.width = texWidth;
texDesc.height = texHeight;
texDesc.depth = 1u;
texDesc.mipLevels = 1u;
texDesc.optimizedClearValue = NvFlowFloat4{0.f, 0.f, 0.f, 0.f};
ptr->textureDevice = ptr->contextInterface.createTexture(context, &texDesc);
NvFlowSamplerDesc samplerDesc = {};
samplerDesc.filterMode = eNvFlowSamplerFilterMode_linear;
samplerDesc.addressModeU = eNvFlowSamplerAddressMode_wrap;
samplerDesc.addressModeV = eNvFlowSamplerAddressMode_wrap;
samplerDesc.addressModeW = eNvFlowSamplerAddressMode_wrap;
ptr->samplerLinear = ptr->contextInterface.createSampler(context, &samplerDesc);
NvFlowTextureTransient* textureTransient = ptr->contextInterface.registerTextureAsTransient(context, ptr->textureDevice);
NvFlowPassCopyBufferToTextureParams copyParams = {};
copyParams.bufferOffset = 0llu;
copyParams.bufferRowPitch = texWidth * 4u * sizeof(unsigned char);
copyParams.bufferDepthPitch = numBytes;
copyParams.textureMipLevel = 0u;
copyParams.textureOffset = NvFlowUint3{0u, 0u, 0u};
copyParams.textureExtent = NvFlowUint3{NvFlowUint(texWidth), NvFlowUint(texHeight), 1u};
copyParams.src = bufferTransient;
copyParams.dst = textureTransient;
copyParams.debugLabel = "ImguiUploadTexture";
ptr->contextInterface.addPassCopyBufferToTexture(context, ©Params);
NvFlowBufferUsageFlags deviceBufUsage = eNvFlowBufferUsage_rwStructuredBuffer | eNvFlowBufferUsage_structuredBuffer;
NvFlowDynamicBuffer_init(&ptr->contextInterface, context, &ptr->treeBuffer, deviceBufUsage, eNvFlowFormat_unknown, sizeof(NvFlowInt4));
NvFlowDynamicBuffer_init(&ptr->contextInterface, context, &ptr->tileCountBuffer, deviceBufUsage, eNvFlowFormat_unknown, sizeof(NvFlowUint));
NvFlowDynamicBuffer_init(&ptr->contextInterface, context, &ptr->triangleBuffer, deviceBufUsage, eNvFlowFormat_unknown, sizeof(NvFlowUint));
NvFlowDynamicBuffer_init(&ptr->contextInterface, context, &ptr->triangleRangeBuffer, deviceBufUsage, eNvFlowFormat_unknown, sizeof(NvFlowUint2));
NvFlowBufferDesc totalCountDesc = {};
totalCountDesc.usageFlags = deviceBufUsage;
totalCountDesc.format = eNvFlowFormat_unknown;
totalCountDesc.structureStride = sizeof(NvFlowUint);
totalCountDesc.sizeInBytes = 1024u * sizeof(NvFlowUint);
ptr->totalCountBuffer = ptr->contextInterface.createBuffer(context, eNvFlowMemoryType_readback, &totalCountDesc);
return cast(ptr);
}
void destroy(NvFlowContext* context, NvFlowImguiRenderer* renderer)
{
auto ptr = cast(renderer);
NvFlowUploadBuffer_destroy(context, &ptr->vertexPosTexCoordBuffer);
NvFlowUploadBuffer_destroy(context, &ptr->vertexColorBuffer);
NvFlowUploadBuffer_destroy(context, &ptr->indicesBuffer);
NvFlowUploadBuffer_destroy(context, &ptr->drawCmdsBuffer);
NvFlowUploadBuffer_destroy(context, &ptr->constantBuffer);
NvFlowUploadBuffer_destroy(context, &ptr->textureUpload);
ptr->contextInterface.destroyTexture(context, ptr->textureDevice);
ptr->contextInterface.destroySampler(context, ptr->samplerLinear);
NvFlowDynamicBuffer_destroy(context, &ptr->treeBuffer);
NvFlowDynamicBuffer_destroy(context, &ptr->tileCountBuffer);
NvFlowDynamicBuffer_destroy(context, &ptr->triangleBuffer);
NvFlowDynamicBuffer_destroy(context, &ptr->triangleRangeBuffer);
ptr->contextInterface.destroyBuffer(context, ptr->totalCountBuffer);
ImguiCS_destroy(context, &ptr->imguiCS);
ImguiBuildCS_destroy(context, &ptr->imguiBuildCS);
ImguiTileCS_destroy(context, &ptr->imguiTileCS);
ImguiTileCountCS_destroy(context, &ptr->imguiTileCountCS);
ImguiTileScanCS_destroy(context, &ptr->imguiTileScanCS);
delete ptr;
}
void render(NvFlowContext* context, NvFlowImguiRenderer* renderer, ImDrawData* drawData, NvFlowUint width, NvFlowUint height, NvFlowTextureTransient* colorIn, NvFlowTextureTransient* colorOut)
{
auto ptr = cast(renderer);
NvFlowUint numVertices = drawData->TotalVtxCount;
NvFlowUint numIndices = drawData->TotalIdxCount;
NvFlowUint numDrawCmds = 0u;
for (int listIdx = 0; listIdx < drawData->CmdListsCount; listIdx++)
{
numDrawCmds += drawData->CmdLists[listIdx]->CmdBuffer.Size;
}
NvFlowUint numTriangles = numIndices / 3u;
NvFlowUint trianglesPerBlock = 256u;
NvFlowUint numBlocks = (numTriangles + trianglesPerBlock - 1u) / trianglesPerBlock;
NvFlowUint64 treeNumBytes = numBlocks * (1u + 4u + 16u + 64u + 256u) * sizeof(NvFlowInt4);
NvFlowDynamicBuffer_resize(context, &ptr->treeBuffer, treeNumBytes);
NvFlowUint tileDimBits = 4u;
NvFlowUint tileDim = 1u << tileDimBits;
NvFlowUint tileGridDim_x = (width + tileDim - 1u) / tileDim;
NvFlowUint tileGridDim_y = (height + tileDim - 1u) / tileDim;
NvFlowUint tileGridDim_xy = tileGridDim_x * tileGridDim_y;
NvFlowUint numTileBuckets = (tileGridDim_xy + 255u) / 256u;
NvFlowUint numTileBucketPasses = (numTileBuckets + 255u) / 256u;
NvFlowUint64 tileCountNumBytes = tileGridDim_x * tileGridDim_y * 3u * sizeof(NvFlowUint);
NvFlowDynamicBuffer_resize(context, &ptr->tileCountBuffer, tileCountNumBytes);
NvFlowUint maxTriangles = 4u * 256u * 1024u;
NvFlowUint64 triangleBufferNumBytes = maxTriangles * sizeof(NvFlowUint);
NvFlowDynamicBuffer_resize(context, &ptr->triangleBuffer, triangleBufferNumBytes);
NvFlowUint64 triangleRangeBufferNumBytes = tileGridDim_xy * sizeof(NvFlowUint2);
NvFlowDynamicBuffer_resize(context, &ptr->triangleRangeBuffer, triangleRangeBufferNumBytes);
NvFlowUint64 numBytesPosTex = (numVertices + 1u) * sizeof(NvFlowFloat4);
NvFlowUint64 numBytesColor = (numVertices + 1u) * sizeof(NvFlowUint);
NvFlowUint64 numBytesIndices = (numIndices + 1u) * sizeof(NvFlowUint);
NvFlowUint64 numBytesDrawCmds = (numDrawCmds + 1u) * sizeof(ImguiRendererDrawCmd);
auto mappedPosTex = (NvFlowFloat4*)NvFlowUploadBuffer_map(context, &ptr->vertexPosTexCoordBuffer, numBytesPosTex);
auto mappedColor = (NvFlowUint*)NvFlowUploadBuffer_map(context, &ptr->vertexColorBuffer, numBytesColor);
auto mappedIndices = (NvFlowUint*)NvFlowUploadBuffer_map(context, &ptr->indicesBuffer, numBytesIndices);
auto mappedDrawCmds = (ImguiRendererDrawCmd*)NvFlowUploadBuffer_map(context, &ptr->drawCmdsBuffer, numBytesDrawCmds);
auto mapped = (ImguiRendererParams*)NvFlowUploadBuffer_map(context, &ptr->constantBuffer, sizeof(ImguiRendererParams));
NvFlowUint vertexOffset = 0u;
NvFlowUint indexOffset = 0u;
NvFlowUint drawCmdOffset = 0u;
for (int cmdListIdx = 0u; cmdListIdx < drawData->CmdListsCount; cmdListIdx++)
{
ImDrawList* cmdList = drawData->CmdLists[cmdListIdx];
// copy vertices
for (int vertIdx = 0; vertIdx < cmdList->VtxBuffer.Size; vertIdx++)
{
NvFlowUint writeIdx = vertIdx + vertexOffset;
mappedPosTex[writeIdx].x = cmdList->VtxBuffer[vertIdx].pos.x;
mappedPosTex[writeIdx].y = cmdList->VtxBuffer[vertIdx].pos.y;
mappedPosTex[writeIdx].z = cmdList->VtxBuffer[vertIdx].uv.x;
mappedPosTex[writeIdx].w = cmdList->VtxBuffer[vertIdx].uv.y;
mappedColor[writeIdx] = cmdList->VtxBuffer[vertIdx].col;
}
// copy indices
for (int indexIdx = 0; indexIdx < cmdList->IdxBuffer.Size; indexIdx++)
{
NvFlowUint writeIdx = indexIdx + indexOffset;
mappedIndices[writeIdx] = cmdList->IdxBuffer[indexIdx] + vertexOffset; // apply vertex offset on CPU
}
// copy drawCmds
NvFlowUint indexOffsetLocal = indexOffset;
for (int drawCmdIdx = 0; drawCmdIdx < cmdList->CmdBuffer.Size; drawCmdIdx++)
{
NvFlowUint writeIdx = drawCmdIdx + drawCmdOffset;
auto& dst = mappedDrawCmds[writeIdx];
auto& src = cmdList->CmdBuffer[drawCmdIdx];
dst.clipRect.x = src.ClipRect.x;
dst.clipRect.y = src.ClipRect.y;
dst.clipRect.z = src.ClipRect.z;
dst.clipRect.w = src.ClipRect.w;
dst.elemCount = src.ElemCount;
dst.userTexture = *((NvFlowUint*)(&src.TextureId));
dst.vertexOffset = 0u; // vertex offset already applied
dst.indexOffset = indexOffsetLocal;
indexOffsetLocal += src.ElemCount;
}
vertexOffset += NvFlowUint(cmdList->VtxBuffer.Size);
indexOffset += NvFlowUint(cmdList->IdxBuffer.Size);
drawCmdOffset += NvFlowUint(cmdList->CmdBuffer.Size);
}
mapped->numVertices = numVertices;
mapped->numIndices = numIndices;
mapped->numDrawCmds = numDrawCmds;
mapped->numBlocks = numBlocks;
mapped->width = float(width);
mapped->height = float(height);
mapped->widthInv = 1.f / float(width);
mapped->heightInv = 1.f / float(height);
mapped->tileGridDim_x = tileGridDim_x;
mapped->tileGridDim_y = tileGridDim_y;
mapped->tileGridDim_xy = tileGridDim_xy;
mapped->tileDimBits = tileDimBits;
mapped->maxTriangles = maxTriangles;
mapped->tileNumTrianglesOffset = 0u;
mapped->tileLocalScanOffset = tileGridDim_xy;
mapped->tileLocalTotalOffset = 2u * tileGridDim_xy;
mapped->tileGlobalScanOffset = 2u * tileGridDim_xy + numTileBuckets;
mapped->numTileBuckets = numTileBuckets;
mapped->numTileBucketPasses = numTileBucketPasses;
mapped->pad3 = 0u;
//NvFlowBufferTransient* vertexPosTexCoordTransient = NvFlowUploadBuffer_unmapDevice(context, &ptr->vertexPosTexCoordBuffer, 0llu, numBytesPosTex);
//NvFlowBufferTransient* vertexColorTransient = NvFlowUploadBuffer_unmapDevice(context, &ptr->vertexColorBuffer, 0llu, numBytesColor);
//NvFlowBufferTransient* indicesTransient = NvFlowUploadBuffer_unmapDevice(context, &ptr->indicesBuffer, 0llu, numBytesIndices);
//NvFlowBufferTransient* drawCmdsInTransient = NvFlowUploadBuffer_unmapDevice(context, &ptr->drawCmdsBuffer, 0llu, numBytesDrawCmds);
//NvFlowBufferTransient* paramsInTransient = NvFlowUploadBuffer_unmap(context, &ptr->constantBuffer);
NvFlowBufferTransient* vertexPosTexCoordTransient = NvFlowUploadBuffer_unmap(context, &ptr->vertexPosTexCoordBuffer);
NvFlowBufferTransient* vertexColorTransient = NvFlowUploadBuffer_unmap(context, &ptr->vertexColorBuffer);
NvFlowBufferTransient* indicesTransient = NvFlowUploadBuffer_unmap(context, &ptr->indicesBuffer);
NvFlowBufferTransient* drawCmdsInTransient = NvFlowUploadBuffer_unmap(context, &ptr->drawCmdsBuffer);
NvFlowBufferTransient* paramsInTransient = NvFlowUploadBuffer_unmap(context, &ptr->constantBuffer);
NvFlowTextureTransient* textureTransient = ptr->contextInterface.registerTextureAsTransient(context, ptr->textureDevice);
NvFlowBufferTransient* treeTransient = NvFlowDynamicBuffer_getTransient(context, &ptr->treeBuffer);
NvFlowBufferTransient* tileCountTransient = NvFlowDynamicBuffer_getTransient(context, &ptr->tileCountBuffer);
NvFlowBufferTransient* triangleTransient = NvFlowDynamicBuffer_getTransient(context, &ptr->triangleBuffer);
NvFlowBufferTransient* triangleRangeTransient = NvFlowDynamicBuffer_getTransient(context, &ptr->triangleRangeBuffer);
auto totalCountMapped = (NvFlowUint*)ptr->contextInterface.mapBuffer(context, ptr->totalCountBuffer);
ptr->contextInterface.unmapBuffer(context, ptr->totalCountBuffer);
NvFlowBufferTransient* totalCountTransient = ptr->contextInterface.registerBufferAsTransient(context, ptr->totalCountBuffer);
// build acceleration structure
{
NvFlowUint3 gridDim = {
numBlocks,
1u,
1u
};
ImguiBuildCS_PassParams passParams = {};
passParams.paramsIn = paramsInTransient;
passParams.vertexPosTexCoordIn = vertexPosTexCoordTransient;
passParams.vertexColorIn = vertexColorTransient;
passParams.indicesIn = indicesTransient;
passParams.drawCmdsIn = drawCmdsInTransient;
passParams.treeOut = treeTransient;
ImguiBuildCS_addPassCompute(context, &ptr->imguiBuildCS, gridDim, &passParams);
}
// count triangles per tile
{
NvFlowUint3 gridDim = {
(tileGridDim_xy + 255u) / 256u,
1u,
1u
};
ImguiTileCountCS_PassParams passParams = {};
passParams.paramsIn = paramsInTransient;
passParams.treeIn = treeTransient;
passParams.tileCountOut = tileCountTransient;
ImguiTileCountCS_addPassCompute(context, &ptr->imguiTileCountCS, gridDim, &passParams);
}
// scan buckets
{
NvFlowUint3 gridDim = {
1u,
1u,
1u
};
ImguiTileScanCS_PassParams passParams = {};
passParams.paramsIn = paramsInTransient;
passParams.tileCountOut = tileCountTransient;
passParams.totalCountOut = totalCountTransient;
ImguiTileScanCS_addPassCompute(context, &ptr->imguiTileScanCS, gridDim, &passParams);
}
// generate tile data
{
NvFlowUint3 gridDim = {
(tileGridDim_xy + 255u) / 256u,
1u,
1u
};
ImguiTileCS_PassParams passParams = {};
passParams.paramsIn = paramsInTransient;
passParams.treeIn = treeTransient;
passParams.tileCountIn = tileCountTransient;
passParams.drawCmdsIn = drawCmdsInTransient;
passParams.triangleOut = triangleTransient;
passParams.triangleRangeOut = triangleRangeTransient;
ImguiTileCS_addPassCompute(context, &ptr->imguiTileCS, gridDim, &passParams);
}
// render
{
NvFlowUint3 gridDim = {
(width + 7u) / 8u,
(height + 7u) / 8u,
1u
};
ImguiCS_PassParams passParams = {};
passParams.paramsIn = paramsInTransient;
passParams.vertexPosTexCoordIn = vertexPosTexCoordTransient;
passParams.vertexColorIn = vertexColorTransient;
passParams.indicesIn = indicesTransient;
passParams.drawCmdsIn = drawCmdsInTransient;
passParams.textureIn = textureTransient;
passParams.samplerIn = ptr->samplerLinear;
passParams.triangleIn = triangleTransient;
passParams.triangleRangeIn = triangleRangeTransient;
passParams.colorIn = colorIn;
passParams.colorOut = colorOut;
ImguiCS_addPassCompute(context, &ptr->imguiCS, gridDim, &passParams);
}
}
}
NvFlowImguiRendererInterface* NvFlowGetImguiRendererInterface()
{
using namespace NvFlowImguiRendererDefault;
static NvFlowImguiRendererInterface iface = { NV_FLOW_REFLECT_INTERFACE_INIT(NvFlowImguiRendererInterface) };
iface.create = create;
iface.destroy = destroy;
iface.render = render;
return &iface;
} |
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/shaders/ImguiParams.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include "NvFlowShaderTypes.h"
struct ImguiRendererParams
{
NvFlowUint numVertices;
NvFlowUint numIndices;
NvFlowUint numDrawCmds;
NvFlowUint numBlocks;
float width;
float height;
float widthInv;
float heightInv;
NvFlowUint tileGridDim_x;
NvFlowUint tileGridDim_y;
NvFlowUint tileGridDim_xy;
NvFlowUint tileDimBits;
NvFlowUint maxTriangles;
NvFlowUint tileNumTrianglesOffset;
NvFlowUint tileLocalScanOffset;
NvFlowUint tileLocalTotalOffset;
NvFlowUint tileGlobalScanOffset;
NvFlowUint numTileBuckets;
NvFlowUint numTileBucketPasses;
NvFlowUint pad3;
};
struct ImguiRendererDrawCmd
{
NvFlowFloat4 clipRect;
NvFlowUint elemCount;
NvFlowUint userTexture;
NvFlowUint vertexOffset;
NvFlowUint indexOffset;
}; |
NVIDIA-Omniverse/PhysX/flow/source/nvfloweditor/shaders/ShapeParams.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include "NvFlowShaderTypes.h"
struct ShapeRendererParams
{
NvFlowFloat4x4 projection;
NvFlowFloat4x4 view;
NvFlowFloat4x4 projectionInv;
NvFlowFloat4x4 viewInv;
NvFlowFloat4 rayDir00;
NvFlowFloat4 rayDir10;
NvFlowFloat4 rayDir01;
NvFlowFloat4 rayDir11;
NvFlowFloat4 rayOrigin00;
NvFlowFloat4 rayOrigin10;
NvFlowFloat4 rayOrigin01;
NvFlowFloat4 rayOrigin11;
float width;
float height;
float widthInv;
float heightInv;
NvFlowUint numSpheres;
float clearDepth;
NvFlowUint isReverseZ;
NvFlowUint pad3;
NvFlowFloat4 clearColor;
}; |
NVIDIA-Omniverse/PhysX/flow/include/nvflow/NvFlowReflect.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#ifndef NV_FLOW_REFLECT_H
#define NV_FLOW_REFLECT_H
#include "NvFlowTypes.h"
/// ************************* NvFlowReflect **********************************
NV_FLOW_INLINE int NvFlowReflectStringCompare(const char* a, const char* b)
{
a = a ? a : "\0";
b = b ? b : "\0";
int idx = 0;
while (a[idx] || b[idx])
{
if (a[idx] != b[idx])
{
return a[idx] < b[idx] ? -1 : +1;
}
idx++;
}
return 0;
}
NV_FLOW_INLINE const char* NvFlowTypeToString(NvFlowType type)
{
switch (type)
{
case eNvFlowType_unknown: return "unknown";
case eNvFlowType_void: return "void";
case eNvFlowType_function: return "function";
case eNvFlowType_struct: return "struct";
case eNvFlowType_int: return "int";
case eNvFlowType_int2: return "int2";
case eNvFlowType_int3: return "int3";
case eNvFlowType_int4: return "int4";
case eNvFlowType_uint: return "uint";
case eNvFlowType_uint2: return "uint2";
case eNvFlowType_uint3: return "uint3";
case eNvFlowType_uint4: return "uint4";
case eNvFlowType_float: return "float";
case eNvFlowType_float2: return "float2";
case eNvFlowType_float3: return "float3";
case eNvFlowType_float4: return "float4";
case eNvFlowType_float4x4: return "float4x4";
case eNvFlowType_bool32: return "bool32";
case eNvFlowType_uint8: return "uint8";
case eNvFlowType_uint16: return "uint16";
case eNvFlowType_uint64: return "uint64";
case eNvFlowType_char: return "char";
case eNvFlowType_double: return "double";
default: return "unknown";
}
}
NV_FLOW_INLINE NvFlowType NvFlowTypeFromString(const char* name)
{
if (NvFlowReflectStringCompare(name, "unknown") == 0) { return eNvFlowType_unknown; }
else if (NvFlowReflectStringCompare(name, "struct") == 0) { return eNvFlowType_struct; }
else if (NvFlowReflectStringCompare(name, "void") == 0) { return eNvFlowType_void; }
else if (NvFlowReflectStringCompare(name, "function") == 0) { return eNvFlowType_function; }
else if (NvFlowReflectStringCompare(name, "int") == 0) { return eNvFlowType_int; }
else if (NvFlowReflectStringCompare(name, "int2") == 0) { return eNvFlowType_int2; }
else if (NvFlowReflectStringCompare(name, "int3") == 0) { return eNvFlowType_int3; }
else if (NvFlowReflectStringCompare(name, "int4") == 0) { return eNvFlowType_int4; }
else if (NvFlowReflectStringCompare(name, "uint") == 0) { return eNvFlowType_uint; }
else if (NvFlowReflectStringCompare(name, "uint2") == 0) { return eNvFlowType_uint2; }
else if (NvFlowReflectStringCompare(name, "uint3") == 0) { return eNvFlowType_uint3; }
else if (NvFlowReflectStringCompare(name, "uint4") == 0) { return eNvFlowType_uint4; }
else if (NvFlowReflectStringCompare(name, "float") == 0) { return eNvFlowType_float; }
else if (NvFlowReflectStringCompare(name, "float2") == 0) { return eNvFlowType_float2; }
else if (NvFlowReflectStringCompare(name, "float3") == 0) { return eNvFlowType_float3; }
else if (NvFlowReflectStringCompare(name, "float4") == 0) { return eNvFlowType_float4; }
else if (NvFlowReflectStringCompare(name, "float4x4") == 0) { return eNvFlowType_float4x4; }
else if (NvFlowReflectStringCompare(name, "bool32") == 0) { return eNvFlowType_bool32; }
else if (NvFlowReflectStringCompare(name, "uint8") == 0) { return eNvFlowType_uint8; }
else if (NvFlowReflectStringCompare(name, "uint16") == 0) { return eNvFlowType_uint16; }
else if (NvFlowReflectStringCompare(name, "uint64") == 0) { return eNvFlowType_uint64; }
else if (NvFlowReflectStringCompare(name, "char") == 0) { return eNvFlowType_char; }
else if (NvFlowReflectStringCompare(name, "double") == 0) { return eNvFlowType_double; }
else return eNvFlowType_unknown;
}
NV_FLOW_INLINE void NvFlowReflectMemcpy(void* dst, const void* src, NvFlowUint64 numBytes)
{
for (NvFlowUint64 byteIdx = 0u; byteIdx < numBytes; byteIdx++)
{
((NvFlowUint8*)dst)[byteIdx] = ((const NvFlowUint8*)src)[byteIdx];
}
}
NV_FLOW_INLINE void NvFlowReflectClear(void* dst, NvFlowUint64 numBytes)
{
for (NvFlowUint64 byteIdx = 0u; byteIdx < numBytes; byteIdx++)
{
((NvFlowUint8*)dst)[byteIdx] = 0;
}
}
typedef NvFlowUint NvFlowReflectHintFlags;
typedef enum NvFlowReflectHint
{
eNvFlowReflectHint_none = 0x00,
eNvFlowReflectHint_transient = 0x00000001, // Hint to not serialize
eNvFlowReflectHint_noEdit = 0x00000002, // Hint to not expose to editor
eNvFlowReflectHint_transientNoEdit = 0x00000003,
eNvFlowReflectHint_resource = 0x0000000C, // Mask for resource hints
eNvFlowReflectHint_asset = 0x0000000C, // Hint to serialize as external asset, instead of inlined
eNvFlowReflectHint_bufferId = 0x00000004, // Hint to treat NvFlowUint64 as bufferId, allowing conversion from paths to ids
eNvFlowReflectHint_textureId = 0x00000008, // Hint to treat NvFlowUint64 as textureId, allowing conversion from paths to ids
eNvFlowReflectHint_pinEnabled = 0x00010000,
eNvFlowReflectHint_pinGlobal = 0x00020000,
eNvFlowReflectHint_pinEnabledGlobal = 0x00030000,
eNvFlowReflectHint_pinMutable = 0x00040000,
eNvFlowReflectHint_pinEnabledMutable = 0x00050000,
eNvFlowReflectHint_pinGroup = 0x00080000,
eNvFlowReflectHint_maxEnum = 0x7FFFFFFF
}NvFlowReflectHint;
typedef NvFlowUint NvFlowReflectModeFlags;
typedef enum NvFlowReflectMode
{
eNvFlowReflectMode_value = 0x00,
eNvFlowReflectMode_pointer = 0x01,
eNvFlowReflectMode_array = 0x02,
eNvFlowReflectMode_pointerArray = 0x03,
eNvFlowReflectMode_valueVersioned = 0x04,
eNvFlowReflectMode_pointerVersioned = 0x05,
eNvFlowReflectMode_arrayVersioned = 0x06,
eNvFlowReflectMode_pointerArrayVersioned = 0x07,
eNvFlowReflectMode_maxEnum = 0x7FFFFFFF
}NvFlowReflectMode;
struct NvFlowReflectDataType;
typedef struct NvFlowReflectDataType NvFlowReflectDataType;
typedef struct NvFlowReflectData
{
NvFlowReflectHintFlags reflectHints;
NvFlowReflectModeFlags reflectMode;
const NvFlowReflectDataType* dataType;
const char* name;
NvFlowUint64 dataOffset;
NvFlowUint64 arraySizeOffset;
NvFlowUint64 versionOffset;
const char* metadata;
}NvFlowReflectData;
typedef struct NvFlowReflectDataType
{
NvFlowType dataType;
NvFlowUint64 elementSize;
const char* structTypename;
const NvFlowReflectData* childReflectDatas;
NvFlowUint64 childReflectDataCount;
const void* defaultValue;
}NvFlowReflectDataType;
typedef void(NV_FLOW_ABI* NvFlowReflectProcess_t)(NvFlowUint8* data, const NvFlowReflectDataType* dataType, void* userdata);
NV_FLOW_INLINE void NvFlowReflectCopyByName(
void* dstData, const NvFlowReflectDataType* dstType,
const void* srcData, const NvFlowReflectDataType* srcType
)
{
NvFlowUint8* dstData8 = (NvFlowUint8*)dstData;
const NvFlowUint8* srcData8 = (const NvFlowUint8*)srcData;
// For safety, take min of elementSize
NvFlowUint64 safeCopySize = srcType->elementSize < dstType->elementSize ? srcType->elementSize : dstType->elementSize;
// Start with raw copy, to potential cover non-reflect data
NvFlowReflectMemcpy(dstData, srcData, safeCopySize);
// Single level copy by name, enough to cover interfaces
if (dstType != srcType)
{
NvFlowUint64 srcIdx = 0u;
for (NvFlowUint64 dstIdx = 0u; dstIdx < dstType->childReflectDataCount; dstIdx++)
{
for (NvFlowUint64 srcCount = 0u; srcCount < srcType->childReflectDataCount; srcCount++)
{
const NvFlowReflectData* childDst = dstType->childReflectDatas + dstIdx;
const NvFlowReflectData* childSrc = srcType->childReflectDatas + srcIdx;
if (childDst->name == childSrc->name ||
NvFlowReflectStringCompare(childDst->name, childSrc->name) == 0)
{
// only copy if not covered by bulk memcpy
if (childDst->dataOffset != childSrc->dataOffset)
{
NvFlowReflectMemcpy(
dstData8 + childDst->dataOffset,
srcData8 + childSrc->dataOffset,
(childDst->reflectMode & eNvFlowReflectMode_pointerArray) ? sizeof(void*) : childDst->dataType->elementSize
);
}
if (childDst->reflectMode & eNvFlowReflectMode_array)
{
if (childDst->arraySizeOffset != childSrc->arraySizeOffset)
{
NvFlowReflectMemcpy(
dstData8 + childDst->arraySizeOffset,
srcData8 + childSrc->arraySizeOffset,
sizeof(NvFlowUint64)
);
}
}
if (childDst->reflectMode & eNvFlowReflectMode_valueVersioned)
{
if (childDst->versionOffset != childSrc->versionOffset)
{
NvFlowReflectMemcpy(
dstData8 + childDst->versionOffset,
srcData8 + childSrc->versionOffset,
sizeof(NvFlowUint64)
);
}
}
srcCount = srcType->childReflectDataCount - 1u;
}
srcIdx++;
if (srcIdx >= srcType->childReflectDataCount)
{
srcIdx = 0u;
}
}
}
}
}
// Reflect blocks must start with #define NV_FLOW_REFLECT_TYPE typename
// And end with #undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_XSTR(X) NV_FLOW_REFLECT_STR(X)
#define NV_FLOW_REFLECT_STR(X) #X
#define NV_FLOW_REFLECT_XCONCAT(A, B) NV_FLOW_REFLECT_CONCAT(A, B)
#define NV_FLOW_REFLECT_CONCAT(A, B) A##B
#define NV_FLOW_REFLECT_VALIDATE(type) \
NV_FLOW_INLINE type* NV_FLOW_REFLECT_XCONCAT(type,_NvFlowValidatePtr)(const type* v) { return (type*)v; } \
NV_FLOW_INLINE type** NV_FLOW_REFLECT_XCONCAT(type,_NvFlowValidatePtrPtr)(const type* const * v) { return (type**)v; } \
NV_FLOW_INLINE type*** NV_FLOW_REFLECT_XCONCAT(type,_NvFlowValidatePtrPtrPtr)(const type*const *const * v) { return (type***)v; }
#if defined(__cplusplus)
#define NV_FLOW_REFLECT_VALIDATE_value(type, name) NV_FLOW_REFLECT_XCONCAT(type,_NvFlowValidatePtr)(&((NV_FLOW_REFLECT_TYPE*)0)->name)
#define NV_FLOW_REFLECT_VALIDATE_pointer(type, name) NV_FLOW_REFLECT_XCONCAT(type,_NvFlowValidatePtrPtr)(&((NV_FLOW_REFLECT_TYPE*)0)->name)
#define NV_FLOW_REFLECT_VALIDATE_array(type, name) NV_FLOW_REFLECT_XCONCAT(type,_NvFlowValidatePtrPtr)(&((NV_FLOW_REFLECT_TYPE*)0)->name)
#define NV_FLOW_REFLECT_VALIDATE_pointerArray(type, name) NV_FLOW_REFLECT_XCONCAT(type,_NvFlowValidatePtrPtrPtr)(&((NV_FLOW_REFLECT_TYPE*)0)->name)
#define NV_FLOW_REFLECT_VALIDATE_valueVersioned(type, name) NV_FLOW_REFLECT_XCONCAT(type,_NvFlowValidatePtr)(&((NV_FLOW_REFLECT_TYPE*)0)->name)
#define NV_FLOW_REFLECT_VALIDATE_pointerVersioned(type, name) NV_FLOW_REFLECT_XCONCAT(type,_NvFlowValidatePtrPtr)(&((NV_FLOW_REFLECT_TYPE*)0)->name)
#define NV_FLOW_REFLECT_VALIDATE_arrayVersioned(type, name) NV_FLOW_REFLECT_XCONCAT(type,_NvFlowValidatePtrPtr)(&((NV_FLOW_REFLECT_TYPE*)0)->name)
#define NV_FLOW_REFLECT_VALIDATE_pointerArrayVersioned(type, name) NV_FLOW_REFLECT_XCONCAT(type,_NvFlowValidatePtrPtrPtr)(&((NV_FLOW_REFLECT_TYPE*)0)->name)
#else
#define NV_FLOW_REFLECT_VALIDATE_value(type, name) (&((NV_FLOW_REFLECT_TYPE*)0)->name)
#define NV_FLOW_REFLECT_VALIDATE_pointer(type, name) (&((NV_FLOW_REFLECT_TYPE*)0)->name)
#define NV_FLOW_REFLECT_VALIDATE_array(type, name) (&((NV_FLOW_REFLECT_TYPE*)0)->name)
#define NV_FLOW_REFLECT_VALIDATE_pointerArray(type, name) (&((NV_FLOW_REFLECT_TYPE*)0)->name)
#define NV_FLOW_REFLECT_VALIDATE_valueVersioned(type, name) (&((NV_FLOW_REFLECT_TYPE*)0)->name)
#define NV_FLOW_REFLECT_VALIDATE_pointerVersioned(type, name) (&((NV_FLOW_REFLECT_TYPE*)0)->name)
#define NV_FLOW_REFLECT_VALIDATE_arrayVersioned(type, name) (&((NV_FLOW_REFLECT_TYPE*)0)->name)
#define NV_FLOW_REFLECT_VALIDATE_pointerArrayVersioned(type, name) (&((NV_FLOW_REFLECT_TYPE*)0)->name)
#endif
#define NV_FLOW_REFLECT_BUILTIN_IMPL(enumName, typeName) \
static const NvFlowReflectDataType NV_FLOW_REFLECT_XCONCAT(typeName,_NvFlowReflectDataType) = { enumName, sizeof(typeName), 0, 0, 0, 0 }; \
NV_FLOW_REFLECT_VALIDATE(typeName)
#define NV_FLOW_REFLECT_STRUCT_OPAQUE_IMPL(name) \
static const NvFlowReflectDataType NV_FLOW_REFLECT_XCONCAT(name,_NvFlowReflectDataType) = { eNvFlowType_struct, 0llu, #name, 0, 0, 0 }; \
NV_FLOW_REFLECT_VALIDATE(name)
#define NV_FLOW_REFLECT_BEGIN() \
static const NvFlowReflectData NV_FLOW_REFLECT_XCONCAT(NV_FLOW_REFLECT_TYPE,_reflectDatas)[] = {
#define NV_FLOW_REFLECT_END(defaultValue) \
}; \
static const NvFlowReflectDataType NV_FLOW_REFLECT_XCONCAT(NV_FLOW_REFLECT_TYPE,_NvFlowReflectDataType) = { \
eNvFlowType_struct, \
sizeof(NV_FLOW_REFLECT_TYPE), \
NV_FLOW_REFLECT_XSTR(NV_FLOW_REFLECT_TYPE), \
NV_FLOW_REFLECT_XCONCAT(NV_FLOW_REFLECT_TYPE,_reflectDatas), \
sizeof(NV_FLOW_REFLECT_XCONCAT(NV_FLOW_REFLECT_TYPE,_reflectDatas)) / sizeof(NvFlowReflectData), \
defaultValue \
}; \
NV_FLOW_REFLECT_VALIDATE(NV_FLOW_REFLECT_TYPE)
#define NV_FLOW_REFLECT_TYPE_ALIAS(SRC, DST) \
typedef SRC DST; \
static const NvFlowReflectDataType NV_FLOW_REFLECT_XCONCAT(DST,_NvFlowReflectDataType) = { \
eNvFlowType_struct, \
sizeof(SRC), \
#DST, \
NV_FLOW_REFLECT_XCONCAT(SRC,_reflectDatas), \
sizeof(NV_FLOW_REFLECT_XCONCAT(SRC,_reflectDatas)) / sizeof(NvFlowReflectData), \
&NV_FLOW_REFLECT_XCONCAT(SRC,_default) \
}; \
NV_FLOW_REFLECT_VALIDATE(DST)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_int, int)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_int2, NvFlowInt2)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_int3, NvFlowInt3)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_int4, NvFlowInt4)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_uint, NvFlowUint)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_uint2, NvFlowUint2)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_uint3, NvFlowUint3)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_uint4, NvFlowUint4)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_float, float)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_float2, NvFlowFloat2)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_float3, NvFlowFloat3)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_float4, NvFlowFloat4)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_float4x4, NvFlowFloat4x4)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_bool32, NvFlowBool32)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_uint8, NvFlowUint8)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_uint16, NvFlowUint16)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_uint64, NvFlowUint64)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_char, char)
NV_FLOW_REFLECT_BUILTIN_IMPL(eNvFlowType_double, double)
#if defined(__cplusplus)
#define NV_FLOW_REFLECT_SIZE_OFFSET(name_size) (NvFlowUint64)NV_FLOW_REFLECT_VALIDATE_value(NvFlowUint64, name_size)
#define NV_FLOW_REFLECT_VERSION_OFFSET(version) (NvFlowUint64)NV_FLOW_REFLECT_VALIDATE_value(NvFlowUint64, version)
#else
#define NV_FLOW_REFLECT_SIZE_OFFSET(name_size) (NvFlowUint64)(&((NV_FLOW_REFLECT_TYPE*)0)->name_size)
#define NV_FLOW_REFLECT_VERSION_OFFSET(version) (NvFlowUint64)(&((NV_FLOW_REFLECT_TYPE*)0)->version)
#endif
/// Builtin
#define NV_FLOW_REFLECT_GENERIC(reflectMode, type, name, ARRAY, VERSION, reflectHints, metadata) { \
reflectHints, \
NV_FLOW_REFLECT_XCONCAT(eNvFlowReflectMode_,reflectMode), \
&NV_FLOW_REFLECT_XCONCAT(type,_NvFlowReflectDataType), \
#name, \
(NvFlowUint64)NV_FLOW_REFLECT_XCONCAT(NV_FLOW_REFLECT_VALIDATE_,reflectMode)(type, name), \
ARRAY, \
VERSION, \
metadata \
},
#define NV_FLOW_REFLECT_VALUE(type, name, reflectHints, metadata) NV_FLOW_REFLECT_GENERIC(value, type, name, 0, 0, reflectHints, metadata)
#define NV_FLOW_REFLECT_POINTER(type, name, reflectHints, metadata) NV_FLOW_REFLECT_GENERIC(pointer, type, name, 0, 0, reflectHints, metadata)
#define NV_FLOW_REFLECT_ARRAY(type, name, name_size, reflectHints, metadata) NV_FLOW_REFLECT_GENERIC(array, type, name, NV_FLOW_REFLECT_SIZE_OFFSET(name_size), 0, reflectHints, metadata)
#define NV_FLOW_REFLECT_POINTER_ARRAY(type, name, name_size, reflectHints, metadata) NV_FLOW_REFLECT_GENERIC(pointerArray, type, name, NV_FLOW_REFLECT_SIZE_OFFSET(name_size), 0, reflectHints, metadata)
#define NV_FLOW_REFLECT_VALUE_VERSIONED(type, name, version, reflectHints, metadata) NV_FLOW_REFLECT_GENERIC(valueVersioned, type, name, 0, NV_FLOW_REFLECT_VERSION_OFFSET(version), reflectHints, metadata)
#define NV_FLOW_REFLECT_POINTER_VERSIONED(type, name, version, reflectHints, metadata) NV_FLOW_REFLECT_GENERIC(pointerVersioned, type, name, 0, NV_FLOW_REFLECT_VERSION_OFFSET(version), reflectHints, metadata)
#define NV_FLOW_REFLECT_ARRAY_VERSIONED(type, name, name_size, version, reflectHints, metadata) NV_FLOW_REFLECT_GENERIC(arrayVersioned, type, name, NV_FLOW_REFLECT_SIZE_OFFSET(name_size), NV_FLOW_REFLECT_VERSION_OFFSET(version), reflectHints, metadata)
#define NV_FLOW_REFLECT_POINTER_ARRAY_VERSIONED(type, name, name_size, version, reflectHints, metadata) NV_FLOW_REFLECT_GENERIC(pointerArrayVersioned, type, name, NV_FLOW_REFLECT_SIZE_OFFSET(name_size), NV_FLOW_REFLECT_VERSION_OFFSET(version), reflectHints, metadata)
/// Function Pointer
static const NvFlowReflectDataType function_NvFlowReflectDataType = { eNvFlowType_function, 0llu, 0, 0, 0, 0 };
#define NV_FLOW_REFLECT_FUNCTION_POINTER(name, reflectHints, metadata) { \
reflectHints, \
eNvFlowReflectMode_pointer, \
&function_NvFlowReflectDataType, \
#name, \
(NvFlowUint64)(&((NV_FLOW_REFLECT_TYPE*)0)->name), \
0, \
0, \
metadata \
},
/// Void
static const NvFlowReflectDataType void_NvFlowReflectDataType = { eNvFlowType_void, 0llu, 0, 0, 0, 0 };
#define NV_FLOW_REFLECT_VOID_POINTER(name, reflectHints, metadata) { \
reflectHints, \
eNvFlowReflectMode_pointer, \
&void_NvFlowReflectDataType, \
#name, \
(NvFlowUint64)(&((NV_FLOW_REFLECT_TYPE*)0)->name), \
0, \
0, \
metadata \
},
/// Enum
#define NV_FLOW_REFLECT_ENUM(name, reflectHints, metadata) { \
reflectHints, \
eNvFlowReflectMode_value, \
&NvFlowUint_NvFlowReflectDataType, \
#name, \
(NvFlowUint64)(&((NV_FLOW_REFLECT_TYPE*)0)->name), \
0, \
0, \
metadata \
},
#define NV_FLOW_REFLECT_INTERFACE() const NvFlowReflectDataType* interface_NvFlowReflectDataType
#define NV_FLOW_REFLECT_INTERFACE_INIT(type) &NV_FLOW_REFLECT_XCONCAT(type,_NvFlowReflectDataType)
#define NV_FLOW_REFLECT_INTERFACE_IMPL() \
NV_FLOW_INLINE void NV_FLOW_REFLECT_XCONCAT(NV_FLOW_REFLECT_TYPE,_duplicate)(NV_FLOW_REFLECT_TYPE* dst, const NV_FLOW_REFLECT_TYPE* src) \
{ \
dst->interface_NvFlowReflectDataType = &NV_FLOW_REFLECT_XCONCAT(NV_FLOW_REFLECT_TYPE,_NvFlowReflectDataType); \
NvFlowReflectCopyByName( \
dst, dst->interface_NvFlowReflectDataType, \
src, src->interface_NvFlowReflectDataType \
); \
}
#define NV_FLOW_REFLECT_TYPE NvFlowReflectData
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint, reflectHints, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, reflectMode, 0, 0)
NV_FLOW_REFLECT_VOID_POINTER(/*NvFlowReflectDataType,*/ dataType, 0, 0) // void to break circular reference
NV_FLOW_REFLECT_POINTER(char, name, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint64, dataOffset, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint64, arraySizeOffset, 0, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowReflectDataType
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_ENUM(dataType, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint64, elementSize, 0, 0)
NV_FLOW_REFLECT_POINTER(char, structTypename, 0, 0)
NV_FLOW_REFLECT_ARRAY(NvFlowReflectData, childReflectDatas, childReflectDataCount, 0, 0)
NV_FLOW_REFLECT_VOID_POINTER(defaultValue, 0, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_INLINE const char* NvFlowReflectTrimPrefix(const char* name)
{
if (name && name[0] == 'N')
{
name++;
}
if (name && name[0] == 'v')
{
name++;
}
return name;
}
#define NV_FLOW_CAST_PAIR(X, Y) \
NV_FLOW_INLINE X* cast(Y* ptr) { return (X*)ptr; } \
NV_FLOW_INLINE Y* cast(X* ptr) { return (Y*)ptr; } \
NV_FLOW_INLINE const X* cast(const Y* ptr) { return (X*)ptr; } \
NV_FLOW_INLINE const Y* cast(const X* ptr) { return (Y*)ptr; }
#define NV_FLOW_CAST_PAIR_NAMED(name, X, Y) \
NV_FLOW_INLINE X* name##_cast(Y* ptr) { return (X*)ptr; } \
NV_FLOW_INLINE Y* name##_cast(X* ptr) { return (Y*)ptr; } \
NV_FLOW_INLINE const X* name##_cast(const Y* ptr) { return (X*)ptr; } \
NV_FLOW_INLINE const Y* name##_cast(const X* ptr) { return (Y*)ptr; }
typedef struct NvFlowDatabaseTypeSnapshot
{
NvFlowUint64 version;
const NvFlowReflectDataType* dataType;
NvFlowUint8** instanceDatas;
NvFlowUint64 instanceCount;
}NvFlowDatabaseTypeSnapshot;
typedef struct NvFlowDatabaseSnapshot
{
NvFlowUint64 version;
NvFlowDatabaseTypeSnapshot* typeSnapshots;
NvFlowUint64 typeSnapshotCount;
}NvFlowDatabaseSnapshot;
NV_FLOW_INLINE void NvFlowDatabaseSnapshot_findType(const NvFlowDatabaseSnapshot* snapshot, const NvFlowReflectDataType* findDataType, NvFlowDatabaseTypeSnapshot** pSnapshot)
{
// try to find matching pointer first
for (NvFlowUint64 idx = 0u; idx < snapshot->typeSnapshotCount; idx++)
{
if (snapshot->typeSnapshots[idx].dataType == findDataType)
{
*pSnapshot = &snapshot->typeSnapshots[idx];
return;
}
}
// try to find by matching size and name
for (NvFlowUint64 idx = 0u; idx < snapshot->typeSnapshotCount; idx++)
{
if (snapshot->typeSnapshots[idx].dataType->elementSize == findDataType->elementSize &&
NvFlowReflectStringCompare(snapshot->typeSnapshots[idx].dataType->structTypename, findDataType->structTypename) == 0)
{
*pSnapshot = &snapshot->typeSnapshots[idx];
return;
}
}
*pSnapshot = 0;
}
NV_FLOW_INLINE void NvFlowDatabaseSnapshot_findTypeArray(const NvFlowDatabaseSnapshot* snapshot, const NvFlowReflectDataType* findDataType, void*** pData, NvFlowUint64* pCount)
{
NvFlowDatabaseTypeSnapshot* typeSnapshot = 0;
NvFlowDatabaseSnapshot_findType(snapshot, findDataType, &typeSnapshot);
if (typeSnapshot)
{
*pData = (void**)typeSnapshot->instanceDatas;
*pCount = typeSnapshot->instanceCount;
}
else
{
*pData = 0;
*pCount = 0llu;
}
}
#define NV_FLOW_DATABASE_SNAPSHOT_FIND_TYPE_ARRAY(snapshot, type) \
type** type##_elements = 0; \
NvFlowUint64 type##_elementCount = 0llu; \
NvFlowDatabaseSnapshot_findTypeArray(snapshot, &type##_NvFlowReflectDataType, (void***)&type##_elements, &type##_elementCount);
#endif
|
NVIDIA-Omniverse/PhysX/flow/include/nvflow/NvFlowTypes.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#ifndef NV_FLOW_TYPES_H
#define NV_FLOW_TYPES_H
#include "shaders/NvFlowShaderTypes.h"
//! \cond HIDDEN_SYMBOLS
#if defined(_WIN32)
#if defined(__cplusplus)
#define NV_FLOW_API extern "C" __declspec(dllexport)
#else
#define NV_FLOW_API __declspec(dllexport)
#endif
#define NV_FLOW_ABI __cdecl
#else
#if defined(__cplusplus)
#define NV_FLOW_API extern "C"
#else
#define NV_FLOW_API
#endif
#define NV_FLOW_ABI
#endif
#if defined(__cplusplus)
#define NV_FLOW_INLINE inline
#else
#define NV_FLOW_INLINE static
#endif
#if defined(_WIN32)
#define NV_FLOW_FORCE_INLINE inline __forceinline
#else
#define NV_FLOW_FORCE_INLINE inline __attribute__((always_inline))
#endif
// #define NV_FLOW_DEBUG_ALLOC
//! \endcond
typedef enum NvFlowLogLevel
{
eNvFlowLogLevel_error = 0,
eNvFlowLogLevel_warning = 1,
eNvFlowLogLevel_info = 2,
eNvFlowLogLevel_maxEnum = 0x7FFFFFFF
}NvFlowLogLevel;
typedef void(NV_FLOW_ABI* NvFlowLogPrint_t)(NvFlowLogLevel level, const char* format, ...);
#define NV_FLOW_FALSE 0
#define NV_FLOW_TRUE 1
typedef enum NvFlowType
{
eNvFlowType_unknown = 0,
eNvFlowType_void = 1,
eNvFlowType_function = 2,
eNvFlowType_struct = 3,
eNvFlowType_int = 4,
eNvFlowType_int2 = 5,
eNvFlowType_int3 = 6,
eNvFlowType_int4 = 7,
eNvFlowType_uint = 8,
eNvFlowType_uint2 = 9,
eNvFlowType_uint3 = 10,
eNvFlowType_uint4 = 11,
eNvFlowType_float = 12,
eNvFlowType_float2 = 13,
eNvFlowType_float3 = 14,
eNvFlowType_float4 = 15,
eNvFlowType_float4x4 = 16,
eNvFlowType_bool32 = 17,
eNvFlowType_uint8 = 18,
eNvFlowType_uint16 = 19,
eNvFlowType_uint64 = 20,
eNvFlowType_char = 21,
eNvFlowType_double = 22,
eNvFlowType_count = 23,
eNvFlowType_maxEnum = 0x7FFFFFFF
}NvFlowType;
typedef enum NvFlowContextApi
{
eNvFlowContextApi_abstract = 0,
eNvFlowContextApi_vulkan = 1,
eNvFlowContextApi_d3d12 = 2,
eNvFlowContextApi_cpu = 3,
eNvFlowContextApi_count = 4,
eNvFlowContextApi_maxEnum = 0x7FFFFFFF
}NvFlowContextApi;
typedef enum NvFlowFormat
{
eNvFlowFormat_unknown = 0,
eNvFlowFormat_r32g32b32a32_float = 1,
eNvFlowFormat_r32g32b32a32_uint = 2,
eNvFlowFormat_r32g32b32a32_sint = 3,
eNvFlowFormat_r32g32b32_float = 4,
eNvFlowFormat_r32g32b32_uint = 5,
eNvFlowFormat_r32g32b32_sint = 6,
eNvFlowFormat_r16g16b16a16_float = 7,
eNvFlowFormat_r16g16b16a16_unorm = 8,
eNvFlowFormat_r16g16b16a16_uint = 9,
eNvFlowFormat_r16g16b16a16_snorm = 10,
eNvFlowFormat_r16g16b16a16_sint = 11,
eNvFlowFormat_r32g32_float = 12,
eNvFlowFormat_r32g32_uint = 13,
eNvFlowFormat_r32g32_sint = 14,
eNvFlowFormat_r10g10b10a2_unorm = 15,
eNvFlowFormat_r10g10b10a2_uint = 16,
eNvFlowFormat_r11g11b10_float = 17,
eNvFlowFormat_r8g8b8a8_unorm = 18,
eNvFlowFormat_r8g8b8a8_unorm_srgb = 19,
eNvFlowFormat_r8g8b8a8_uint = 20,
eNvFlowFormat_r8g8b8a8_snorm = 21,
eNvFlowFormat_r8g8b8a8_sint = 22,
eNvFlowFormat_r16g16_float = 23,
eNvFlowFormat_r16g16_unorm = 24,
eNvFlowFormat_r16g16_uint = 25,
eNvFlowFormat_r16g16_snorm = 26,
eNvFlowFormat_r16g16_sint = 27,
eNvFlowFormat_r32_float = 28,
eNvFlowFormat_r32_uint = 29,
eNvFlowFormat_r32_sint = 30,
eNvFlowFormat_r8g8_unorm = 31,
eNvFlowFormat_r8g8_uint = 32,
eNvFlowFormat_r8g8_snorm = 33,
eNvFlowFormat_r8g8_sint = 34,
eNvFlowFormat_r16_float = 35,
eNvFlowFormat_r16_unorm = 36,
eNvFlowFormat_r16_uint = 37,
eNvFlowFormat_r16_snorm = 38,
eNvFlowFormat_r16_sint = 39,
eNvFlowFormat_r8_unorm = 40,
eNvFlowFormat_r8_uint = 41,
eNvFlowFormat_r8_snorm = 42,
eNvFlowFormat_r8_sint = 43,
eNvFlowFormat_b8g8r8a8_unorm = 44,
eNvFlowFormat_b8g8r8a8_unorm_srgb = 45,
eNvFlowFormat_count = 256,
eNvFlowFormat_maxEnum = 0x7FFFFFFF
}NvFlowFormat;
#endif |
NVIDIA-Omniverse/PhysX/flow/include/nvflow/NvFlow.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#ifndef NV_FLOW_H
#define NV_FLOW_H
#include "NvFlowContext.h"
#include "shaders/NvFlowShaderTypes.h"
/// ********************************* Op ***************************************
typedef enum NvFlowPinDir
{
eNvFlowPinDir_in = 0,
eNvFlowPinDir_out = 1,
eNvFlowPinDir_count = 2,
eNvFlowPinDir_maxEnum = 0x7FFFFFFF
}NvFlowPinDir;
struct NvFlowOp;
typedef struct NvFlowOp NvFlowOp;
struct NvFlowOpGraph;
typedef struct NvFlowOpGraph NvFlowOpGraph;
struct NvFlowOpGenericPinsIn;
typedef struct NvFlowOpGenericPinsIn NvFlowOpGenericPinsIn;
struct NvFlowOpGenericPinsOut;
typedef struct NvFlowOpGenericPinsOut NvFlowOpGenericPinsOut;
struct NvFlowOpExecuteGroup;
typedef struct NvFlowOpExecuteGroup NvFlowOpExecuteGroup;
NV_FLOW_REFLECT_STRUCT_OPAQUE_IMPL(NvFlowOpGraph)
typedef struct NvFlowOpExecuteGroupDesc
{
NvFlowOpExecuteGroup* group;
const char* name;
}NvFlowOpExecuteGroupDesc;
struct NvFlowOpInterface;
typedef struct NvFlowOpInterface NvFlowOpInterface;
typedef struct NvFlowOpInterface
{
NV_FLOW_REFLECT_INTERFACE();
const char* opTypename;
const NvFlowOpGraph* opGraph;
const NvFlowReflectDataType* pinsIn;
const NvFlowReflectDataType* pinsOut;
const NvFlowOpExecuteGroupDesc* executeGroupDescs;
NvFlowUint64 executeGroupCount;
NvFlowOp*(NV_FLOW_ABI* create)(const NvFlowOpInterface* opInterface, const NvFlowOpGenericPinsIn* in, NvFlowOpGenericPinsOut* out);
void(NV_FLOW_ABI* destroy)(NvFlowOp* op, const NvFlowOpGenericPinsIn* in, NvFlowOpGenericPinsOut* out);
void(NV_FLOW_ABI* execute)(NvFlowOp* op, const NvFlowOpGenericPinsIn* in, NvFlowOpGenericPinsOut* out);
void(NV_FLOW_ABI* executeGroup)(NvFlowOp* op, NvFlowOpExecuteGroup* group, const NvFlowOpGenericPinsIn* in, NvFlowOpGenericPinsOut* out);
}NvFlowOpInterface;
#define NV_FLOW_REFLECT_TYPE NvFlowOpInterface
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(char, opTypename, 0, 0)
NV_FLOW_REFLECT_POINTER(NvFlowOpGraph, opGraph, 0, 0)
NV_FLOW_REFLECT_POINTER(NvFlowReflectDataType, pinsIn, 0, 0)
NV_FLOW_REFLECT_POINTER(NvFlowReflectDataType, pinsOut, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(create, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroy, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(execute, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(executeGroup, 0, 0)
NV_FLOW_REFLECT_END(0)
NV_FLOW_REFLECT_INTERFACE_IMPL()
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_OP_IMPL(name, nameImpl) \
NvFlowOp* NvFlowOp_##nameImpl##_createGeneric(const NvFlowOpInterface* opInterface, const NvFlowOpGenericPinsIn* in, NvFlowOpGenericPinsOut* out) \
{ \
return (NvFlowOp*)nameImpl##_create(opInterface, (const name##PinsIn*)in, (name##PinsOut*)out); \
} \
void NvFlowOp_##nameImpl##_destroyGeneric(NvFlowOp* op, const NvFlowOpGenericPinsIn* in, NvFlowOpGenericPinsOut* out) \
{ \
nameImpl##_destroy((nameImpl*)op, (const name##PinsIn*)in, (name##PinsOut*)out); \
} \
void NvFlowOp_##nameImpl##_executeGeneric(NvFlowOp* op, const NvFlowOpGenericPinsIn* in, NvFlowOpGenericPinsOut* out) \
{ \
nameImpl##_execute((nameImpl*)op, (const name##PinsIn*)in, (name##PinsOut*)out); \
} \
void NvFlowOp_##nameImpl##_executeGroupGeneric(NvFlowOp* op, NvFlowOpExecuteGroup* group, const NvFlowOpGenericPinsIn* in, NvFlowOpGenericPinsOut* out) \
{ \
nameImpl##_execute((nameImpl*)op, (const name##PinsIn*)in, (name##PinsOut*)out); \
} \
NvFlowOpInterface* NvFlowOp_##nameImpl##_getOpInterface() \
{ \
static const NvFlowOpExecuteGroupDesc executeGroupDesc = {0, 0}; \
static NvFlowOpInterface iface = { \
NV_FLOW_REFLECT_INTERFACE_INIT(NvFlowOpInterface), \
#name, \
0, \
&name##PinsIn_NvFlowReflectDataType, \
&name##PinsOut_NvFlowReflectDataType, \
&executeGroupDesc, \
1u, \
NvFlowOp_##nameImpl##_createGeneric, \
NvFlowOp_##nameImpl##_destroyGeneric, \
NvFlowOp_##nameImpl##_executeGeneric, \
NvFlowOp_##nameImpl##_executeGroupGeneric \
}; \
return &iface; \
}
#define NV_FLOW_OP_TYPED(name) \
typedef struct name \
{ \
NvFlowOpInterface opInterface; \
NvFlowOp* op; \
}name; \
NV_FLOW_INLINE NvFlowBool32 NV_FLOW_REFLECT_XCONCAT(name,_init)(name* ptr, NvFlowOpInterface* opInterface, const NV_FLOW_REFLECT_XCONCAT(name,PinsIn)* pinsIn, NV_FLOW_REFLECT_XCONCAT(name,PinsOut)* pinsOut) \
{ \
NvFlowOpInterface_duplicate(&ptr->opInterface, opInterface); \
if (NvFlowReflectStringCompare(ptr->opInterface.opTypename, #name) == 0) \
{ \
ptr->op = ptr->opInterface.create(&ptr->opInterface, (const NvFlowOpGenericPinsIn*)pinsIn, (NvFlowOpGenericPinsOut*)pinsOut); \
return NV_FLOW_TRUE; \
} \
ptr->opInterface.create = 0; \
ptr->opInterface.destroy = 0; \
ptr->opInterface.execute = 0; \
ptr->opInterface.executeGroup = 0; \
ptr->op = 0; \
return NV_FLOW_FALSE; \
} \
NV_FLOW_INLINE void name##_destroy(name* ptr, const NV_FLOW_REFLECT_XCONCAT(name,PinsIn)* pinsIn, NV_FLOW_REFLECT_XCONCAT(name,PinsOut)* pinsOut) \
{ \
ptr->opInterface.destroy(ptr->op, (const NvFlowOpGenericPinsIn*)pinsIn, (NvFlowOpGenericPinsOut*)pinsOut); \
} \
NV_FLOW_INLINE void name##_execute(name* ptr, const NV_FLOW_REFLECT_XCONCAT(name,PinsIn)* pinsIn, NV_FLOW_REFLECT_XCONCAT(name,PinsOut)* pinsOut) \
{ \
ptr->opInterface.execute(ptr->op, (const NvFlowOpGenericPinsIn*)pinsIn, (NvFlowOpGenericPinsOut*)pinsOut); \
}
/// ********************************* OpGraph ***************************************
// Reserved, not in use yet
struct NvFlowOpGraphInterface;
typedef struct NvFlowOpGraphInterface NvFlowOpGraphInterface;
/// ********************************* OpRuntime ***************************************
// Reserved, not in use yet
struct NvFlowOpRuntimeInterface;
typedef struct NvFlowOpRuntimeInterface NvFlowOpRuntimeInterface;
/// ********************************* Sparse ***************************************
struct NvFlowSparse;
typedef struct NvFlowSparse NvFlowSparse;
NV_FLOW_REFLECT_STRUCT_OPAQUE_IMPL(NvFlowSparse)
typedef struct NvFlowSparseParams
{
NvFlowSparseLayerParams* layers;
NvFlowUint layerCount;
NvFlowSparseLevelParams* levels;
NvFlowUint levelCount;
NvFlowInt4* locations;
NvFlowUint64 locationCount;
NvFlowUint2* tableRanges;
NvFlowUint64 tableRangeCount;
}NvFlowSparseParams;
NV_FLOW_INLINE NvFlowUint NvFlowSparseParams_layerToLayerParamIdx(const NvFlowSparseParams* params, int layer)
{
NvFlowUint retLayerParamIdx = ~0u;
for (NvFlowUint layerParamIdx = 0u; layerParamIdx < params->layerCount; layerParamIdx++)
{
if (params->layers[layerParamIdx].layer == layer)
{
retLayerParamIdx = layerParamIdx;
break;
}
}
return retLayerParamIdx;
}
NV_FLOW_INLINE NvFlowUint NvFlowSparseParams_locationToBlockIdx(const NvFlowSparseParams* params, NvFlowInt4 location)
{
const NvFlowSparseLevelParams* tableParams = ¶ms->levels[0u];
NvFlowUint3 bucketIdx = {
(NvFlowUint)location.x & tableParams->tableDimLessOne.x,
(NvFlowUint)location.y & tableParams->tableDimLessOne.y,
(NvFlowUint)location.z & tableParams->tableDimLessOne.z
};
NvFlowUint bucketIdx1D = (bucketIdx.z << (tableParams->tableDimBits_xy)) |
(bucketIdx.y << tableParams->tableDimBits_x) |
(bucketIdx.x);
NvFlowUint2 range = params->tableRanges[bucketIdx1D];
NvFlowUint outBlockIdx = ~0u;
for (NvFlowUint blockIdx = range.x; blockIdx < range.y; blockIdx++)
{
NvFlowInt4 compareLocation = params->locations[blockIdx];
if (compareLocation.x == location.x &&
compareLocation.y == location.y &&
compareLocation.z == location.z &&
compareLocation.w == location.w)
{
outBlockIdx = blockIdx;
break;
}
}
return outBlockIdx;
}
NV_FLOW_INLINE NvFlowBool32 NvFlowBlockIdxToLocation(const NvFlowSparseParams* params, NvFlowUint blockIdx, NvFlowInt4* out_location)
{
NvFlowBool32 ret;
if (blockIdx < params->locationCount)
{
*out_location = params->locations[blockIdx];
ret = NV_FLOW_TRUE;
}
else
{
out_location->x = 0x40000000;
out_location->y = 0x40000000;
out_location->z = 0x40000000;
out_location->w = 0x40000000;
ret = NV_FLOW_FALSE;
}
return ret;
}
// TODO, maybe expand
#define NV_FLOW_REFLECT_TYPE NvFlowSparseParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint, layerCount, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, levelCount, 0, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
// TODO, maybe expand
#define NV_FLOW_REFLECT_TYPE NvFlowSparseLevelParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint, numLocations, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, numLayers, 0, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowSparseTexture
{
NvFlowTextureTransient* textureTransient;
NvFlowBufferTransient* sparseBuffer;
NvFlowSparseParams sparseParams;
NvFlowUint levelIdx;
NvFlowFormat format;
}NvFlowSparseTexture;
NV_FLOW_REFLECT_STRUCT_OPAQUE_IMPL(NvFlowTextureTransient)
NV_FLOW_REFLECT_STRUCT_OPAQUE_IMPL(NvFlowBufferTransient)
#define NV_FLOW_REFLECT_TYPE NvFlowSparseTexture
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowTextureTransient, textureTransient, 0, 0)
NV_FLOW_REFLECT_POINTER(NvFlowBufferTransient, sparseBuffer, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseParams, sparseParams, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, levelIdx, 0, 0)
NV_FLOW_REFLECT_ENUM(format, 0, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_INLINE void NvFlowSparseTexture_passThrough(NvFlowSparseTexture* dst, const NvFlowSparseTexture* src)
{
*dst = *src;
}
NV_FLOW_INLINE void NvFlowSparseTexture_duplicateWithFormat(NvFlowContextInterface* contextInterface, NvFlowContext* context, NvFlowSparseTexture* dst, const NvFlowSparseTexture* src, NvFlowFormat format)
{
*dst = *src;
NvFlowSparseLevelParams* levelParams = &dst->sparseParams.levels[dst->levelIdx];
NvFlowTextureDesc texDesc = { eNvFlowTextureType_3d };
texDesc.textureType = eNvFlowTextureType_3d;
texDesc.usageFlags = eNvFlowTextureUsage_rwTexture | eNvFlowTextureUsage_texture;
texDesc.format = format;
texDesc.width = levelParams->dim.x;
texDesc.height = levelParams->dim.y;
texDesc.depth = levelParams->dim.z;
texDesc.mipLevels = 1u;
dst->textureTransient = contextInterface->getTextureTransient(context, &texDesc);
}
NV_FLOW_INLINE void NvFlowSparseTexture_duplicate(NvFlowContextInterface* contextInterface, NvFlowContext* context, NvFlowSparseTexture* dst, const NvFlowSparseTexture* src)
{
NvFlowSparseTexture_duplicateWithFormat(contextInterface, context, dst, src, src->format);
}
typedef struct NvFlowSparseUpdateLayerParams
{
NvFlowFloat3 blockSizeWorld;
int layer;
NvFlowBool32 forceClear;
NvFlowBool32 forceDisableEmitters;
NvFlowBool32 forceDisableCoreSimulation;
}NvFlowSparseUpdateLayerParams;
typedef struct NvFlowSparseInterface
{
NV_FLOW_REFLECT_INTERFACE();
NvFlowSparse*(NV_FLOW_ABI* create)(NvFlowContextInterface* contextInterface, NvFlowContext* context, NvFlowUint maxLocations);
void(NV_FLOW_ABI* destroy)(NvFlowContext* context, NvFlowSparse* sparse);
void(NV_FLOW_ABI* reset)(NvFlowContext* context, NvFlowSparse* sparse, NvFlowUint maxLocations);
void(NV_FLOW_ABI* updateLayers)(NvFlowSparse* sparse, NvFlowSparseUpdateLayerParams* layers, NvFlowUint numLayers);
void(NV_FLOW_ABI* updateLocations)(NvFlowSparse* sparse, NvFlowInt4* locations, NvFlowUint numLocations, NvFlowUint3 baseBlockDimBits, NvFlowUint minLifetime);
void(NV_FLOW_ABI* updateLayerDeltaTimes)(NvFlowSparse* sparse, float* layerDeltaTimes, NvFlowUint64 layerDeltaTimeCount);
NvFlowBool32(NV_FLOW_ABI* getParams)(NvFlowSparse* sparse, NvFlowSparseParams* out);
void(NV_FLOW_ABI* addPasses)(NvFlowContext* context, NvFlowSparse* sparse, NvFlowBufferTransient** pBufferTransient);
void(NV_FLOW_ABI* addPassesNanoVdb)(
NvFlowContext* context,
NvFlowSparse* sparse,
NvFlowUint gridType,
NvFlowUint levelIdx,
NvFlowSparseNanoVdbParams* pParams,
NvFlowBufferTransient** pNanoVdbBufferTransient,
NvFlowBufferTransient** pCacheBufferTransient
);
void(NV_FLOW_ABI* addPassesNanoVdbComputeStats)(
NvFlowContext* context,
NvFlowSparse* sparse,
const NvFlowSparseNanoVdbParams* params,
NvFlowBufferTransient* nanoVdbBufferTransient,
NvFlowBufferTransient* cacheBufferTransient,
NvFlowBufferTransient* targetNanoVdbBuffer
);
void(NV_FLOW_ABI* addPassesMigrate)(
NvFlowContext* context,
NvFlowSparse* sparse,
const int* clearLayers,
NvFlowUint64 clearLayerCount,
NvFlowBool32* clearedNoMigrateOut,
NvFlowTextureTransient* oldTextureTransient,
const NvFlowTextureDesc* oldTexDesc,
NvFlowFormat targetFormat,
NvFlowUint targetLevelIdx,
NvFlowSparseTexture* valueOut,
NvFlowTextureDesc* texDescOut
);
NvFlowBufferTransient*(NV_FLOW_ABI* getSparseBuffer)(NvFlowContext* context, NvFlowSparse* sparse);
}NvFlowSparseInterface;
#define NV_FLOW_REFLECT_TYPE NvFlowSparseInterface
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_FUNCTION_POINTER(create, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroy, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(reset, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(updateLayers, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(updateLocations, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(updateLayerDeltaTimes, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getParams, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(addPasses, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(addPassesNanoVdb, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(addPassesNanoVdbComputeStats, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(addPassesMigrate, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getSparseBuffer, 0, 0)
NV_FLOW_REFLECT_END(0)
NV_FLOW_REFLECT_INTERFACE_IMPL()
#undef NV_FLOW_REFLECT_TYPE
/// ********************************* SparseNanoVdbExport ***************************************
typedef struct NvFlowSparseNanoVdbExportParams
{
NvFlowBool32 enabled;
NvFlowBool32 statisticsEnabled;
NvFlowBool32 readbackEnabled;
NvFlowBool32 temperatureEnabled;
NvFlowBool32 fuelEnabled;
NvFlowBool32 burnEnabled;
NvFlowBool32 smokeEnabled;
NvFlowBool32 velocityEnabled;
NvFlowBool32 divergenceEnabled;
}NvFlowSparseNanoVdbExportParams;
#define NvFlowSparseNanoVdbExportParams_default_init { \
NV_FLOW_FALSE, /*enabled*/ \
NV_FLOW_TRUE, /*statisticsEnabled*/ \
NV_FLOW_FALSE, /*readbackEnabled*/ \
NV_FLOW_FALSE, /*temperatureEnabled*/ \
NV_FLOW_FALSE, /*fuelEnabled*/ \
NV_FLOW_FALSE, /*burnEnabled*/ \
NV_FLOW_TRUE, /*smokeEnabled*/ \
NV_FLOW_FALSE, /*velocityEnabled*/ \
NV_FLOW_FALSE, /*divergenceEnabled*/ \
}
static const NvFlowSparseNanoVdbExportParams NvFlowSparseNanoVdbExportParams_default = NvFlowSparseNanoVdbExportParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowSparseNanoVdbExportParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, statisticsEnabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, readbackEnabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, temperatureEnabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, fuelEnabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, burnEnabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, smokeEnabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, velocityEnabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, divergenceEnabled, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowSparseNanoVdbExportParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowSparseNanoVdbExportPinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
NvFlowSparseInterface* sparseInterface;
NvFlowSparse* sparse;
const NvFlowSparseNanoVdbExportParams** params;
NvFlowUint64 paramCount;
NvFlowSparseTexture velocity;
NvFlowSparseTexture density;
}NvFlowSparseNanoVdbExportPinsIn;
typedef struct NvFlowSparseNanoVdbExportReadback
{
NvFlowUint64 globalFrameCompleted;
NvFlowUint8* temperatureNanoVdbReadback;
NvFlowUint64 temperatureNanoVdbReadbackSize;
NvFlowUint8* fuelNanoVdbReadback;
NvFlowUint64 fuelNanoVdbReadbackSize;
NvFlowUint8* burnNanoVdbReadback;
NvFlowUint64 burnNanoVdbReadbackSize;
NvFlowUint8* smokeNanoVdbReadback;
NvFlowUint64 smokeNanoVdbReadbackSize;
NvFlowUint8* velocityNanoVdbReadback;
NvFlowUint64 velocityNanoVdbReadbackSize;
NvFlowUint8* divergenceNanoVdbReadback;
NvFlowUint64 divergenceNanoVdbReadbackSize;
}NvFlowSparseNanoVdbExportReadback;
#define NvFlowSparseNanoVdbExportReadback_default_init { \
~0llu, /*globalFrameCompleted*/ \
0, /*temperatureNanoVdbReadback*/ \
0, /*temperatureNanoVdbReadbackSize*/ \
0, /*fuelNanoVdbReadback*/ \
0, /*fuelNanoVdbReadbackSize*/ \
0, /*burnNanoVdbReadback*/ \
0, /*burnNanoVdbReadbackSize*/ \
0, /*smokeNanoVdbReadback*/ \
0, /*smokeNanoVdbReadbackSize*/ \
0, /*velocityNanoVdbReadback*/ \
0, /*velocityNanoVdbReadbackSize*/ \
0, /*divergenceNanoVdbReadback*/ \
0, /*divergenceNanoVdbReadbackSize*/ \
}
static const NvFlowSparseNanoVdbExportReadback NvFlowSparseNanoVdbExportReadback_default = NvFlowSparseNanoVdbExportReadback_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowSparseNanoVdbExportReadback
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint64, globalFrameCompleted, 0, 0)
NV_FLOW_REFLECT_ARRAY(NvFlowUint8, temperatureNanoVdbReadback, temperatureNanoVdbReadbackSize, 0, 0)
NV_FLOW_REFLECT_ARRAY(NvFlowUint8, fuelNanoVdbReadback, fuelNanoVdbReadbackSize, 0, 0)
NV_FLOW_REFLECT_ARRAY(NvFlowUint8, burnNanoVdbReadback, burnNanoVdbReadbackSize, 0, 0)
NV_FLOW_REFLECT_ARRAY(NvFlowUint8, smokeNanoVdbReadback, smokeNanoVdbReadbackSize, 0, 0)
NV_FLOW_REFLECT_ARRAY(NvFlowUint8, velocityNanoVdbReadback, velocityNanoVdbReadbackSize, 0, 0)
NV_FLOW_REFLECT_ARRAY(NvFlowUint8, divergenceNanoVdbReadback, divergenceNanoVdbReadbackSize, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowSparseNanoVdbExportReadback_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowSparseNanoVdbExportPinsOut
{
NvFlowBufferTransient* temperatureNanoVdb;
NvFlowBufferTransient* fuelNanoVdb;
NvFlowBufferTransient* burnNanoVdb;
NvFlowBufferTransient* smokeNanoVdb;
NvFlowBufferTransient* velocityNanoVdb;
NvFlowBufferTransient* divergenceNanoVdb;
NvFlowSparseNanoVdbExportReadback* readbacks;
NvFlowUint64 readbackCount;
}NvFlowSparseNanoVdbExportPinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowSparseNanoVdbExportPinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowSparseInterface, sparseInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowSparse, sparse, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowSparseNanoVdbExportParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, velocity, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, density, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowSparseNanoVdbExportPinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowBufferTransient, temperatureNanoVdb, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER(NvFlowBufferTransient, fuelNanoVdb, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER(NvFlowBufferTransient, burnNanoVdb, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER(NvFlowBufferTransient, smokeNanoVdb, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER(NvFlowBufferTransient, velocityNanoVdb, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER(NvFlowBufferTransient, divergenceNanoVdb, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_ARRAY(NvFlowSparseNanoVdbExportReadback, readbacks, readbackCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowSparseNanoVdbExport)
/// ********************************* Advect ***************************************
typedef struct NvFlowAdvectionChannelParams
{
float secondOrderBlendThreshold;
float secondOrderBlendFactor;
float damping;
float fade;
}NvFlowAdvectionChannelParams;
#define NvFlowAdvectionChannelParams_default_init { \
0.5f, /*secondOrderBlendThreshold*/ \
0.001f, /*secondOrderBlendFactor*/ \
0.01f, /*damping*/ \
0.f /*fade*/ \
}
static const NvFlowAdvectionChannelParams NvFlowAdvectionChannelParams_default = NvFlowAdvectionChannelParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowAdvectionChannelParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(float, secondOrderBlendThreshold, 0, 0)
NV_FLOW_REFLECT_VALUE(float, secondOrderBlendFactor, 0, 0)
NV_FLOW_REFLECT_VALUE(float, damping, 0, 0)
NV_FLOW_REFLECT_VALUE(float, fade, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowAdvectionChannelParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowAdvectionCombustionParams
{
NvFlowBool32 enabled; //!< Allows advection to be disabled when not in use
NvFlowBool32 downsampleEnabled; //!< Allows density downsample in velocity advection to be disabled
NvFlowBool32 combustionEnabled; //!< Allows combustion to be disabled
NvFlowBool32 forceFadeEnabled; //!< Force fade to apply even when advection disabled
NvFlowAdvectionChannelParams velocity;
NvFlowAdvectionChannelParams divergence;
NvFlowAdvectionChannelParams temperature;
NvFlowAdvectionChannelParams fuel;
NvFlowAdvectionChannelParams burn;
NvFlowAdvectionChannelParams smoke;
float ignitionTemp; //!< Minimum temperature for combustion
float burnPerTemp; //!< Burn amount per unit temperature above ignitionTemp
float fuelPerBurn; //!< Fuel consumed per unit burn
float tempPerBurn; //!< Temperature increase per unit burn
float smokePerBurn; //!< Density increase per unit burn
float divergencePerBurn; //!< Expansion per unit burn
float buoyancyPerTemp; //!< Buoyant force per unit temperature
float buoyancyPerSmoke; //!< Buoyant force per unit smoke
float buoyancyMaxSmoke; //!< Smoke clamp value applied before computing smoke buoyancy
float coolingRate; //!< Cooling rate, exponential
NvFlowFloat3 gravity;
NvFlowBool32 globalFetch; //!< Global fetch, removes velocity clamping
}NvFlowAdvectionCombustionParams;
#define NvFlowAdvectionCombustionParams_default_init { \
NV_FLOW_TRUE, /*enabled*/ \
NV_FLOW_TRUE, /*downsampleEnabled*/ \
NV_FLOW_TRUE, /*combustionEnabled*/ \
NV_FLOW_FALSE, /*forceFadeEnabled*/ \
{0.001f, 0.5f, 0.01f, 1.00f}, /*velocity : {secondOrderBlendThreshold, secondOrderBlendFactor, damping, fade}*/ \
{0.001f, 0.5f, 0.01f, 1.00f}, /*divergence : {secondOrderBlendThreshold, secondOrderBlendFactor, damping, fade}*/ \
{0.001f, 0.9f, 0.00f, 0.00f}, /*temperature : {secondOrderBlendThreshold, secondOrderBlendFactor, damping, fade}*/ \
{0.001f, 0.9f, 0.00f, 0.00f}, /*fuel : {secondOrderBlendThreshold, secondOrderBlendFactor, damping, fade}*/ \
{0.001f, 0.9f, 0.00f, 0.00f}, /*burn : {secondOrderBlendThreshold, secondOrderBlendFactor, damping, fade}*/ \
{0.001f, 0.9f, 0.30f, 0.65f}, /*smoke : {secondOrderBlendThreshold, secondOrderBlendFactor, damping, fade}*/ \
0.05f, /*ignitionTemp*/ \
4.f, /*burnPerTemp*/ \
0.25f, /*fuelPerBurn*/ \
5.f, /*tempPerBurn*/ \
3.f, /*smokePerBurn*/ \
0.f, /*divergencePerBurn*/ \
2.f, /*buoyancyPerTemp*/ \
0.f, /*buoyancyPerSmoke*/ \
1.f, /*buoyancyMaxSmoke*/ \
1.5f, /*coolingRate*/ \
0.f, /*gravity.x*/ \
0.f, /*gravity.y*/ \
-100.f, /*gravity.z*/ \
0u /*globalFetch*/ \
}
static const NvFlowAdvectionCombustionParams NvFlowAdvectionCombustionParams_default = NvFlowAdvectionCombustionParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowAdvectionCombustionParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, downsampleEnabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, combustionEnabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, forceFadeEnabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowAdvectionChannelParams, velocity, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowAdvectionChannelParams, divergence, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowAdvectionChannelParams, temperature, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowAdvectionChannelParams, fuel, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowAdvectionChannelParams, burn, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowAdvectionChannelParams, smoke, 0, 0)
NV_FLOW_REFLECT_VALUE(float, ignitionTemp, 0, 0)
NV_FLOW_REFLECT_VALUE(float, burnPerTemp, 0, 0)
NV_FLOW_REFLECT_VALUE(float, fuelPerBurn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, tempPerBurn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, smokePerBurn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, divergencePerBurn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, buoyancyPerTemp, 0, 0)
NV_FLOW_REFLECT_VALUE(float, buoyancyPerSmoke, 0, 0)
NV_FLOW_REFLECT_VALUE(float, buoyancyMaxSmoke, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coolingRate, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, gravity, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, globalFetch, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowAdvectionCombustionParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowAdvectionSimplePinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
float deltaTime;
NvFlowSparseTexture velocity;
}NvFlowAdvectionSimplePinsIn;
typedef struct NvFlowAdvectionSimplePinsOut
{
NvFlowSparseTexture velocity;
}NvFlowAdvectionSimplePinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowAdvectionSimplePinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, velocity, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowAdvectionSimplePinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, velocity, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowAdvectionSimple)
typedef struct NvFlowAdvectionCombustionDensityPinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
float deltaTime;
const NvFlowAdvectionCombustionParams** params;
NvFlowUint64 paramCount;
NvFlowSparseTexture velocity;
NvFlowSparseTexture density;
NvFlowSparseTexture densityTemp;
}NvFlowAdvectionCombustionDensityPinsIn;
typedef struct NvFlowAdvectionCombustionDensityPinsOut
{
NvFlowSparseTexture density;
}NvFlowAdvectionCombustionDensityPinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowAdvectionCombustionDensityPinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowAdvectionCombustionParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, velocity, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, density, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, densityTemp, eNvFlowReflectHint_pinEnabledMutable, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowAdvectionCombustionDensityPinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, density, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowAdvectionCombustionDensity)
typedef struct NvFlowAdvectionCombustionVelocityPinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
float deltaTime;
const NvFlowAdvectionCombustionParams** params;
NvFlowUint64 paramCount;
NvFlowSparseTexture velocity;
NvFlowSparseTexture velocityTemp;
NvFlowSparseTexture density;
NvFlowSparseTexture densityCoarse;
}NvFlowAdvectionCombustionVelocityPinsIn;
typedef struct NvFlowAdvectionCombustionVelocityPinsOut
{
NvFlowSparseTexture velocity;
NvFlowSparseTexture densityCoarse;
}NvFlowAdvectionCombustionVelocityPinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowAdvectionCombustionVelocityPinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowAdvectionCombustionParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, velocity, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, velocityTemp, eNvFlowReflectHint_pinEnabledMutable, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, density, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, densityCoarse, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowAdvectionCombustionVelocityPinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, velocity, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, densityCoarse, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowAdvectionCombustionVelocity)
/// ********************************* Pressure ***************************************
typedef struct NvFlowPressureParams
{
NvFlowBool32 enabled;
}NvFlowPressureParams;
#define NvFlowPressureParams_default_init { \
NV_FLOW_TRUE, /*enabled*/ \
}
static const NvFlowPressureParams NvFlowPressureParams_default = NvFlowPressureParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowPressureParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enabled, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowPressureParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowPressurePinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
const NvFlowPressureParams** params;
NvFlowUint64 paramCount;
NvFlowSparseTexture velocity;
}NvFlowPressurePinsIn;
typedef struct NvFlowPressurePinsOut
{
NvFlowSparseTexture velocity;
}NvFlowPressurePinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowPressurePinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowPressureParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, velocity, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowPressurePinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, velocity, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowPressure)
/// ********************************* Vorticity ***************************************
typedef struct NvFlowVorticityParams
{
NvFlowBool32 enabled;
float forceScale;
float velocityMask;
float constantMask;
float densityMask;
float velocityLogScale;
float velocityLinearMask;
float temperatureMask;
float fuelMask;
float burnMask;
float smokeMask;
}NvFlowVorticityParams;
#define NvFlowVorticityParams_default_init { \
NV_FLOW_TRUE, /*enabled*/ \
0.6f, /*forceScale*/ \
1.f, /*velocityMask*/ \
0.f, /*constantMask*/ \
0.f, /*densityMask*/ \
1.f, /*velocityLogScale*/ \
0.f, /*velocityLinearMask*/ \
0.f, /*temperatureMask*/ \
0.f, /*fuelMask*/ \
0.f, /*burnMask*/ \
0.f /*smokeMask*/ \
}
static const NvFlowVorticityParams NvFlowVorticityParams_default = NvFlowVorticityParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowVorticityParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enabled, 0, 0)
NV_FLOW_REFLECT_VALUE(float, forceScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, velocityMask, 0, 0)
NV_FLOW_REFLECT_VALUE(float, constantMask, 0, 0)
NV_FLOW_REFLECT_VALUE(float, densityMask, 0, 0)
NV_FLOW_REFLECT_VALUE(float, velocityLogScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, velocityLinearMask, 0, 0)
NV_FLOW_REFLECT_VALUE(float, temperatureMask, 0, 0)
NV_FLOW_REFLECT_VALUE(float, fuelMask, 0, 0)
NV_FLOW_REFLECT_VALUE(float, burnMask, 0, 0)
NV_FLOW_REFLECT_VALUE(float, smokeMask, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowVorticityParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowVorticityPinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
float deltaTime;
const NvFlowVorticityParams** params;
NvFlowUint64 paramCount;
NvFlowSparseTexture velocity;
NvFlowSparseTexture coarseDensity;
}NvFlowVorticityPinsIn;
typedef struct NvFlowVorticityPinsOut
{
NvFlowSparseTexture velocity;
}NvFlowVorticityPinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowVorticityPinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowVorticityParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, velocity, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, coarseDensity, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowVorticityPinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, velocity, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowVorticity)
/// ********************************* Summary ***************************************
typedef struct NvFlowSummaryAllocateParams
{
float smokeThreshold;
float speedThreshold;
float speedThresholdMinSmoke;
NvFlowBool32 enableNeighborAllocation;
}NvFlowSummaryAllocateParams;
#define NvFlowSummaryAllocateParams_default_init { \
0.02f, /*smokeThreshold*/ \
1.f, /*speedThreshold*/ \
0.f, /*speedThresholdMinSmoke*/ \
NV_FLOW_TRUE, /*enableNeighborAllocation*/ \
}
static const NvFlowSummaryAllocateParams NvFlowSummaryAllocateParams_default = NvFlowSummaryAllocateParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowSummaryAllocateParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(float, smokeThreshold, 0, 0)
NV_FLOW_REFLECT_VALUE(float, speedThreshold, 0, 0)
NV_FLOW_REFLECT_VALUE(float, speedThresholdMinSmoke, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enableNeighborAllocation, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowSummaryAllocateParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowSummaryFeedback
{
void* data;
}NvFlowSummaryFeedback;
NV_FLOW_REFLECT_STRUCT_OPAQUE_IMPL(NvFlowSummaryFeedback)
typedef struct NvFlowSummaryPinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
NvFlowSummaryFeedback feedback;
NvFlowSparseTexture velocity;
NvFlowSparseTexture densityCoarse;
const NvFlowSummaryAllocateParams** params;
NvFlowUint64 paramCount;
}NvFlowSummaryPinsIn;
typedef struct NvFlowSummaryPinsOut
{
NvFlowUint unused;
}NvFlowSummaryPinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowSummaryPinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSummaryFeedback, feedback, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, velocity, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, densityCoarse, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowSummaryAllocateParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowSummaryPinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint, unused, eNvFlowReflectHint_none, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowSummary)
typedef struct NvFlowSummaryAllocatePinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
NvFlowSparseParams sparseParams;
const NvFlowSummaryAllocateParams** params;
NvFlowUint64 paramCount;
}NvFlowSummaryAllocatePinsIn;
typedef struct NvFlowSummaryAllocatePinsOut
{
NvFlowSummaryFeedback feedback;
NvFlowInt4* locations;
NvFlowUint64 locationCount;
}NvFlowSummaryAllocatePinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowSummaryAllocatePinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseParams, sparseParams, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowSummaryAllocateParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowSummaryAllocatePinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowSummaryFeedback, feedback, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_ARRAY(NvFlowInt4, locations, locationCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowSummaryAllocate)
/// ********************************* NvFlowOpList ***************************************
typedef struct NvFlowOpList
{
NV_FLOW_REFLECT_INTERFACE();
NvFlowOpGraphInterface* (NV_FLOW_ABI* getOpGraphInterface)();
NvFlowOpRuntimeInterface* (NV_FLOW_ABI* getOpRuntimeInterface)();
NvFlowSparseInterface* (NV_FLOW_ABI* getSparseInterface)();
NvFlowOpInterface* (NV_FLOW_ABI* pSparseNanoVdbExport)();
NvFlowOpInterface* (NV_FLOW_ABI* pAdvectionSimple)();
NvFlowOpInterface* (NV_FLOW_ABI* pAdvectionCombustionDensity)();
NvFlowOpInterface* (NV_FLOW_ABI* pAdvectionCombustionVelocity)();
NvFlowOpInterface* (NV_FLOW_ABI* pPressure)();
NvFlowOpInterface* (NV_FLOW_ABI* pVorticity)();
NvFlowOpInterface* (NV_FLOW_ABI* pSummary)();
NvFlowOpInterface* (NV_FLOW_ABI* pSummaryAllocate)();
}NvFlowOpList;
#define NV_FLOW_REFLECT_TYPE NvFlowOpList
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_FUNCTION_POINTER(getOpGraphInterface, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getOpRuntimeInterface, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getSparseInterface, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pSparseNanoVdbExport, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pAdvectionSimple, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pAdvectionCombustionDensity, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pAdvectionCombustionVelocity, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pPressure, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pVorticity, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pSummary, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pSummaryAllocate, 0, 0)
NV_FLOW_REFLECT_END(0)
NV_FLOW_REFLECT_INTERFACE_IMPL()
#undef NV_FLOW_REFLECT_TYPE
typedef NvFlowOpList* (NV_FLOW_ABI* PFN_NvFlowGetOpList)();
NV_FLOW_API NvFlowOpList* NvFlowGetOpList();
#endif
|
NVIDIA-Omniverse/PhysX/flow/include/nvflow/NvFlowContext.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#ifndef NV_FLOW_CONTEXT_H
#define NV_FLOW_CONTEXT_H
#include "NvFlowReflect.h"
/// ************************* NvFlowContext **********************************
struct NvFlowContext;
typedef struct NvFlowContext NvFlowContext;
NV_FLOW_REFLECT_STRUCT_OPAQUE_IMPL(NvFlowContext)
typedef enum NvFlowTextureBindingType
{
eNvFlowTextureBindingType_separateSampler = 0,
eNvFlowTextureBindingType_combinedSampler = 1,
eNvFlowTextureBindingType_count = 2,
eNvFlowTextureBindingType_maxEnum = 0x7FFFFFFF
}NvFlowTextureBindingType;
typedef struct NvFlowContextConfig
{
NvFlowContextApi api;
NvFlowTextureBindingType textureBinding;
}NvFlowContextConfig;
typedef struct NvFlowBytecode
{
const void* data;
NvFlowUint64 sizeInBytes;
}NvFlowBytecode;
struct NvFlowBuffer;
typedef struct NvFlowBuffer NvFlowBuffer;
struct NvFlowBufferTransient;
typedef struct NvFlowBufferTransient NvFlowBufferTransient;
struct NvFlowBufferAcquire;
typedef struct NvFlowBufferAcquire NvFlowBufferAcquire;
typedef enum NvFlowMemoryType
{
eNvFlowMemoryType_device = 0,
eNvFlowMemoryType_upload = 1,
eNvFlowMemoryType_readback = 2,
eNvFlowMemoryType_maxEnum = 0x7FFFFFFF
}NvFlowMemoryType;
typedef NvFlowUint NvFlowBufferUsageFlags;
typedef enum NvFlowBufferUsage
{
eNvFlowBufferUsage_constantBuffer = 0x01,
eNvFlowBufferUsage_structuredBuffer = 0x02,
eNvFlowBufferUsage_buffer = 0x04,
eNvFlowBufferUsage_rwStructuredBuffer = 0x08,
eNvFlowBufferUsage_rwBuffer = 0x10,
eNvFlowBufferUsage_indirectBuffer = 0x20,
eNvFlowBufferUsage_bufferCopySrc = 0x40,
eNvFlowBufferUsage_bufferCopyDst = 0x80,
eNvFlowBufferUsage_maxEnum = 0x7FFFFFFF
}NvFlowBufferUsage;
typedef struct NvFlowBufferDesc
{
NvFlowBufferUsageFlags usageFlags;
NvFlowFormat format;
NvFlowUint structureStride;
NvFlowUint64 sizeInBytes;
}NvFlowBufferDesc;
struct NvFlowTexture;
typedef struct NvFlowTexture NvFlowTexture;
struct NvFlowTextureTransient;
typedef struct NvFlowTextureTransient NvFlowTextureTransient;
struct NvFlowTextureAcquire;
typedef struct NvFlowTextureAcquire NvFlowTextureAcquire;
struct NvFlowSampler;
typedef struct NvFlowSampler NvFlowSampler;
typedef enum NvFlowTextureType
{
eNvFlowTextureType_1d = 0,
eNvFlowTextureType_2d = 1,
eNvFlowTextureType_3d = 2,
eNvFlowTextureType_maxEnum = 0x7FFFFFFF
}NvFlowTextureType;
typedef NvFlowUint NvFlowTextureUsageFlags;
typedef enum NvFlowTextureUsage
{
eNvFlowTextureUsage_texture = 0x01,
eNvFlowTextureUsage_rwTexture = 0x02,
eNvFlowTextureUsage_textureCopySrc = 0x04,
eNvFlowTextureUsage_textureCopyDst = 0x08,
eNvFlowTextureUsage_maxEnum = 0x7FFFFFFF
}NvFlowTextureUsage;
typedef struct NvFlowTextureDesc
{
NvFlowTextureType textureType;
NvFlowTextureUsageFlags usageFlags;
NvFlowFormat format;
NvFlowUint width;
NvFlowUint height;
NvFlowUint depth;
NvFlowUint mipLevels;
NvFlowFloat4 optimizedClearValue;
}NvFlowTextureDesc;
typedef enum NvFlowSamplerAddressMode
{
eNvFlowSamplerAddressMode_wrap = 0,
eNvFlowSamplerAddressMode_clamp = 1,
eNvFlowSamplerAddressMode_mirror = 2,
eNvFlowSamplerAddressMode_border = 3,
eNvFlowSamplerAddressMode_count = 4,
eNvFlowSamplerAddressMode_maxEnum = 0x7FFFFFFF
}NvFlowSamplerAddressMode;
typedef enum NvFlowSamplerFilterMode
{
eNvFlowSamplerFilterMode_point = 0,
eNvFlowSamplerFilterMode_linear = 1,
eNvFlowSamplerFilterMode_count = 2,
eNvFlowSamplerFilterMode_maxEnum = 0x7FFFFFFF
}NvFlowSamplerFilterMode;
typedef struct NvFlowSamplerDesc
{
NvFlowSamplerAddressMode addressModeU;
NvFlowSamplerAddressMode addressModeV;
NvFlowSamplerAddressMode addressModeW;
NvFlowSamplerFilterMode filterMode;
}NvFlowSamplerDesc;
typedef enum NvFlowDescriptorType
{
eNvFlowDescriptorType_unknown = 0,
/// Explicit in NFSL shader code
eNvFlowDescriptorType_constantBuffer = 1, // HLSL register b
eNvFlowDescriptorType_structuredBuffer = 2, // HLSL register t
eNvFlowDescriptorType_buffer = 3, // HLSL register t
eNvFlowDescriptorType_texture = 4, // HLSL register t
eNvFlowDescriptorType_sampler = 5, // HLSL register s
eNvFlowDescriptorType_rwStructuredBuffer = 6, // HLSL register u
eNvFlowDescriptorType_rwBuffer = 7, // HLSL register u
eNvFlowDescriptorType_rwTexture = 8, // HLSL register u
/// If requiresCombinedTextureSampler, uses TextureSampler instead of separate texture and sampler
eNvFlowDescriptorType_textureSampler = 9, // Vulkan only
/// Descriptors not explicitly mentioned in shaders
eNvFlowDescriptorType_indirectBuffer = 10, // No register
eNvFlowDescriptorType_bufferCopySrc = 11, // No register
eNvFlowDescriptorType_bufferCopyDst = 12, // No register
eNvFlowDescriptorType_textureCopySrc = 13, // No register
eNvFlowDescriptorType_textureCopyDst = 14, // No register
eNvFlowDescriptorType_count = 15,
eNvFlowDescriptorType_maxEnum = 0x7FFFFFFF
}NvFlowDescriptorType;
typedef struct NvFlowResource
{
NvFlowBufferTransient* bufferTransient;
NvFlowTextureTransient* textureTransient;
NvFlowSampler* sampler;
}NvFlowResource;
typedef enum NvFlowRegisterHlsl
{
eNvFlowRegisterHlsl_unknown = 0,
eNvFlowRegisterHlsl_b = 1,
eNvFlowRegisterHlsl_t = 2,
eNvFlowRegisterHlsl_s = 3,
eNvFlowRegisterHlsl_u = 4,
eNvFlowRegisterHlsl_count = 5,
eNvFlowRegisterHlsl_maxEnum = 0x7FFFFFFF
}NvFlowRegisterHlsl;
typedef struct NvFlowDescriptorWriteD3D12
{
NvFlowRegisterHlsl registerHlsl;
NvFlowUint registerIndex;
NvFlowUint space;
}NvFlowDescriptorWriteD3D12;
typedef struct NvFlowDescriptorWriteVulkan
{
NvFlowUint binding;
NvFlowUint arrayIndex;
NvFlowUint set;
}NvFlowDescriptorWriteVulkan;
typedef struct NvFlowDescriptorWriteUnion
{
NvFlowDescriptorWriteD3D12 d3d12;
NvFlowDescriptorWriteVulkan vulkan;
}NvFlowDescriptorWriteUnion;
typedef struct NvFlowDescriptorWrite
{
NvFlowDescriptorType type;
NvFlowDescriptorWriteUnion write;
}NvFlowDescriptorWrite;
typedef struct NvFlowBindingDescD3D12
{
NvFlowRegisterHlsl registerHlsl;
NvFlowUint registerBegin;
NvFlowUint numRegisters;
NvFlowUint space;
}NvFlowBindingDescD3D12;
typedef struct NvFlowBindingDescVulkan
{
NvFlowUint binding;
NvFlowUint descriptorCount;
NvFlowUint set;
}NvFlowBindingDescVulkan;
typedef struct NvFlowBindingDescUnion
{
NvFlowBindingDescD3D12 d3d12;
NvFlowBindingDescVulkan vulkan;
}NvFlowBindingDescUnion;
typedef struct NvFlowBindingDesc
{
NvFlowDescriptorType type;
NvFlowBindingDescUnion bindingDesc;
}NvFlowBindingDesc;
struct NvFlowComputePipeline;
typedef struct NvFlowComputePipeline NvFlowComputePipeline;
typedef struct NvFlowComputePipelineDesc
{
NvFlowUint numBindingDescs;
NvFlowBindingDesc* bindingDescs;
NvFlowBytecode bytecode;
}NvFlowComputePipelineDesc;
typedef struct NvFlowPassComputeParams
{
NvFlowComputePipeline* pipeline;
NvFlowUint3 gridDim;
NvFlowUint numDescriptorWrites;
const NvFlowDescriptorWrite* descriptorWrites;
const NvFlowResource* resources;
const char* debugLabel;
}NvFlowPassComputeParams;
typedef struct NvFlowPassCopyBufferParams
{
NvFlowUint64 srcOffset;
NvFlowUint64 dstOffset;
NvFlowUint64 numBytes;
NvFlowBufferTransient* src;
NvFlowBufferTransient* dst;
const char* debugLabel;
}NvFlowPassCopyBufferParams;
typedef struct NvFlowPassCopyBufferToTextureParams
{
NvFlowUint64 bufferOffset;
NvFlowUint bufferRowPitch;
NvFlowUint bufferDepthPitch;
NvFlowUint textureMipLevel;
NvFlowUint3 textureOffset;
NvFlowUint3 textureExtent;
NvFlowBufferTransient* src;
NvFlowTextureTransient* dst;
const char* debugLabel;
}NvFlowPassCopyBufferToTextureParams;
typedef struct NvFlowPassCopyTextureToBufferParams
{
NvFlowUint64 bufferOffset;
NvFlowUint bufferRowPitch;
NvFlowUint bufferDepthPitch;
NvFlowUint textureMipLevel;
NvFlowUint3 textureOffset;
NvFlowUint3 textureExtent;
NvFlowTextureTransient* src;
NvFlowBufferTransient* dst;
const char* debugLabel;
}NvFlowPassCopyTextureToBufferParams;
typedef struct NvFlowPassCopyTextureParams
{
NvFlowUint srcMipLevel;
NvFlowUint3 srcOffset;
NvFlowUint dstMipLevel;
NvFlowUint3 dstOffset;
NvFlowUint3 extent;
NvFlowTextureTransient* src;
NvFlowTextureTransient* dst;
const char* debugLabel;
}NvFlowPassCopyTextureParams;
typedef void(*NvFlowContextThreadPoolTask_t)(NvFlowUint taskIdx, NvFlowUint threadIdx, void* sharedMem, void* userdata);
typedef struct NvFlowContextInterface
{
NV_FLOW_REFLECT_INTERFACE();
void(NV_FLOW_ABI* getContextConfig)(NvFlowContext* context, NvFlowContextConfig* config);
NvFlowUint64(NV_FLOW_ABI* getCurrentFrame)(NvFlowContext* context);
NvFlowUint64(NV_FLOW_ABI* getLastFrameCompleted)(NvFlowContext* context);
NvFlowUint64(NV_FLOW_ABI* getCurrentGlobalFrame)(NvFlowContext* context);
NvFlowUint64(NV_FLOW_ABI* getLastGlobalFrameCompleted)(NvFlowContext* context);
NvFlowLogPrint_t(NV_FLOW_ABI* getLogPrint)(NvFlowContext* context);
void(NV_FLOW_ABI* executeTasks)(NvFlowContext* context, NvFlowUint taskCount, NvFlowUint taskGranularity, NvFlowContextThreadPoolTask_t task, void* userdata);
NvFlowBuffer*(NV_FLOW_ABI* createBuffer)(NvFlowContext* context, NvFlowMemoryType memoryType, const NvFlowBufferDesc* desc);
void(NV_FLOW_ABI* destroyBuffer)(NvFlowContext* context, NvFlowBuffer* buffer);
NvFlowBufferTransient*(NV_FLOW_ABI* getBufferTransient)(NvFlowContext* context, const NvFlowBufferDesc* desc);
NvFlowBufferTransient*(NV_FLOW_ABI* registerBufferAsTransient)(NvFlowContext* context, NvFlowBuffer* buffer);
NvFlowBufferAcquire*(NV_FLOW_ABI* enqueueAcquireBuffer)(NvFlowContext* context, NvFlowBufferTransient* buffer);
NvFlowBool32(NV_FLOW_ABI* getAcquiredBuffer)(NvFlowContext* context, NvFlowBufferAcquire* acquire, NvFlowBuffer** outBuffer);
void*(NV_FLOW_ABI* mapBuffer)(NvFlowContext* context, NvFlowBuffer* buffer);
void(NV_FLOW_ABI* unmapBuffer)(NvFlowContext* context, NvFlowBuffer* buffer);
NvFlowBufferTransient*(NV_FLOW_ABI* getBufferTransientById)(NvFlowContext* context, NvFlowUint64 bufferId);
NvFlowTexture*(NV_FLOW_ABI* createTexture)(NvFlowContext* context, const NvFlowTextureDesc* desc);
void(NV_FLOW_ABI* destroyTexture)(NvFlowContext* context, NvFlowTexture* texture);
NvFlowTextureTransient*(NV_FLOW_ABI* getTextureTransient)(NvFlowContext* context, const NvFlowTextureDesc* desc);
NvFlowTextureTransient*(NV_FLOW_ABI* registerTextureAsTransient)(NvFlowContext* context, NvFlowTexture* texture);
NvFlowTextureAcquire*(NV_FLOW_ABI* enqueueAcquireTexture)(NvFlowContext* context, NvFlowTextureTransient* texture);
NvFlowBool32(NV_FLOW_ABI* getAcquiredTexture)(NvFlowContext* context, NvFlowTextureAcquire* acquire, NvFlowTexture** outTexture);
NvFlowTextureTransient*(NV_FLOW_ABI* getTextureTransientById)(NvFlowContext* context, NvFlowUint64 textureId);
NvFlowSampler*(NV_FLOW_ABI* createSampler)(NvFlowContext* context, const NvFlowSamplerDesc* desc);
NvFlowSampler*(NV_FLOW_ABI* getDefaultSampler)(NvFlowContext* context);
void(NV_FLOW_ABI* destroySampler)(NvFlowContext* context, NvFlowSampler* sampler);
NvFlowComputePipeline*(NV_FLOW_ABI* createComputePipeline)(NvFlowContext* context, const NvFlowComputePipelineDesc* desc);
void(NV_FLOW_ABI* destroyComputePipeline)(NvFlowContext* context, NvFlowComputePipeline* pipeline);
void(NV_FLOW_ABI* addPassCompute)(NvFlowContext* context, const NvFlowPassComputeParams* params);
void(NV_FLOW_ABI* addPassCopyBuffer)(NvFlowContext* context, const NvFlowPassCopyBufferParams* params);
void(NV_FLOW_ABI* addPassCopyBufferToTexture)(NvFlowContext* context, const NvFlowPassCopyBufferToTextureParams* params);
void(NV_FLOW_ABI* addPassCopyTextureToBuffer)(NvFlowContext* context, const NvFlowPassCopyTextureToBufferParams* params);
void(NV_FLOW_ABI* addPassCopyTexture)(NvFlowContext* context, const NvFlowPassCopyTextureParams* params);
}NvFlowContextInterface;
#define NV_FLOW_REFLECT_TYPE NvFlowContextInterface
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_FUNCTION_POINTER(getContextConfig, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getCurrentFrame, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getLastFrameCompleted, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getCurrentGlobalFrame, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getLastGlobalFrameCompleted, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getLogPrint, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(executeTasks, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(createBuffer, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroyBuffer, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getBufferTransient, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(registerBufferAsTransient, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(enqueueAcquireBuffer, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getAcquiredBuffer, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(mapBuffer, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(unmapBuffer, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getBufferTransientById, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(createTexture, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroyTexture, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getTextureTransient, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(registerTextureAsTransient, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(enqueueAcquireTexture, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getAcquiredTexture, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getTextureTransientById, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(createSampler, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getDefaultSampler, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroySampler, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(createComputePipeline, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroyComputePipeline, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(addPassCompute, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(addPassCopyBuffer, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(addPassCopyBufferToTexture, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(addPassCopyTextureToBuffer, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(addPassCopyTexture, 0, 0)
NV_FLOW_REFLECT_END(0)
NV_FLOW_REFLECT_INTERFACE_IMPL()
#undef NV_FLOW_REFLECT_TYPE
#endif |
NVIDIA-Omniverse/PhysX/flow/include/nvflow/shaders/PNanoVDBWrite.h |
// Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/*!
\file PNanoVDBWrite.h
\author Andrew Reidmeyer
\brief This file is a portable (e.g. pointer-less) C99/GLSL/HLSL port
of NanoVDBWrite.h, which is compatible with most graphics APIs.
*/
#ifndef NANOVDB_PNANOVDB_WRITE_H_HAS_BEEN_INCLUDED
#define NANOVDB_PNANOVDB_WRITE_H_HAS_BEEN_INCLUDED
#if defined(PNANOVDB_BUF_C)
#if defined(PNANOVDB_ADDRESS_32)
PNANOVDB_BUF_FORCE_INLINE void pnanovdb_buf_write_uint32(pnanovdb_buf_t buf, uint32_t byte_offset, uint32_t value)
{
uint32_t wordaddress = (byte_offset >> 2u);
#ifdef PNANOVDB_BUF_BOUNDS_CHECK
if (wordaddress < buf.size_in_words)
{
buf.data[wordaddress] = value;
}
#else
buf.data[wordaddress] = value;
#endif
}
PNANOVDB_BUF_FORCE_INLINE void pnanovdb_buf_write_uint64(pnanovdb_buf_t buf, uint32_t byte_offset, uint64_t value)
{
uint64_t* data64 = (uint64_t*)buf.data;
uint32_t wordaddress64 = (byte_offset >> 3u);
#ifdef PNANOVDB_BUF_BOUNDS_CHECK
uint64_t size_in_words64 = buf.size_in_words >> 1u;
if (wordaddress64 < size_in_words64)
{
data64[wordaddress64] = value;
}
#else
data64[wordaddress64] = value;
#endif
}
#elif defined(PNANOVDB_ADDRESS_64)
PNANOVDB_BUF_FORCE_INLINE void pnanovdb_buf_write_uint32(pnanovdb_buf_t buf, uint64_t byte_offset, uint32_t value)
{
uint64_t wordaddress = (byte_offset >> 2u);
#ifdef PNANOVDB_BUF_BOUNDS_CHECK
if (wordaddress < buf.size_in_words)
{
buf.data[wordaddress] = value;
}
#else
buf.data[wordaddress] = value;
#endif
}
PNANOVDB_BUF_FORCE_INLINE void pnanovdb_buf_write_uint64(pnanovdb_buf_t buf, uint64_t byte_offset, uint64_t value)
{
uint64_t* data64 = (uint64_t*)buf.data;
uint64_t wordaddress64 = (byte_offset >> 3u);
#ifdef PNANOVDB_BUF_BOUNDS_CHECK
uint64_t size_in_words64 = buf.size_in_words >> 1u;
if (wordaddress64 < size_in_words64)
{
data64[wordaddress64] = value;
}
#else
data64[wordaddress64] = value;
#endif
}
#endif
#endif
#if defined(PNANOVDB_C)
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_float_as_uint32(float v) { return *((pnanovdb_uint32_t*)(&v)); }
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_double_as_uint64(double v) { return *((pnanovdb_uint64_t*)(&v)); }
#elif defined(PNANOVDB_HLSL)
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_float_as_uint32(float v) { return asuint(v); }
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_double_as_uint64(double v) { uint2 ret; asuint(v, ret.x, ret.y); return ret; }
#elif defined(PNANOVDB_GLSL)
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_float_as_uint32(float v) { return floatBitsToUint(v); }
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_double_as_uint64(double v) { return unpackDouble2x32(v); }
#endif
PNANOVDB_FORCE_INLINE void pnanovdb_write_uint32(pnanovdb_buf_t buf, pnanovdb_address_t address, pnanovdb_uint32_t value)
{
pnanovdb_buf_write_uint32(buf, address.byte_offset, value);
}
PNANOVDB_FORCE_INLINE void pnanovdb_write_uint64(pnanovdb_buf_t buf, pnanovdb_address_t address, pnanovdb_uint64_t value)
{
pnanovdb_buf_write_uint64(buf, address.byte_offset, value);
}
PNANOVDB_FORCE_INLINE void pnanovdb_write_int32(pnanovdb_buf_t buf, pnanovdb_address_t address, pnanovdb_int32_t value)
{
pnanovdb_write_uint32(buf, address, pnanovdb_int32_as_uint32(value));
}
PNANOVDB_FORCE_INLINE void pnanovdb_write_int64(pnanovdb_buf_t buf, pnanovdb_address_t address, pnanovdb_int64_t value)
{
pnanovdb_buf_write_uint64(buf, address.byte_offset, pnanovdb_int64_as_uint64(value));
}
PNANOVDB_FORCE_INLINE void pnanovdb_write_float(pnanovdb_buf_t buf, pnanovdb_address_t address, float value)
{
pnanovdb_write_uint32(buf, address, pnanovdb_float_as_uint32(value));
}
PNANOVDB_FORCE_INLINE void pnanovdb_write_double(pnanovdb_buf_t buf, pnanovdb_address_t address, double value)
{
pnanovdb_write_uint64(buf, address, pnanovdb_double_as_uint64(value));
}
PNANOVDB_FORCE_INLINE void pnanovdb_write_coord(pnanovdb_buf_t buf, pnanovdb_address_t address, PNANOVDB_IN(pnanovdb_coord_t) value)
{
pnanovdb_write_uint32(buf, pnanovdb_address_offset(address, 0u), pnanovdb_int32_as_uint32(PNANOVDB_DEREF(value).x));
pnanovdb_write_uint32(buf, pnanovdb_address_offset(address, 4u), pnanovdb_int32_as_uint32(PNANOVDB_DEREF(value).y));
pnanovdb_write_uint32(buf, pnanovdb_address_offset(address, 8u), pnanovdb_int32_as_uint32(PNANOVDB_DEREF(value).z));
}
PNANOVDB_FORCE_INLINE void pnanovdb_tree_set_node_offset_leaf(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p, pnanovdb_uint64_t node_offset_leaf) {
pnanovdb_write_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_NODE_OFFSET_LEAF), node_offset_leaf);
}
PNANOVDB_FORCE_INLINE void pnanovdb_tree_set_node_offset_lower(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p, pnanovdb_uint64_t node_offset_lower) {
pnanovdb_write_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_NODE_OFFSET_LOWER), node_offset_lower);
}
PNANOVDB_FORCE_INLINE void pnanovdb_tree_set_node_offset_upper(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p, pnanovdb_uint64_t node_offset_upper) {
pnanovdb_write_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_NODE_OFFSET_UPPER), node_offset_upper);
}
PNANOVDB_FORCE_INLINE void pnanovdb_tree_set_node_offset_root(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p, pnanovdb_uint64_t node_offset_root) {
pnanovdb_write_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_NODE_OFFSET_ROOT), node_offset_root);
}
PNANOVDB_FORCE_INLINE void pnanovdb_tree_set_node_count_leaf(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p, pnanovdb_uint32_t node_count_leaf) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_NODE_COUNT_LEAF), node_count_leaf);
}
PNANOVDB_FORCE_INLINE void pnanovdb_tree_set_node_count_lower(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p, pnanovdb_uint32_t node_count_lower) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_NODE_COUNT_LOWER), node_count_lower);
}
PNANOVDB_FORCE_INLINE void pnanovdb_tree_set_node_count_upper(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p, pnanovdb_uint32_t node_count_upper) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_NODE_COUNT_UPPER), node_count_upper);
}
PNANOVDB_FORCE_INLINE void pnanovdb_tree_set_tile_count_leaf(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p, pnanovdb_uint32_t tile_count_leaf) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_TILE_COUNT_LEAF), tile_count_leaf);
}
PNANOVDB_FORCE_INLINE void pnanovdb_tree_set_tile_count_lower(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p, pnanovdb_uint32_t tile_count_lower) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_TILE_COUNT_LOWER), tile_count_lower);
}
PNANOVDB_FORCE_INLINE void pnanovdb_tree_set_tile_count_upper(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p, pnanovdb_uint32_t tile_count_upper) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_TILE_COUNT_UPPER), tile_count_upper);
}
PNANOVDB_FORCE_INLINE void pnanovdb_tree_set_voxel_count(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p, pnanovdb_uint64_t voxel_count) {
pnanovdb_write_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_VOXEL_COUNT), voxel_count);
}
PNANOVDB_FORCE_INLINE void pnanovdb_root_set_bbox_min(pnanovdb_buf_t buf, pnanovdb_root_handle_t p, PNANOVDB_IN(pnanovdb_coord_t) bbox_min) {
pnanovdb_write_coord(buf, pnanovdb_address_offset(p.address, PNANOVDB_ROOT_OFF_BBOX_MIN), bbox_min);
}
PNANOVDB_FORCE_INLINE void pnanovdb_root_set_bbox_max(pnanovdb_buf_t buf, pnanovdb_root_handle_t p, PNANOVDB_IN(pnanovdb_coord_t) bbox_max) {
pnanovdb_write_coord(buf, pnanovdb_address_offset(p.address, PNANOVDB_ROOT_OFF_BBOX_MAX), bbox_max);
}
PNANOVDB_FORCE_INLINE void pnanovdb_root_set_tile_count(pnanovdb_buf_t buf, pnanovdb_root_handle_t p, pnanovdb_uint32_t tile_count) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_ROOT_OFF_TABLE_SIZE), tile_count);
}
PNANOVDB_FORCE_INLINE void pnanovdb_root_tile_set_key(pnanovdb_buf_t buf, pnanovdb_root_tile_handle_t p, pnanovdb_uint64_t key) {
pnanovdb_write_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_ROOT_TILE_OFF_KEY), key);
}
PNANOVDB_FORCE_INLINE void pnanovdb_root_tile_set_child(pnanovdb_buf_t buf, pnanovdb_root_tile_handle_t p, pnanovdb_int64_t child) {
pnanovdb_write_int64(buf, pnanovdb_address_offset(p.address, PNANOVDB_ROOT_TILE_OFF_CHILD), child);
}
PNANOVDB_FORCE_INLINE void pnanovdb_root_tile_set_state(pnanovdb_buf_t buf, pnanovdb_root_tile_handle_t p, pnanovdb_uint32_t state) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_ROOT_TILE_OFF_STATE), state);
}
PNANOVDB_FORCE_INLINE void pnanovdb_upper_set_bbox_min(pnanovdb_buf_t buf, pnanovdb_upper_handle_t p, PNANOVDB_IN(pnanovdb_coord_t) bbox_min) {
pnanovdb_write_coord(buf, pnanovdb_address_offset(p.address, PNANOVDB_UPPER_OFF_BBOX_MIN), bbox_min);
}
PNANOVDB_FORCE_INLINE void pnanovdb_upper_set_bbox_max(pnanovdb_buf_t buf, pnanovdb_upper_handle_t p, PNANOVDB_IN(pnanovdb_coord_t) bbox_max) {
pnanovdb_write_coord(buf, pnanovdb_address_offset(p.address, PNANOVDB_UPPER_OFF_BBOX_MAX), bbox_max);
}
PNANOVDB_FORCE_INLINE void pnanovdb_upper_set_child_mask(pnanovdb_buf_t buf, pnanovdb_upper_handle_t p, pnanovdb_uint32_t bit_index, pnanovdb_bool_t value) {
pnanovdb_address_t addr = pnanovdb_address_offset(p.address, PNANOVDB_UPPER_OFF_CHILD_MASK + 4u * (bit_index >> 5u));
pnanovdb_uint32_t valueMask = pnanovdb_read_uint32(buf, addr);
if (!value) { valueMask &= ~(1u << (bit_index & 31u)); }
if (value) valueMask |= (1u << (bit_index & 31u));
pnanovdb_write_uint32(buf, addr, valueMask);
}
PNANOVDB_FORCE_INLINE void pnanovdb_upper_set_table_child(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_upper_handle_t node, pnanovdb_uint32_t n, pnanovdb_int64_t child)
{
pnanovdb_address_t bufAddress = pnanovdb_upper_get_table_address(grid_type, buf, node, n);
pnanovdb_write_int64(buf, bufAddress, child);
}
PNANOVDB_FORCE_INLINE void pnanovdb_lower_set_bbox_min(pnanovdb_buf_t buf, pnanovdb_lower_handle_t p, PNANOVDB_IN(pnanovdb_coord_t) bbox_min) {
pnanovdb_write_coord(buf, pnanovdb_address_offset(p.address, PNANOVDB_LOWER_OFF_BBOX_MIN), bbox_min);
}
PNANOVDB_FORCE_INLINE void pnanovdb_lower_set_bbox_max(pnanovdb_buf_t buf, pnanovdb_lower_handle_t p, PNANOVDB_IN(pnanovdb_coord_t) bbox_max) {
pnanovdb_write_coord(buf, pnanovdb_address_offset(p.address, PNANOVDB_LOWER_OFF_BBOX_MAX), bbox_max);
}
PNANOVDB_FORCE_INLINE void pnanovdb_lower_set_child_mask(pnanovdb_buf_t buf, pnanovdb_lower_handle_t p, pnanovdb_uint32_t bit_index, pnanovdb_bool_t value) {
pnanovdb_address_t addr = pnanovdb_address_offset(p.address, PNANOVDB_LOWER_OFF_CHILD_MASK + 4u * (bit_index >> 5u));
pnanovdb_uint32_t valueMask = pnanovdb_read_uint32(buf, addr);
if (!value) { valueMask &= ~(1u << (bit_index & 31u)); }
if (value) valueMask |= (1u << (bit_index & 31u));
pnanovdb_write_uint32(buf, addr, valueMask);
}
PNANOVDB_FORCE_INLINE void pnanovdb_lower_set_table_child(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_lower_handle_t node, pnanovdb_uint32_t n, pnanovdb_int64_t child)
{
pnanovdb_address_t table_address = pnanovdb_lower_get_table_address(grid_type, buf, node, n);
pnanovdb_write_int64(buf, table_address, child);
}
PNANOVDB_FORCE_INLINE void pnanovdb_leaf_set_bbox_min(pnanovdb_buf_t buf, pnanovdb_leaf_handle_t p, PNANOVDB_IN(pnanovdb_coord_t) bbox_min) {
pnanovdb_write_coord(buf, pnanovdb_address_offset(p.address, PNANOVDB_LEAF_OFF_BBOX_MIN), bbox_min);
}
PNANOVDB_FORCE_INLINE void pnanovdb_leaf_set_bbox_dif_and_flags(pnanovdb_buf_t buf, pnanovdb_leaf_handle_t p, pnanovdb_uint32_t bbox_dif_and_flags) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_LEAF_OFF_BBOX_DIF_AND_FLAGS), bbox_dif_and_flags);
}
PNANOVDB_FORCE_INLINE void pnanovdb_map_set_matf(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index, float matf) {
pnanovdb_write_float(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_MATF + 4u * index), matf);
}
PNANOVDB_FORCE_INLINE void pnanovdb_map_set_invmatf(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index, float invmatf) {
pnanovdb_write_float(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_INVMATF + 4u * index), invmatf);
}
PNANOVDB_FORCE_INLINE void pnanovdb_map_set_vecf(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index, float vecf) {
pnanovdb_write_float(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_VECF + 4u * index), vecf);
}
PNANOVDB_FORCE_INLINE void pnanovdb_map_set_taperf(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index, float taperf) {
pnanovdb_write_float(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_TAPERF), taperf);
}
PNANOVDB_FORCE_INLINE void pnanovdb_map_set_matd(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index, double matd) {
pnanovdb_write_double(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_MATD + 8u * index), matd);
}
PNANOVDB_FORCE_INLINE void pnanovdb_map_set_invmatd(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index, double invmatd) {
pnanovdb_write_double(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_INVMATD + 8u * index), invmatd);
}
PNANOVDB_FORCE_INLINE void pnanovdb_map_set_vecd(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index, double vecd) {
pnanovdb_write_double(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_VECD + 8u * index), vecd);
}
PNANOVDB_FORCE_INLINE void pnanovdb_map_set_taperd(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index, double taperd) {
pnanovdb_write_double(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_TAPERD), taperd);
}
PNANOVDB_FORCE_INLINE void pnanovdb_grid_set_magic(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint64_t magic) {
pnanovdb_write_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_MAGIC), magic);
}
PNANOVDB_FORCE_INLINE void pnanovdb_grid_set_checksum(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint64_t checksum) {
pnanovdb_write_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_CHECKSUM), checksum);
}
PNANOVDB_FORCE_INLINE void pnanovdb_grid_set_version(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint32_t version) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_VERSION), version);
}
PNANOVDB_FORCE_INLINE void pnanovdb_grid_set_flags(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint32_t flags) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_FLAGS), flags);
}
PNANOVDB_FORCE_INLINE void pnanovdb_grid_get_grid_index(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint32_t grid_index) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_GRID_INDEX), grid_index);
}
PNANOVDB_FORCE_INLINE void pnanovdb_grid_get_grid_count(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint32_t grid_count) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_GRID_COUNT), grid_count);
}
PNANOVDB_FORCE_INLINE void pnanovdb_grid_set_grid_size(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint64_t grid_size) {
pnanovdb_write_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_GRID_SIZE), grid_size);
}
PNANOVDB_FORCE_INLINE void pnanovdb_grid_set_grid_name(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint32_t index, pnanovdb_uint32_t grid_name) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_GRID_NAME + 4u * index), grid_name);
}
PNANOVDB_FORCE_INLINE void pnanovdb_grid_set_world_bbox(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint32_t index, double world_bbox) {
pnanovdb_write_double(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_WORLD_BBOX + 8u * index), world_bbox);
}
PNANOVDB_FORCE_INLINE void pnanovdb_grid_set_voxel_size(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint32_t index, double voxel_size) {
pnanovdb_write_double(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_VOXEL_SIZE + 8u * index), voxel_size);
}
PNANOVDB_FORCE_INLINE void pnanovdb_grid_set_grid_class(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint32_t grid_class) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_GRID_CLASS), grid_class);
}
PNANOVDB_FORCE_INLINE void pnanovdb_grid_set_grid_type(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint32_t grid_type) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_GRID_TYPE), grid_type);
}
PNANOVDB_FORCE_INLINE void pnanovdb_grid_set_blind_metadata_offset(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint64_t blind_metadata_offset) {
pnanovdb_write_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_BLIND_METADATA_OFFSET), blind_metadata_offset);
}
PNANOVDB_FORCE_INLINE void pnanovdb_grid_set_blind_metadata_count(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint32_t metadata_count) {
pnanovdb_write_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_BLIND_METADATA_COUNT), metadata_count);
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_make_version(pnanovdb_uint32_t major, pnanovdb_uint32_t minor, pnanovdb_uint32_t patch)
{
return (major << 21u) | (minor << 10u) | (patch);
}
#endif |
NVIDIA-Omniverse/PhysX/flow/include/nvflow/shaders/NvFlowShaderTypes.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#ifndef NV_FLOW_SHADER_TYPES_H
#define NV_FLOW_SHADER_TYPES_H
#ifndef NV_FLOW_CPU
#if defined(__cplusplus)
#define NV_FLOW_CPU 1
#endif
#endif
#ifdef NV_FLOW_CPU_SHADER
// For CPU Shader, basic types defined at global scope before shader
#elif defined(NV_FLOW_CPU)
typedef unsigned int NvFlowBool32;
typedef unsigned int NvFlowUint;
typedef unsigned char NvFlowUint8;
typedef unsigned short NvFlowUint16;
typedef unsigned long long NvFlowUint64;
typedef struct NvFlowUint2
{
NvFlowUint x, y;
}NvFlowUint2;
typedef struct NvFlowUint3
{
NvFlowUint x, y, z;
}NvFlowUint3;
typedef struct NvFlowUint4
{
NvFlowUint x, y, z, w;
}NvFlowUint4;
typedef struct NvFlowInt2
{
int x, y;
}NvFlowInt2;
typedef struct NvFlowInt3
{
int x, y, z;
}NvFlowInt3;
typedef struct NvFlowInt4
{
int x, y, z, w;
}NvFlowInt4;
typedef struct NvFlowFloat2
{
float x, y;
}NvFlowFloat2;
typedef struct NvFlowFloat3
{
float x, y, z;
}NvFlowFloat3;
typedef struct NvFlowFloat4
{
float x, y, z, w;
}NvFlowFloat4;
typedef struct NvFlowFloat4x4
{
NvFlowFloat4 x, y, z, w;
}NvFlowFloat4x4;
#else
#define NvFlowUint uint
#define NvFlowUint2 uint2
#define NvFlowUint3 uint3
#define NvFlowUint4 uint4
#define NvFlowInt2 int2
#define NvFlowInt3 int3
#define NvFlowInt4 int4
#define NvFlowFloat2 float2
#define NvFlowFloat3 float3
#define NvFlowFloat4 float4
#define NvFlowFloat4x4 float4x4
#define NvFlowBool32 uint
#endif
struct NvFlowSparseLevelParams
{
NvFlowUint3 blockDimLessOne;
NvFlowUint threadsPerBlock;
NvFlowUint3 blockDimBits;
NvFlowUint numLocations;
NvFlowUint3 tableDimLessOne;
NvFlowUint tableDim3;
NvFlowUint tableDimBits_x;
NvFlowUint tableDimBits_xy;
NvFlowUint tableDimBits_z;
NvFlowUint locationOffset;
NvFlowUint allocationOffset;
NvFlowUint newListOffset;
NvFlowUint blockLevelOffsetGlobal;
NvFlowUint blockLevelOffsetLocal;
NvFlowUint layerParamIdxOffset;
NvFlowUint numLayers;
NvFlowUint pad0;
NvFlowUint pad1;
NvFlowUint3 dim;
NvFlowUint maxLocations;
NvFlowFloat3 dimInv;
NvFlowUint numNewLocations;
NvFlowInt4 globalLocationMin;
NvFlowInt4 globalLocationMax;
};
#ifdef NV_FLOW_CPU
typedef struct NvFlowSparseLevelParams NvFlowSparseLevelParams;
#endif
struct NvFlowSparseLayerParams
{
NvFlowFloat3 blockSizeWorld;
float blockSizeWorld3;
NvFlowFloat3 blockSizeWorldInv;
int layer;
NvFlowInt4 locationMin;
NvFlowInt4 locationMax;
NvFlowFloat3 worldMin;
NvFlowUint forceClear;
NvFlowFloat3 worldMax;
NvFlowUint forceDisableEmitters;
NvFlowUint numLocations;
float deltaTime;
NvFlowUint forceDisableCoreSimulation;
NvFlowUint gridReset;
};
#ifdef NV_FLOW_CPU
typedef struct NvFlowSparseLayerParams NvFlowSparseLayerParams;
#endif
struct NvFlowSparseNanoVdbParams
{
NvFlowUint2 nanovdb_size_without_leaves;
NvFlowUint2 nanovdb_size_with_leaves;
NvFlowUint2 list_tile_offset;
NvFlowUint2 list_upper_offset;
NvFlowUint2 list_lower_offset;
NvFlowUint2 list_leaf_offset;
NvFlowUint2 cache_tile_offset;
NvFlowUint2 cache_upper_offset;
NvFlowUint2 cache_lower_offset;
NvFlowUint2 cache_leaf_offset;
NvFlowUint list_tile_count;
NvFlowUint list_upper_count;
NvFlowUint list_lower_count;
NvFlowUint list_leaf_count;
NvFlowUint cache_tile_count;
NvFlowUint cache_upper_count;
NvFlowUint cache_lower_count;
NvFlowUint cache_leaf_count;
NvFlowUint2 cache_size;
NvFlowUint grid_count;
NvFlowUint grid_type;
NvFlowUint3 subGridDimLessOne;
NvFlowUint pad3;
NvFlowUint3 subGridDimBits;
NvFlowUint pad4;
};
#ifdef NV_FLOW_CPU
typedef struct NvFlowSparseNanoVdbParams NvFlowSparseNanoVdbParams;
#endif
#endif |
NVIDIA-Omniverse/PhysX/flow/include/nvflow/shaders/PNanoVDB.h |
// Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
/*!
\file PNanoVDB.h
\author Andrew Reidmeyer
\brief This file is a portable (e.g. pointer-less) C99/GLSL/HLSL port
of NanoVDB.h, which is compatible with most graphics APIs.
*/
#ifndef NANOVDB_PNANOVDB_H_HAS_BEEN_INCLUDED
#define NANOVDB_PNANOVDB_H_HAS_BEEN_INCLUDED
// ------------------------------------------------ Configuration -----------------------------------------------------------
// platforms
//#define PNANOVDB_C
//#define PNANOVDB_HLSL
//#define PNANOVDB_GLSL
// addressing mode
// PNANOVDB_ADDRESS_32
// PNANOVDB_ADDRESS_64
#if defined(PNANOVDB_C)
#ifndef PNANOVDB_ADDRESS_32
#define PNANOVDB_ADDRESS_64
#endif
#elif defined(PNANOVDB_HLSL)
#ifndef PNANOVDB_ADDRESS_64
#define PNANOVDB_ADDRESS_32
#endif
#elif defined(PNANOVDB_GLSL)
#ifndef PNANOVDB_ADDRESS_64
#define PNANOVDB_ADDRESS_32
#endif
#endif
// bounds checking
//#define PNANOVDB_BUF_BOUNDS_CHECK
// enable HDDA by default on HLSL/GLSL, make explicit on C
#if defined(PNANOVDB_C)
//#define PNANOVDB_HDDA
#ifdef PNANOVDB_HDDA
#ifndef PNANOVDB_CMATH
#define PNANOVDB_CMATH
#endif
#endif
#elif defined(PNANOVDB_HLSL)
#define PNANOVDB_HDDA
#elif defined(PNANOVDB_GLSL)
#define PNANOVDB_HDDA
#endif
#ifdef PNANOVDB_CMATH
#include <math.h>
#endif
// ------------------------------------------------ Buffer -----------------------------------------------------------
#if defined(PNANOVDB_BUF_CUSTOM)
// NOP
#elif defined(PNANOVDB_C)
#define PNANOVDB_BUF_C
#elif defined(PNANOVDB_HLSL)
#define PNANOVDB_BUF_HLSL
#elif defined(PNANOVDB_GLSL)
#define PNANOVDB_BUF_GLSL
#endif
#if defined(PNANOVDB_BUF_C)
#include <stdint.h>
#if defined(_WIN32)
#define PNANOVDB_BUF_FORCE_INLINE static inline __forceinline
#else
#define PNANOVDB_BUF_FORCE_INLINE static inline __attribute__((always_inline))
#endif
typedef struct pnanovdb_buf_t
{
uint32_t* data;
#ifdef PNANOVDB_BUF_BOUNDS_CHECK
uint64_t size_in_words;
#endif
}pnanovdb_buf_t;
PNANOVDB_BUF_FORCE_INLINE pnanovdb_buf_t pnanovdb_make_buf(uint32_t* data, uint64_t size_in_words)
{
pnanovdb_buf_t ret;
ret.data = data;
#ifdef PNANOVDB_BUF_BOUNDS_CHECK
ret.size_in_words = size_in_words;
#endif
return ret;
}
#if defined(PNANOVDB_ADDRESS_32)
PNANOVDB_BUF_FORCE_INLINE uint32_t pnanovdb_buf_read_uint32(pnanovdb_buf_t buf, uint32_t byte_offset)
{
uint32_t wordaddress = (byte_offset >> 2u);
#ifdef PNANOVDB_BUF_BOUNDS_CHECK
return wordaddress < buf.size_in_words ? buf.data[wordaddress] : 0u;
#else
return buf.data[wordaddress];
#endif
}
PNANOVDB_BUF_FORCE_INLINE uint64_t pnanovdb_buf_read_uint64(pnanovdb_buf_t buf, uint32_t byte_offset)
{
uint64_t* data64 = (uint64_t*)buf.data;
uint32_t wordaddress64 = (byte_offset >> 3u);
#ifdef PNANOVDB_BUF_BOUNDS_CHECK
uint64_t size_in_words64 = buf.size_in_words >> 1u;
return wordaddress64 < size_in_words64 ? data64[wordaddress64] : 0llu;
#else
return data64[wordaddress64];
#endif
}
#elif defined(PNANOVDB_ADDRESS_64)
PNANOVDB_BUF_FORCE_INLINE uint32_t pnanovdb_buf_read_uint32(pnanovdb_buf_t buf, uint64_t byte_offset)
{
uint64_t wordaddress = (byte_offset >> 2u);
#ifdef PNANOVDB_BUF_BOUNDS_CHECK
return wordaddress < buf.size_in_words ? buf.data[wordaddress] : 0u;
#else
return buf.data[wordaddress];
#endif
}
PNANOVDB_BUF_FORCE_INLINE uint64_t pnanovdb_buf_read_uint64(pnanovdb_buf_t buf, uint64_t byte_offset)
{
uint64_t* data64 = (uint64_t*)buf.data;
uint64_t wordaddress64 = (byte_offset >> 3u);
#ifdef PNANOVDB_BUF_BOUNDS_CHECK
uint64_t size_in_words64 = buf.size_in_words >> 1u;
return wordaddress64 < size_in_words64 ? data64[wordaddress64] : 0llu;
#else
return data64[wordaddress64];
#endif
}
#endif
typedef uint32_t pnanovdb_grid_type_t;
#define PNANOVDB_GRID_TYPE_GET(grid_typeIn, nameIn) pnanovdb_grid_type_constants[grid_typeIn].nameIn
#elif defined(PNANOVDB_BUF_HLSL)
#if defined(PNANOVDB_ADDRESS_32)
#define pnanovdb_buf_t StructuredBuffer<uint>
uint pnanovdb_buf_read_uint32(pnanovdb_buf_t buf, uint byte_offset)
{
return buf[(byte_offset >> 2u)];
}
uint2 pnanovdb_buf_read_uint64(pnanovdb_buf_t buf, uint byte_offset)
{
uint2 ret;
ret.x = pnanovdb_buf_read_uint32(buf, byte_offset + 0u);
ret.y = pnanovdb_buf_read_uint32(buf, byte_offset + 4u);
return ret;
}
#elif defined(PNANOVDB_ADDRESS_64)
#define pnanovdb_buf_t StructuredBuffer<uint>
uint pnanovdb_buf_read_uint32(pnanovdb_buf_t buf, uint64_t byte_offset)
{
return buf[uint(byte_offset >> 2u)];
}
uint64_t pnanovdb_buf_read_uint64(pnanovdb_buf_t buf, uint64_t byte_offset)
{
uint64_t ret;
ret = pnanovdb_buf_read_uint32(buf, byte_offset + 0u);
ret = ret + (uint64_t(pnanovdb_buf_read_uint32(buf, byte_offset + 4u)) << 32u);
return ret;
}
#endif
#define pnanovdb_grid_type_t uint
#define PNANOVDB_GRID_TYPE_GET(grid_typeIn, nameIn) pnanovdb_grid_type_constants[grid_typeIn].nameIn
#elif defined(PNANOVDB_BUF_GLSL)
struct pnanovdb_buf_t
{
uint unused; // to satisfy min struct size?
};
uint pnanovdb_buf_read_uint32(pnanovdb_buf_t buf, uint byte_offset)
{
return pnanovdb_buf_data[(byte_offset >> 2u)];
}
uvec2 pnanovdb_buf_read_uint64(pnanovdb_buf_t buf, uint byte_offset)
{
uvec2 ret;
ret.x = pnanovdb_buf_read_uint32(buf, byte_offset + 0u);
ret.y = pnanovdb_buf_read_uint32(buf, byte_offset + 4u);
return ret;
}
#define pnanovdb_grid_type_t uint
#define PNANOVDB_GRID_TYPE_GET(grid_typeIn, nameIn) pnanovdb_grid_type_constants[grid_typeIn].nameIn
#endif
// ------------------------------------------------ Basic Types -----------------------------------------------------------
// force inline
#if defined(PNANOVDB_C)
#if defined(_WIN32)
#define PNANOVDB_FORCE_INLINE static inline __forceinline
#else
#define PNANOVDB_FORCE_INLINE static inline __attribute__((always_inline))
#endif
#elif defined(PNANOVDB_HLSL)
#define PNANOVDB_FORCE_INLINE
#elif defined(PNANOVDB_GLSL)
#define PNANOVDB_FORCE_INLINE
#endif
// struct typedef, static const, inout
#if defined(PNANOVDB_C)
#define PNANOVDB_STRUCT_TYPEDEF(X) typedef struct X X;
#define PNANOVDB_STATIC_CONST static const
#define PNANOVDB_INOUT(X) X*
#define PNANOVDB_IN(X) const X*
#define PNANOVDB_DEREF(X) (*X)
#define PNANOVDB_REF(X) &X
#elif defined(PNANOVDB_HLSL)
#define PNANOVDB_STRUCT_TYPEDEF(X)
#define PNANOVDB_STATIC_CONST static const
#define PNANOVDB_INOUT(X) inout X
#define PNANOVDB_IN(X) X
#define PNANOVDB_DEREF(X) X
#define PNANOVDB_REF(X) X
#elif defined(PNANOVDB_GLSL)
#define PNANOVDB_STRUCT_TYPEDEF(X)
#define PNANOVDB_STATIC_CONST const
#define PNANOVDB_INOUT(X) inout X
#define PNANOVDB_IN(X) X
#define PNANOVDB_DEREF(X) X
#define PNANOVDB_REF(X) X
#endif
// basic types, type conversion
#if defined(PNANOVDB_C)
#define PNANOVDB_NATIVE_64
#include <stdint.h>
#if !defined(PNANOVDB_MEMCPY_CUSTOM)
#include <string.h>
#define pnanovdb_memcpy memcpy
#endif
typedef uint32_t pnanovdb_uint32_t;
typedef int32_t pnanovdb_int32_t;
typedef int32_t pnanovdb_bool_t;
#define PNANOVDB_FALSE 0
#define PNANOVDB_TRUE 1
typedef uint64_t pnanovdb_uint64_t;
typedef int64_t pnanovdb_int64_t;
typedef struct pnanovdb_coord_t
{
pnanovdb_int32_t x, y, z;
}pnanovdb_coord_t;
typedef struct pnanovdb_vec3_t
{
float x, y, z;
}pnanovdb_vec3_t;
PNANOVDB_FORCE_INLINE pnanovdb_int32_t pnanovdb_uint32_as_int32(pnanovdb_uint32_t v) { return (pnanovdb_int32_t)v; }
PNANOVDB_FORCE_INLINE pnanovdb_int64_t pnanovdb_uint64_as_int64(pnanovdb_uint64_t v) { return (pnanovdb_int64_t)v; }
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_int64_as_uint64(pnanovdb_int64_t v) { return (pnanovdb_uint64_t)v; }
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_int32_as_uint32(pnanovdb_int32_t v) { return (pnanovdb_uint32_t)v; }
PNANOVDB_FORCE_INLINE float pnanovdb_uint32_as_float(pnanovdb_uint32_t v) { float vf; pnanovdb_memcpy(&vf, &v, sizeof(vf)); return vf; }
PNANOVDB_FORCE_INLINE double pnanovdb_uint64_as_double(pnanovdb_uint64_t v) { double vf; pnanovdb_memcpy(&vf, &v, sizeof(vf)); return vf; }
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_uint64_low(pnanovdb_uint64_t v) { return (pnanovdb_uint32_t)v; }
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_uint64_high(pnanovdb_uint64_t v) { return (pnanovdb_uint32_t)(v >> 32u); }
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_uint32_as_uint64(pnanovdb_uint32_t x, pnanovdb_uint32_t y) { return ((pnanovdb_uint64_t)x) | (((pnanovdb_uint64_t)y) << 32u); }
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_uint32_as_uint64_low(pnanovdb_uint32_t x) { return ((pnanovdb_uint64_t)x); }
PNANOVDB_FORCE_INLINE pnanovdb_int32_t pnanovdb_uint64_is_equal(pnanovdb_uint64_t a, pnanovdb_uint64_t b) { return a == b; }
PNANOVDB_FORCE_INLINE pnanovdb_int32_t pnanovdb_int64_is_zero(pnanovdb_int64_t a) { return a == 0; }
#ifdef PNANOVDB_CMATH
PNANOVDB_FORCE_INLINE float pnanovdb_floor(float v) { return floorf(v); }
#endif
PNANOVDB_FORCE_INLINE pnanovdb_int32_t pnanovdb_float_to_int32(float v) { return (pnanovdb_int32_t)v; }
PNANOVDB_FORCE_INLINE float pnanovdb_int32_to_float(pnanovdb_int32_t v) { return (float)v; }
PNANOVDB_FORCE_INLINE float pnanovdb_uint32_to_float(pnanovdb_uint32_t v) { return (float)v; }
PNANOVDB_FORCE_INLINE float pnanovdb_min(float a, float b) { return a < b ? a : b; }
PNANOVDB_FORCE_INLINE float pnanovdb_max(float a, float b) { return a > b ? a : b; }
#elif defined(PNANOVDB_HLSL)
typedef uint pnanovdb_uint32_t;
typedef int pnanovdb_int32_t;
typedef bool pnanovdb_bool_t;
#define PNANOVDB_FALSE false
#define PNANOVDB_TRUE true
typedef int3 pnanovdb_coord_t;
typedef float3 pnanovdb_vec3_t;
pnanovdb_int32_t pnanovdb_uint32_as_int32(pnanovdb_uint32_t v) { return int(v); }
pnanovdb_uint32_t pnanovdb_int32_as_uint32(pnanovdb_int32_t v) { return uint(v); }
float pnanovdb_uint32_as_float(pnanovdb_uint32_t v) { return asfloat(v); }
float pnanovdb_floor(float v) { return floor(v); }
pnanovdb_int32_t pnanovdb_float_to_int32(float v) { return int(v); }
float pnanovdb_int32_to_float(pnanovdb_int32_t v) { return float(v); }
float pnanovdb_uint32_to_float(pnanovdb_uint32_t v) { return float(v); }
float pnanovdb_min(float a, float b) { return min(a, b); }
float pnanovdb_max(float a, float b) { return max(a, b); }
#if defined(PNANOVDB_ADDRESS_32)
typedef uint2 pnanovdb_uint64_t;
typedef int2 pnanovdb_int64_t;
pnanovdb_int64_t pnanovdb_uint64_as_int64(pnanovdb_uint64_t v) { return int2(v); }
pnanovdb_uint64_t pnanovdb_int64_as_uint64(pnanovdb_int64_t v) { return uint2(v); }
double pnanovdb_uint64_as_double(pnanovdb_uint64_t v) { return asdouble(v.x, v.y); }
pnanovdb_uint32_t pnanovdb_uint64_low(pnanovdb_uint64_t v) { return v.x; }
pnanovdb_uint32_t pnanovdb_uint64_high(pnanovdb_uint64_t v) { return v.y; }
pnanovdb_uint64_t pnanovdb_uint32_as_uint64(pnanovdb_uint32_t x, pnanovdb_uint32_t y) { return uint2(x, y); }
pnanovdb_uint64_t pnanovdb_uint32_as_uint64_low(pnanovdb_uint32_t x) { return uint2(x, 0); }
bool pnanovdb_uint64_is_equal(pnanovdb_uint64_t a, pnanovdb_uint64_t b) { return (a.x == b.x) && (a.y == b.y); }
bool pnanovdb_int64_is_zero(pnanovdb_int64_t a) { return a.x == 0 && a.y == 0; }
#else
typedef uint64_t pnanovdb_uint64_t;
typedef int64_t pnanovdb_int64_t;
pnanovdb_int64_t pnanovdb_uint64_as_int64(pnanovdb_uint64_t v) { return int64_t(v); }
pnanovdb_uint64_t pnanovdb_int64_as_uint64(pnanovdb_int64_t v) { return uint64_t(v); }
double pnanovdb_uint64_as_double(pnanovdb_uint64_t v) { return asdouble(uint(v), uint(v >> 32u)); }
pnanovdb_uint32_t pnanovdb_uint64_low(pnanovdb_uint64_t v) { return uint(v); }
pnanovdb_uint32_t pnanovdb_uint64_high(pnanovdb_uint64_t v) { return uint(v >> 32u); }
pnanovdb_uint64_t pnanovdb_uint32_as_uint64(pnanovdb_uint32_t x, pnanovdb_uint32_t y) { return uint64_t(x) + (uint64_t(y) << 32u); }
pnanovdb_uint64_t pnanovdb_uint32_as_uint64_low(pnanovdb_uint32_t x) { return uint64_t(x); }
bool pnanovdb_uint64_is_equal(pnanovdb_uint64_t a, pnanovdb_uint64_t b) { return a == b; }
bool pnanovdb_int64_is_zero(pnanovdb_int64_t a) { return a == 0; }
#endif
#elif defined(PNANOVDB_GLSL)
#define pnanovdb_uint32_t uint
#define pnanovdb_int32_t int
#define pnanovdb_bool_t bool
#define PNANOVDB_FALSE false
#define PNANOVDB_TRUE true
#define pnanovdb_uint64_t uvec2
#define pnanovdb_int64_t ivec2
#define pnanovdb_coord_t ivec3
#define pnanovdb_vec3_t vec3
pnanovdb_int32_t pnanovdb_uint32_as_int32(pnanovdb_uint32_t v) { return int(v); }
pnanovdb_int64_t pnanovdb_uint64_as_int64(pnanovdb_uint64_t v) { return ivec2(v); }
pnanovdb_uint64_t pnanovdb_int64_as_uint64(pnanovdb_int64_t v) { return uvec2(v); }
pnanovdb_uint32_t pnanovdb_int32_as_uint32(pnanovdb_int32_t v) { return uint(v); }
float pnanovdb_uint32_as_float(pnanovdb_uint32_t v) { return uintBitsToFloat(v); }
double pnanovdb_uint64_as_double(pnanovdb_uint64_t v) { return packDouble2x32(uvec2(v.x, v.y)); }
pnanovdb_uint32_t pnanovdb_uint64_low(pnanovdb_uint64_t v) { return v.x; }
pnanovdb_uint32_t pnanovdb_uint64_high(pnanovdb_uint64_t v) { return v.y; }
pnanovdb_uint64_t pnanovdb_uint32_as_uint64(pnanovdb_uint32_t x, pnanovdb_uint32_t y) { return uvec2(x, y); }
pnanovdb_uint64_t pnanovdb_uint32_as_uint64_low(pnanovdb_uint32_t x) { return uvec2(x, 0); }
bool pnanovdb_uint64_is_equal(pnanovdb_uint64_t a, pnanovdb_uint64_t b) { return (a.x == b.x) && (a.y == b.y); }
bool pnanovdb_int64_is_zero(pnanovdb_int64_t a) { return a.x == 0 && a.y == 0; }
float pnanovdb_floor(float v) { return floor(v); }
pnanovdb_int32_t pnanovdb_float_to_int32(float v) { return int(v); }
float pnanovdb_int32_to_float(pnanovdb_int32_t v) { return float(v); }
float pnanovdb_uint32_to_float(pnanovdb_uint32_t v) { return float(v); }
float pnanovdb_min(float a, float b) { return min(a, b); }
float pnanovdb_max(float a, float b) { return max(a, b); }
#endif
// ------------------------------------------------ Coord/Vec3 Utilties -----------------------------------------------------------
#if defined(PNANOVDB_C)
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_vec3_uniform(float a)
{
pnanovdb_vec3_t v;
v.x = a;
v.y = a;
v.z = a;
return v;
}
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_vec3_add(const pnanovdb_vec3_t a, const pnanovdb_vec3_t b)
{
pnanovdb_vec3_t v;
v.x = a.x + b.x;
v.y = a.y + b.y;
v.z = a.z + b.z;
return v;
}
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_vec3_sub(const pnanovdb_vec3_t a, const pnanovdb_vec3_t b)
{
pnanovdb_vec3_t v;
v.x = a.x - b.x;
v.y = a.y - b.y;
v.z = a.z - b.z;
return v;
}
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_vec3_mul(const pnanovdb_vec3_t a, const pnanovdb_vec3_t b)
{
pnanovdb_vec3_t v;
v.x = a.x * b.x;
v.y = a.y * b.y;
v.z = a.z * b.z;
return v;
}
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_vec3_div(const pnanovdb_vec3_t a, const pnanovdb_vec3_t b)
{
pnanovdb_vec3_t v;
v.x = a.x / b.x;
v.y = a.y / b.y;
v.z = a.z / b.z;
return v;
}
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_vec3_min(const pnanovdb_vec3_t a, const pnanovdb_vec3_t b)
{
pnanovdb_vec3_t v;
v.x = a.x < b.x ? a.x : b.x;
v.y = a.y < b.y ? a.y : b.y;
v.z = a.z < b.z ? a.z : b.z;
return v;
}
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_vec3_max(const pnanovdb_vec3_t a, const pnanovdb_vec3_t b)
{
pnanovdb_vec3_t v;
v.x = a.x > b.x ? a.x : b.x;
v.y = a.y > b.y ? a.y : b.y;
v.z = a.z > b.z ? a.z : b.z;
return v;
}
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_coord_to_vec3(const pnanovdb_coord_t coord)
{
pnanovdb_vec3_t v;
v.x = pnanovdb_int32_to_float(coord.x);
v.y = pnanovdb_int32_to_float(coord.y);
v.z = pnanovdb_int32_to_float(coord.z);
return v;
}
PNANOVDB_FORCE_INLINE pnanovdb_coord_t pnanovdb_coord_uniform(const pnanovdb_int32_t a)
{
pnanovdb_coord_t v;
v.x = a;
v.y = a;
v.z = a;
return v;
}
PNANOVDB_FORCE_INLINE pnanovdb_coord_t pnanovdb_coord_add(pnanovdb_coord_t a, pnanovdb_coord_t b)
{
pnanovdb_coord_t v;
v.x = a.x + b.x;
v.y = a.y + b.y;
v.z = a.z + b.z;
return v;
}
#elif defined(PNANOVDB_HLSL)
pnanovdb_vec3_t pnanovdb_vec3_uniform(float a) { return float3(a, a, a); }
pnanovdb_vec3_t pnanovdb_vec3_add(pnanovdb_vec3_t a, pnanovdb_vec3_t b) { return a + b; }
pnanovdb_vec3_t pnanovdb_vec3_sub(pnanovdb_vec3_t a, pnanovdb_vec3_t b) { return a - b; }
pnanovdb_vec3_t pnanovdb_vec3_mul(pnanovdb_vec3_t a, pnanovdb_vec3_t b) { return a * b; }
pnanovdb_vec3_t pnanovdb_vec3_div(pnanovdb_vec3_t a, pnanovdb_vec3_t b) { return a / b; }
pnanovdb_vec3_t pnanovdb_vec3_min(pnanovdb_vec3_t a, pnanovdb_vec3_t b) { return min(a, b); }
pnanovdb_vec3_t pnanovdb_vec3_max(pnanovdb_vec3_t a, pnanovdb_vec3_t b) { return max(a, b); }
pnanovdb_vec3_t pnanovdb_coord_to_vec3(pnanovdb_coord_t coord) { return float3(coord); }
pnanovdb_coord_t pnanovdb_coord_uniform(pnanovdb_int32_t a) { return int3(a, a, a); }
pnanovdb_coord_t pnanovdb_coord_add(pnanovdb_coord_t a, pnanovdb_coord_t b) { return a + b; }
#elif defined(PNANOVDB_GLSL)
pnanovdb_vec3_t pnanovdb_vec3_uniform(float a) { return vec3(a, a, a); }
pnanovdb_vec3_t pnanovdb_vec3_add(pnanovdb_vec3_t a, pnanovdb_vec3_t b) { return a + b; }
pnanovdb_vec3_t pnanovdb_vec3_sub(pnanovdb_vec3_t a, pnanovdb_vec3_t b) { return a - b; }
pnanovdb_vec3_t pnanovdb_vec3_mul(pnanovdb_vec3_t a, pnanovdb_vec3_t b) { return a * b; }
pnanovdb_vec3_t pnanovdb_vec3_div(pnanovdb_vec3_t a, pnanovdb_vec3_t b) { return a / b; }
pnanovdb_vec3_t pnanovdb_vec3_min(pnanovdb_vec3_t a, pnanovdb_vec3_t b) { return min(a, b); }
pnanovdb_vec3_t pnanovdb_vec3_max(pnanovdb_vec3_t a, pnanovdb_vec3_t b) { return max(a, b); }
pnanovdb_vec3_t pnanovdb_coord_to_vec3(const pnanovdb_coord_t coord) { return vec3(coord); }
pnanovdb_coord_t pnanovdb_coord_uniform(pnanovdb_int32_t a) { return ivec3(a, a, a); }
pnanovdb_coord_t pnanovdb_coord_add(pnanovdb_coord_t a, pnanovdb_coord_t b) { return a + b; }
#endif
// ------------------------------------------------ Address Type -----------------------------------------------------------
#if defined(PNANOVDB_ADDRESS_32)
struct pnanovdb_address_t
{
pnanovdb_uint32_t byte_offset;
};
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_address_t)
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_address_offset(pnanovdb_address_t address, pnanovdb_uint32_t byte_offset)
{
pnanovdb_address_t ret = address;
ret.byte_offset += byte_offset;
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_address_offset_neg(pnanovdb_address_t address, pnanovdb_uint32_t byte_offset)
{
pnanovdb_address_t ret = address;
ret.byte_offset -= byte_offset;
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_address_offset_product(pnanovdb_address_t address, pnanovdb_uint32_t byte_offset, pnanovdb_uint32_t multiplier)
{
pnanovdb_address_t ret = address;
ret.byte_offset += byte_offset * multiplier;
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_address_offset64(pnanovdb_address_t address, pnanovdb_uint64_t byte_offset)
{
pnanovdb_address_t ret = address;
// lose high bits on 32-bit
ret.byte_offset += pnanovdb_uint64_low(byte_offset);
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_address_mask(pnanovdb_address_t address, pnanovdb_uint32_t mask)
{
return address.byte_offset & mask;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_address_mask_inv(pnanovdb_address_t address, pnanovdb_uint32_t mask)
{
pnanovdb_address_t ret = address;
ret.byte_offset &= (~mask);
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_address_null()
{
pnanovdb_address_t ret = { 0 };
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_address_is_null(pnanovdb_address_t address)
{
return address.byte_offset == 0u;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_address_in_interval(pnanovdb_address_t address, pnanovdb_address_t min_address, pnanovdb_address_t max_address)
{
return address.byte_offset >= min_address.byte_offset && address.byte_offset < max_address.byte_offset;
}
#elif defined(PNANOVDB_ADDRESS_64)
struct pnanovdb_address_t
{
pnanovdb_uint64_t byte_offset;
};
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_address_t)
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_address_offset(pnanovdb_address_t address, pnanovdb_uint32_t byte_offset)
{
pnanovdb_address_t ret = address;
ret.byte_offset += byte_offset;
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_address_offset_neg(pnanovdb_address_t address, pnanovdb_uint32_t byte_offset)
{
pnanovdb_address_t ret = address;
ret.byte_offset -= byte_offset;
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_address_offset_product(pnanovdb_address_t address, pnanovdb_uint32_t byte_offset, pnanovdb_uint32_t multiplier)
{
pnanovdb_address_t ret = address;
ret.byte_offset += pnanovdb_uint32_as_uint64_low(byte_offset) * pnanovdb_uint32_as_uint64_low(multiplier);
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_address_offset64(pnanovdb_address_t address, pnanovdb_uint64_t byte_offset)
{
pnanovdb_address_t ret = address;
ret.byte_offset += byte_offset;
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_address_mask(pnanovdb_address_t address, pnanovdb_uint32_t mask)
{
return pnanovdb_uint64_low(address.byte_offset) & mask;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_address_mask_inv(pnanovdb_address_t address, pnanovdb_uint32_t mask)
{
pnanovdb_address_t ret = address;
ret.byte_offset &= (~pnanovdb_uint32_as_uint64_low(mask));
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_address_null()
{
pnanovdb_address_t ret = { 0 };
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_address_is_null(pnanovdb_address_t address)
{
return address.byte_offset == 0llu;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_address_in_interval(pnanovdb_address_t address, pnanovdb_address_t min_address, pnanovdb_address_t max_address)
{
return address.byte_offset >= min_address.byte_offset && address.byte_offset < max_address.byte_offset;
}
#endif
// ------------------------------------------------ High Level Buffer Read -----------------------------------------------------------
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_read_uint32(pnanovdb_buf_t buf, pnanovdb_address_t address)
{
return pnanovdb_buf_read_uint32(buf, address.byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_read_uint64(pnanovdb_buf_t buf, pnanovdb_address_t address)
{
return pnanovdb_buf_read_uint64(buf, address.byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_int32_t pnanovdb_read_int32(pnanovdb_buf_t buf, pnanovdb_address_t address)
{
return pnanovdb_uint32_as_int32(pnanovdb_read_uint32(buf, address));
}
PNANOVDB_FORCE_INLINE float pnanovdb_read_float(pnanovdb_buf_t buf, pnanovdb_address_t address)
{
return pnanovdb_uint32_as_float(pnanovdb_read_uint32(buf, address));
}
PNANOVDB_FORCE_INLINE pnanovdb_int64_t pnanovdb_read_int64(pnanovdb_buf_t buf, pnanovdb_address_t address)
{
return pnanovdb_uint64_as_int64(pnanovdb_read_uint64(buf, address));
}
PNANOVDB_FORCE_INLINE double pnanovdb_read_double(pnanovdb_buf_t buf, pnanovdb_address_t address)
{
return pnanovdb_uint64_as_double(pnanovdb_read_uint64(buf, address));
}
PNANOVDB_FORCE_INLINE pnanovdb_coord_t pnanovdb_read_coord(pnanovdb_buf_t buf, pnanovdb_address_t address)
{
pnanovdb_coord_t ret;
ret.x = pnanovdb_uint32_as_int32(pnanovdb_read_uint32(buf, pnanovdb_address_offset(address, 0u)));
ret.y = pnanovdb_uint32_as_int32(pnanovdb_read_uint32(buf, pnanovdb_address_offset(address, 4u)));
ret.z = pnanovdb_uint32_as_int32(pnanovdb_read_uint32(buf, pnanovdb_address_offset(address, 8u)));
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_read_bit(pnanovdb_buf_t buf, pnanovdb_address_t address, pnanovdb_uint32_t bit_offset)
{
pnanovdb_address_t word_address = pnanovdb_address_mask_inv(address, 3u);
pnanovdb_uint32_t bit_index = (pnanovdb_address_mask(address, 3u) << 3u) + bit_offset;
pnanovdb_uint32_t value_word = pnanovdb_buf_read_uint32(buf, word_address.byte_offset);
return ((value_word >> bit_index) & 1) != 0u;
}
#if defined(PNANOVDB_C)
PNANOVDB_FORCE_INLINE short pnanovdb_read_half(pnanovdb_buf_t buf, pnanovdb_address_t address)
{
pnanovdb_uint32_t raw = pnanovdb_read_uint32(buf, address);
return (short)(raw >> (pnanovdb_address_mask(address, 2) << 3));
}
#elif defined(PNANOVDB_HLSL)
PNANOVDB_FORCE_INLINE float pnanovdb_read_half(pnanovdb_buf_t buf, pnanovdb_address_t address)
{
pnanovdb_uint32_t raw = pnanovdb_read_uint32(buf, address);
return f16tof32(raw >> (pnanovdb_address_mask(address, 2) << 3));
}
#elif defined(PNANOVDB_GLSL)
PNANOVDB_FORCE_INLINE float pnanovdb_read_half(pnanovdb_buf_t buf, pnanovdb_address_t address)
{
pnanovdb_uint32_t raw = pnanovdb_read_uint32(buf, address);
return unpackHalf2x16(raw >> (pnanovdb_address_mask(address, 2) << 3)).x;
}
#endif
// ------------------------------------------------ Core Structures -----------------------------------------------------------
#define PNANOVDB_MAGIC_NUMBER 0x304244566f6e614eUL// "NanoVDB0" in hex - little endian (uint64_t)
#define PNANOVDB_MAJOR_VERSION_NUMBER 32// reflects changes to the ABI
#define PNANOVDB_MINOR_VERSION_NUMBER 3// reflects changes to the API but not ABI
#define PNANOVDB_PATCH_VERSION_NUMBER 0// reflects bug-fixes with no ABI or API changes
#define PNANOVDB_GRID_TYPE_UNKNOWN 0
#define PNANOVDB_GRID_TYPE_FLOAT 1
#define PNANOVDB_GRID_TYPE_DOUBLE 2
#define PNANOVDB_GRID_TYPE_INT16 3
#define PNANOVDB_GRID_TYPE_INT32 4
#define PNANOVDB_GRID_TYPE_INT64 5
#define PNANOVDB_GRID_TYPE_VEC3F 6
#define PNANOVDB_GRID_TYPE_VEC3D 7
#define PNANOVDB_GRID_TYPE_MASK 8
#define PNANOVDB_GRID_TYPE_HALF 9
#define PNANOVDB_GRID_TYPE_UINT32 10
#define PNANOVDB_GRID_TYPE_BOOLEAN 11
#define PNANOVDB_GRID_TYPE_RGBA8 12
#define PNANOVDB_GRID_TYPE_FP4 13
#define PNANOVDB_GRID_TYPE_FP8 14
#define PNANOVDB_GRID_TYPE_FP16 15
#define PNANOVDB_GRID_TYPE_FPN 16
#define PNANOVDB_GRID_TYPE_VEC4F 17
#define PNANOVDB_GRID_TYPE_VEC4D 18
#define PNANOVDB_GRID_TYPE_END 19
#define PNANOVDB_GRID_CLASS_UNKNOWN 0
#define PNANOVDB_GRID_CLASS_LEVEL_SET 1 // narrow band levelset, e.g. SDF
#define PNANOVDB_GRID_CLASS_FOG_VOLUME 2 // fog volume, e.g. density
#define PNANOVDB_GRID_CLASS_STAGGERED 3 // staggered MAC grid, e.g. velocity
#define PNANOVDB_GRID_CLASS_POINT_INDEX 4 // point index grid
#define PNANOVDB_GRID_CLASS_POINT_DATA 5 // point data grid
#define PNANOVDB_GRID_CLASS_TOPOLOGY 6 // grid with active states only (no values)
#define PNANOVDB_GRID_CLASS_VOXEL_VOLUME 7 // volume of geometric cubes, e.g. minecraft
#define PNANOVDB_GRID_CLASS_END 8
#define PNANOVDB_GRID_FLAGS_HAS_LONG_GRID_NAME (1 << 0)
#define PNANOVDB_GRID_FLAGS_HAS_BBOX (1 << 1)
#define PNANOVDB_GRID_FLAGS_HAS_MIN_MAX (1 << 2)
#define PNANOVDB_GRID_FLAGS_HAS_AVERAGE (1 << 3)
#define PNANOVDB_GRID_FLAGS_HAS_STD_DEVIATION (1 << 4)
#define PNANOVDB_GRID_FLAGS_IS_BREADTH_FIRST (1 << 5)
#define PNANOVDB_GRID_FLAGS_END (1 << 6)
#define PNANOVDB_LEAF_TYPE_DEFAULT 0
#define PNANOVDB_LEAF_TYPE_LITE 1
#define PNANOVDB_LEAF_TYPE_FP 2
PNANOVDB_STATIC_CONST pnanovdb_uint32_t pnanovdb_grid_type_value_strides_bits[PNANOVDB_GRID_TYPE_END] = { 0, 32, 64, 16, 32, 64, 96, 192, 0, 16, 32, 1, 32, 4, 8, 16, 0, 128, 256 };
PNANOVDB_STATIC_CONST pnanovdb_uint32_t pnanovdb_grid_type_table_strides_bits[PNANOVDB_GRID_TYPE_END] = { 64, 64, 64, 64, 64, 64, 128, 192, 64, 64, 64, 64, 64, 64, 64, 64, 64, 128, 256 };
PNANOVDB_STATIC_CONST pnanovdb_uint32_t pnanovdb_grid_type_minmax_strides_bits[PNANOVDB_GRID_TYPE_END] = { 0, 32, 64, 16, 32, 64, 96, 192, 8, 16, 32, 8, 32, 32, 32, 32, 32, 128, 256 };
PNANOVDB_STATIC_CONST pnanovdb_uint32_t pnanovdb_grid_type_minmax_aligns_bits[PNANOVDB_GRID_TYPE_END] = { 0, 32, 64, 16, 32, 64, 32, 64, 8, 16, 32, 8, 32, 32, 32, 32, 32, 32, 64 };
PNANOVDB_STATIC_CONST pnanovdb_uint32_t pnanovdb_grid_type_stat_strides_bits[PNANOVDB_GRID_TYPE_END] = { 0, 32, 64, 32, 32, 64, 32, 64, 8, 32, 32, 8, 32, 32, 32, 32, 32, 32, 64 };
PNANOVDB_STATIC_CONST pnanovdb_uint32_t pnanovdb_grid_type_leaf_type[PNANOVDB_GRID_TYPE_END] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 2, 2, 2, 2, 0, 0 };
struct pnanovdb_map_t
{
float matf[9];
float invmatf[9];
float vecf[3];
float taperf;
double matd[9];
double invmatd[9];
double vecd[3];
double taperd;
};
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_map_t)
struct pnanovdb_map_handle_t { pnanovdb_address_t address; };
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_map_handle_t)
#define PNANOVDB_MAP_SIZE 264
#define PNANOVDB_MAP_OFF_MATF 0
#define PNANOVDB_MAP_OFF_INVMATF 36
#define PNANOVDB_MAP_OFF_VECF 72
#define PNANOVDB_MAP_OFF_TAPERF 84
#define PNANOVDB_MAP_OFF_MATD 88
#define PNANOVDB_MAP_OFF_INVMATD 160
#define PNANOVDB_MAP_OFF_VECD 232
#define PNANOVDB_MAP_OFF_TAPERD 256
PNANOVDB_FORCE_INLINE float pnanovdb_map_get_matf(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index) {
return pnanovdb_read_float(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_MATF + 4u * index));
}
PNANOVDB_FORCE_INLINE float pnanovdb_map_get_invmatf(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index) {
return pnanovdb_read_float(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_INVMATF + 4u * index));
}
PNANOVDB_FORCE_INLINE float pnanovdb_map_get_vecf(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index) {
return pnanovdb_read_float(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_VECF + 4u * index));
}
PNANOVDB_FORCE_INLINE float pnanovdb_map_get_taperf(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index) {
return pnanovdb_read_float(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_TAPERF));
}
PNANOVDB_FORCE_INLINE double pnanovdb_map_get_matd(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index) {
return pnanovdb_read_double(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_MATD + 8u * index));
}
PNANOVDB_FORCE_INLINE double pnanovdb_map_get_invmatd(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index) {
return pnanovdb_read_double(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_INVMATD + 8u * index));
}
PNANOVDB_FORCE_INLINE double pnanovdb_map_get_vecd(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index) {
return pnanovdb_read_double(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_VECD + 8u * index));
}
PNANOVDB_FORCE_INLINE double pnanovdb_map_get_taperd(pnanovdb_buf_t buf, pnanovdb_map_handle_t p, pnanovdb_uint32_t index) {
return pnanovdb_read_double(buf, pnanovdb_address_offset(p.address, PNANOVDB_MAP_OFF_TAPERD));
}
struct pnanovdb_grid_t
{
pnanovdb_uint64_t magic; // 8 bytes, 0
pnanovdb_uint64_t checksum; // 8 bytes, 8
pnanovdb_uint32_t version; // 4 bytes, 16
pnanovdb_uint32_t flags; // 4 bytes, 20
pnanovdb_uint32_t grid_index; // 4 bytes, 24
pnanovdb_uint32_t grid_count; // 4 bytes, 28
pnanovdb_uint64_t grid_size; // 8 bytes, 32
pnanovdb_uint32_t grid_name[256 / 4]; // 256 bytes, 40
pnanovdb_map_t map; // 264 bytes, 296
double world_bbox[6]; // 48 bytes, 560
double voxel_size[3]; // 24 bytes, 608
pnanovdb_uint32_t grid_class; // 4 bytes, 632
pnanovdb_uint32_t grid_type; // 4 bytes, 636
pnanovdb_int64_t blind_metadata_offset; // 8 bytes, 640
pnanovdb_uint32_t blind_metadata_count; // 4 bytes, 648
pnanovdb_uint32_t pad[5]; // 20 bytes, 652
};
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_grid_t)
struct pnanovdb_grid_handle_t { pnanovdb_address_t address; };
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_grid_handle_t)
#define PNANOVDB_GRID_SIZE 672
#define PNANOVDB_GRID_OFF_MAGIC 0
#define PNANOVDB_GRID_OFF_CHECKSUM 8
#define PNANOVDB_GRID_OFF_VERSION 16
#define PNANOVDB_GRID_OFF_FLAGS 20
#define PNANOVDB_GRID_OFF_GRID_INDEX 24
#define PNANOVDB_GRID_OFF_GRID_COUNT 28
#define PNANOVDB_GRID_OFF_GRID_SIZE 32
#define PNANOVDB_GRID_OFF_GRID_NAME 40
#define PNANOVDB_GRID_OFF_MAP 296
#define PNANOVDB_GRID_OFF_WORLD_BBOX 560
#define PNANOVDB_GRID_OFF_VOXEL_SIZE 608
#define PNANOVDB_GRID_OFF_GRID_CLASS 632
#define PNANOVDB_GRID_OFF_GRID_TYPE 636
#define PNANOVDB_GRID_OFF_BLIND_METADATA_OFFSET 640
#define PNANOVDB_GRID_OFF_BLIND_METADATA_COUNT 648
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_grid_get_magic(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p) {
return pnanovdb_read_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_MAGIC));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_grid_get_checksum(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p) {
return pnanovdb_read_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_CHECKSUM));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_grid_get_version(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_VERSION));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_grid_get_flags(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_FLAGS));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_grid_get_grid_index(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_GRID_INDEX));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_grid_get_grid_count(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_GRID_COUNT));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_grid_get_grid_size(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p) {
return pnanovdb_read_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_GRID_SIZE));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_grid_get_grid_name(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint32_t index) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_GRID_NAME + 4u * index));
}
PNANOVDB_FORCE_INLINE pnanovdb_map_handle_t pnanovdb_grid_get_map(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p) {
pnanovdb_map_handle_t ret;
ret.address = pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_MAP);
return ret;
}
PNANOVDB_FORCE_INLINE double pnanovdb_grid_get_world_bbox(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint32_t index) {
return pnanovdb_read_double(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_WORLD_BBOX + 8u * index));
}
PNANOVDB_FORCE_INLINE double pnanovdb_grid_get_voxel_size(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p, pnanovdb_uint32_t index) {
return pnanovdb_read_double(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_VOXEL_SIZE + 8u * index));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_grid_get_grid_class(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_GRID_CLASS));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_grid_get_grid_type(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_GRID_TYPE));
}
PNANOVDB_FORCE_INLINE pnanovdb_int64_t pnanovdb_grid_get_blind_metadata_offset(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p) {
return pnanovdb_read_int64(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_BLIND_METADATA_OFFSET));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_grid_get_blind_metadata_count(pnanovdb_buf_t buf, pnanovdb_grid_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRID_OFF_BLIND_METADATA_COUNT));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_version_get_major(pnanovdb_uint32_t version)
{
return (version >> 21u) & ((1u << 11u) - 1u);
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_version_get_minor(pnanovdb_uint32_t version)
{
return (version >> 10u) & ((1u << 11u) - 1u);
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_version_get_patch(pnanovdb_uint32_t version)
{
return version & ((1u << 10u) - 1u);
}
struct pnanovdb_gridblindmetadata_t
{
pnanovdb_int64_t byte_offset; // 8 bytes, 0
pnanovdb_uint64_t element_count; // 8 bytes, 8
pnanovdb_uint32_t flags; // 4 bytes, 16
pnanovdb_uint32_t semantic; // 4 bytes, 20
pnanovdb_uint32_t data_class; // 4 bytes, 24
pnanovdb_uint32_t data_type; // 4 bytes, 28
pnanovdb_uint32_t name[256 / 4]; // 256 bytes, 32
};
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_gridblindmetadata_t)
struct pnanovdb_gridblindmetadata_handle_t { pnanovdb_address_t address; };
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_gridblindmetadata_handle_t)
#define PNANOVDB_GRIDBLINDMETADATA_SIZE 288
#define PNANOVDB_GRIDBLINDMETADATA_OFF_BYTE_OFFSET 0
#define PNANOVDB_GRIDBLINDMETADATA_OFF_ELEMENT_COUNT 8
#define PNANOVDB_GRIDBLINDMETADATA_OFF_FLAGS 16
#define PNANOVDB_GRIDBLINDMETADATA_OFF_SEMANTIC 20
#define PNANOVDB_GRIDBLINDMETADATA_OFF_DATA_CLASS 24
#define PNANOVDB_GRIDBLINDMETADATA_OFF_DATA_TYPE 28
#define PNANOVDB_GRIDBLINDMETADATA_OFF_NAME 32
PNANOVDB_FORCE_INLINE pnanovdb_int64_t pnanovdb_gridblindmetadata_get_byte_offset(pnanovdb_buf_t buf, pnanovdb_gridblindmetadata_handle_t p) {
return pnanovdb_read_int64(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRIDBLINDMETADATA_OFF_BYTE_OFFSET));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_gridblindmetadata_get_element_count(pnanovdb_buf_t buf, pnanovdb_gridblindmetadata_handle_t p) {
return pnanovdb_read_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRIDBLINDMETADATA_OFF_ELEMENT_COUNT));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_gridblindmetadata_get_flags(pnanovdb_buf_t buf, pnanovdb_gridblindmetadata_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRIDBLINDMETADATA_OFF_FLAGS));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_gridblindmetadata_get_semantic(pnanovdb_buf_t buf, pnanovdb_gridblindmetadata_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRIDBLINDMETADATA_OFF_SEMANTIC));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_gridblindmetadata_get_data_class(pnanovdb_buf_t buf, pnanovdb_gridblindmetadata_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRIDBLINDMETADATA_OFF_DATA_CLASS));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_gridblindmetadata_get_data_type(pnanovdb_buf_t buf, pnanovdb_gridblindmetadata_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRIDBLINDMETADATA_OFF_DATA_TYPE));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_gridblindmetadata_get_name(pnanovdb_buf_t buf, pnanovdb_gridblindmetadata_handle_t p, pnanovdb_uint32_t index) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_GRIDBLINDMETADATA_OFF_NAME + 4u * index));
}
struct pnanovdb_tree_t
{
pnanovdb_uint64_t node_offset_leaf;
pnanovdb_uint64_t node_offset_lower;
pnanovdb_uint64_t node_offset_upper;
pnanovdb_uint64_t node_offset_root;
pnanovdb_uint32_t node_count_leaf;
pnanovdb_uint32_t node_count_lower;
pnanovdb_uint32_t node_count_upper;
pnanovdb_uint32_t tile_count_leaf;
pnanovdb_uint32_t tile_count_lower;
pnanovdb_uint32_t tile_count_upper;
pnanovdb_uint64_t voxel_count;
};
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_tree_t)
struct pnanovdb_tree_handle_t { pnanovdb_address_t address; };
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_tree_handle_t)
#define PNANOVDB_TREE_SIZE 64
#define PNANOVDB_TREE_OFF_NODE_OFFSET_LEAF 0
#define PNANOVDB_TREE_OFF_NODE_OFFSET_LOWER 8
#define PNANOVDB_TREE_OFF_NODE_OFFSET_UPPER 16
#define PNANOVDB_TREE_OFF_NODE_OFFSET_ROOT 24
#define PNANOVDB_TREE_OFF_NODE_COUNT_LEAF 32
#define PNANOVDB_TREE_OFF_NODE_COUNT_LOWER 36
#define PNANOVDB_TREE_OFF_NODE_COUNT_UPPER 40
#define PNANOVDB_TREE_OFF_TILE_COUNT_LEAF 44
#define PNANOVDB_TREE_OFF_TILE_COUNT_LOWER 48
#define PNANOVDB_TREE_OFF_TILE_COUNT_UPPER 52
#define PNANOVDB_TREE_OFF_VOXEL_COUNT 56
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_tree_get_node_offset_leaf(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p) {
return pnanovdb_read_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_NODE_OFFSET_LEAF));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_tree_get_node_offset_lower(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p) {
return pnanovdb_read_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_NODE_OFFSET_LOWER));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_tree_get_node_offset_upper(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p) {
return pnanovdb_read_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_NODE_OFFSET_UPPER));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_tree_get_node_offset_root(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p) {
return pnanovdb_read_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_NODE_OFFSET_ROOT));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_tree_get_node_count_leaf(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_NODE_COUNT_LEAF));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_tree_get_node_count_lower(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_NODE_COUNT_LOWER));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_tree_get_node_count_upper(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_NODE_COUNT_UPPER));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_tree_get_tile_count_leaf(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_TILE_COUNT_LEAF));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_tree_get_tile_count_lower(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_TILE_COUNT_LOWER));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_tree_get_tile_count_upper(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_TILE_COUNT_UPPER));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_tree_get_voxel_count(pnanovdb_buf_t buf, pnanovdb_tree_handle_t p) {
return pnanovdb_read_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_TREE_OFF_VOXEL_COUNT));
}
struct pnanovdb_root_t
{
pnanovdb_coord_t bbox_min;
pnanovdb_coord_t bbox_max;
pnanovdb_uint32_t table_size;
pnanovdb_uint32_t pad1; // background can start here
// background, min, max
};
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_root_t)
struct pnanovdb_root_handle_t { pnanovdb_address_t address; };
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_root_handle_t)
#define PNANOVDB_ROOT_BASE_SIZE 28
#define PNANOVDB_ROOT_OFF_BBOX_MIN 0
#define PNANOVDB_ROOT_OFF_BBOX_MAX 12
#define PNANOVDB_ROOT_OFF_TABLE_SIZE 24
PNANOVDB_FORCE_INLINE pnanovdb_coord_t pnanovdb_root_get_bbox_min(pnanovdb_buf_t buf, pnanovdb_root_handle_t p) {
return pnanovdb_read_coord(buf, pnanovdb_address_offset(p.address, PNANOVDB_ROOT_OFF_BBOX_MIN));
}
PNANOVDB_FORCE_INLINE pnanovdb_coord_t pnanovdb_root_get_bbox_max(pnanovdb_buf_t buf, pnanovdb_root_handle_t p) {
return pnanovdb_read_coord(buf, pnanovdb_address_offset(p.address, PNANOVDB_ROOT_OFF_BBOX_MAX));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_root_get_tile_count(pnanovdb_buf_t buf, pnanovdb_root_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_ROOT_OFF_TABLE_SIZE));
}
struct pnanovdb_root_tile_t
{
pnanovdb_uint64_t key;
pnanovdb_int64_t child; // signed byte offset from root to the child node, 0 means it is a constant tile, so use value
pnanovdb_uint32_t state;
pnanovdb_uint32_t pad1; // value can start here
// value
};
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_root_tile_t)
struct pnanovdb_root_tile_handle_t { pnanovdb_address_t address; };
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_root_tile_handle_t)
#define PNANOVDB_ROOT_TILE_BASE_SIZE 20
#define PNANOVDB_ROOT_TILE_OFF_KEY 0
#define PNANOVDB_ROOT_TILE_OFF_CHILD 8
#define PNANOVDB_ROOT_TILE_OFF_STATE 16
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_root_tile_get_key(pnanovdb_buf_t buf, pnanovdb_root_tile_handle_t p) {
return pnanovdb_read_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_ROOT_TILE_OFF_KEY));
}
PNANOVDB_FORCE_INLINE pnanovdb_int64_t pnanovdb_root_tile_get_child(pnanovdb_buf_t buf, pnanovdb_root_tile_handle_t p) {
return pnanovdb_read_int64(buf, pnanovdb_address_offset(p.address, PNANOVDB_ROOT_TILE_OFF_CHILD));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_root_tile_get_state(pnanovdb_buf_t buf, pnanovdb_root_tile_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_ROOT_TILE_OFF_STATE));
}
struct pnanovdb_upper_t
{
pnanovdb_coord_t bbox_min;
pnanovdb_coord_t bbox_max;
pnanovdb_uint64_t flags;
pnanovdb_uint32_t value_mask[1024];
pnanovdb_uint32_t child_mask[1024];
// min, max
// alignas(32) pnanovdb_uint32_t table[];
};
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_upper_t)
struct pnanovdb_upper_handle_t { pnanovdb_address_t address; };
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_upper_handle_t)
#define PNANOVDB_UPPER_TABLE_COUNT 32768
#define PNANOVDB_UPPER_BASE_SIZE 8224
#define PNANOVDB_UPPER_OFF_BBOX_MIN 0
#define PNANOVDB_UPPER_OFF_BBOX_MAX 12
#define PNANOVDB_UPPER_OFF_FLAGS 24
#define PNANOVDB_UPPER_OFF_VALUE_MASK 32
#define PNANOVDB_UPPER_OFF_CHILD_MASK 4128
PNANOVDB_FORCE_INLINE pnanovdb_coord_t pnanovdb_upper_get_bbox_min(pnanovdb_buf_t buf, pnanovdb_upper_handle_t p) {
return pnanovdb_read_coord(buf, pnanovdb_address_offset(p.address, PNANOVDB_UPPER_OFF_BBOX_MIN));
}
PNANOVDB_FORCE_INLINE pnanovdb_coord_t pnanovdb_upper_get_bbox_max(pnanovdb_buf_t buf, pnanovdb_upper_handle_t p) {
return pnanovdb_read_coord(buf, pnanovdb_address_offset(p.address, PNANOVDB_UPPER_OFF_BBOX_MAX));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_upper_get_flags(pnanovdb_buf_t buf, pnanovdb_upper_handle_t p) {
return pnanovdb_read_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_UPPER_OFF_FLAGS));
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_upper_get_value_mask(pnanovdb_buf_t buf, pnanovdb_upper_handle_t p, pnanovdb_uint32_t bit_index) {
pnanovdb_uint32_t value = pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_UPPER_OFF_VALUE_MASK + 4u * (bit_index >> 5u)));
return ((value >> (bit_index & 31u)) & 1) != 0u;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_upper_get_child_mask(pnanovdb_buf_t buf, pnanovdb_upper_handle_t p, pnanovdb_uint32_t bit_index) {
pnanovdb_uint32_t value = pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_UPPER_OFF_CHILD_MASK + 4u * (bit_index >> 5u)));
return ((value >> (bit_index & 31u)) & 1) != 0u;
}
struct pnanovdb_lower_t
{
pnanovdb_coord_t bbox_min;
pnanovdb_coord_t bbox_max;
pnanovdb_uint64_t flags;
pnanovdb_uint32_t value_mask[128];
pnanovdb_uint32_t child_mask[128];
// min, max
// alignas(32) pnanovdb_uint32_t table[];
};
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_lower_t)
struct pnanovdb_lower_handle_t { pnanovdb_address_t address; };
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_lower_handle_t)
#define PNANOVDB_LOWER_TABLE_COUNT 4096
#define PNANOVDB_LOWER_BASE_SIZE 1056
#define PNANOVDB_LOWER_OFF_BBOX_MIN 0
#define PNANOVDB_LOWER_OFF_BBOX_MAX 12
#define PNANOVDB_LOWER_OFF_FLAGS 24
#define PNANOVDB_LOWER_OFF_VALUE_MASK 32
#define PNANOVDB_LOWER_OFF_CHILD_MASK 544
PNANOVDB_FORCE_INLINE pnanovdb_coord_t pnanovdb_lower_get_bbox_min(pnanovdb_buf_t buf, pnanovdb_lower_handle_t p) {
return pnanovdb_read_coord(buf, pnanovdb_address_offset(p.address, PNANOVDB_LOWER_OFF_BBOX_MIN));
}
PNANOVDB_FORCE_INLINE pnanovdb_coord_t pnanovdb_lower_get_bbox_max(pnanovdb_buf_t buf, pnanovdb_lower_handle_t p) {
return pnanovdb_read_coord(buf, pnanovdb_address_offset(p.address, PNANOVDB_LOWER_OFF_BBOX_MAX));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_lower_get_flags(pnanovdb_buf_t buf, pnanovdb_lower_handle_t p) {
return pnanovdb_read_uint64(buf, pnanovdb_address_offset(p.address, PNANOVDB_LOWER_OFF_FLAGS));
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_lower_get_value_mask(pnanovdb_buf_t buf, pnanovdb_lower_handle_t p, pnanovdb_uint32_t bit_index) {
pnanovdb_uint32_t value = pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_LOWER_OFF_VALUE_MASK + 4u * (bit_index >> 5u)));
return ((value >> (bit_index & 31u)) & 1) != 0u;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_lower_get_child_mask(pnanovdb_buf_t buf, pnanovdb_lower_handle_t p, pnanovdb_uint32_t bit_index) {
pnanovdb_uint32_t value = pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_LOWER_OFF_CHILD_MASK + 4u * (bit_index >> 5u)));
return ((value >> (bit_index & 31u)) & 1) != 0u;
}
struct pnanovdb_leaf_t
{
pnanovdb_coord_t bbox_min;
pnanovdb_uint32_t bbox_dif_and_flags;
pnanovdb_uint32_t value_mask[16];
// min, max
// alignas(32) pnanovdb_uint32_t values[];
};
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_leaf_t)
struct pnanovdb_leaf_handle_t { pnanovdb_address_t address; };
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_leaf_handle_t)
#define PNANOVDB_LEAF_TABLE_COUNT 512
#define PNANOVDB_LEAF_BASE_SIZE 80
#define PNANOVDB_LEAF_OFF_BBOX_MIN 0
#define PNANOVDB_LEAF_OFF_BBOX_DIF_AND_FLAGS 12
#define PNANOVDB_LEAF_OFF_VALUE_MASK 16
#define PNANOVDB_LEAF_TABLE_NEG_OFF_BBOX_DIF_AND_FLAGS 84
#define PNANOVDB_LEAF_TABLE_NEG_OFF_MINIMUM 16
#define PNANOVDB_LEAF_TABLE_NEG_OFF_QUANTUM 12
PNANOVDB_FORCE_INLINE pnanovdb_coord_t pnanovdb_leaf_get_bbox_min(pnanovdb_buf_t buf, pnanovdb_leaf_handle_t p) {
return pnanovdb_read_coord(buf, pnanovdb_address_offset(p.address, PNANOVDB_LEAF_OFF_BBOX_MIN));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_leaf_get_bbox_dif_and_flags(pnanovdb_buf_t buf, pnanovdb_leaf_handle_t p) {
return pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_LEAF_OFF_BBOX_DIF_AND_FLAGS));
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_leaf_get_value_mask(pnanovdb_buf_t buf, pnanovdb_leaf_handle_t p, pnanovdb_uint32_t bit_index) {
pnanovdb_uint32_t value = pnanovdb_read_uint32(buf, pnanovdb_address_offset(p.address, PNANOVDB_LEAF_OFF_VALUE_MASK + 4u * (bit_index >> 5u)));
return ((value >> (bit_index & 31u)) & 1) != 0u;
}
struct pnanovdb_grid_type_constants_t
{
pnanovdb_uint32_t root_off_background;
pnanovdb_uint32_t root_off_min;
pnanovdb_uint32_t root_off_max;
pnanovdb_uint32_t root_off_ave;
pnanovdb_uint32_t root_off_stddev;
pnanovdb_uint32_t root_size;
pnanovdb_uint32_t value_stride_bits;
pnanovdb_uint32_t table_stride;
pnanovdb_uint32_t root_tile_off_value;
pnanovdb_uint32_t root_tile_size;
pnanovdb_uint32_t upper_off_min;
pnanovdb_uint32_t upper_off_max;
pnanovdb_uint32_t upper_off_ave;
pnanovdb_uint32_t upper_off_stddev;
pnanovdb_uint32_t upper_off_table;
pnanovdb_uint32_t upper_size;
pnanovdb_uint32_t lower_off_min;
pnanovdb_uint32_t lower_off_max;
pnanovdb_uint32_t lower_off_ave;
pnanovdb_uint32_t lower_off_stddev;
pnanovdb_uint32_t lower_off_table;
pnanovdb_uint32_t lower_size;
pnanovdb_uint32_t leaf_off_min;
pnanovdb_uint32_t leaf_off_max;
pnanovdb_uint32_t leaf_off_ave;
pnanovdb_uint32_t leaf_off_stddev;
pnanovdb_uint32_t leaf_off_table;
pnanovdb_uint32_t leaf_size;
};
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_grid_type_constants_t)
PNANOVDB_STATIC_CONST pnanovdb_grid_type_constants_t pnanovdb_grid_type_constants[PNANOVDB_GRID_TYPE_END] =
{
{28, 28, 28, 28, 28, 32, 0, 8, 20, 32, 8224, 8224, 8224, 8224, 8224, 270368, 1056, 1056, 1056, 1056, 1056, 33824, 80, 80, 80, 80, 96, 96},
{28, 32, 36, 40, 44, 64, 32, 8, 20, 32, 8224, 8228, 8232, 8236, 8256, 270400, 1056, 1060, 1064, 1068, 1088, 33856, 80, 84, 88, 92, 96, 2144},
{32, 40, 48, 56, 64, 96, 64, 8, 24, 32, 8224, 8232, 8240, 8248, 8256, 270400, 1056, 1064, 1072, 1080, 1088, 33856, 80, 88, 96, 104, 128, 4224},
{28, 30, 32, 36, 40, 64, 16, 8, 20, 32, 8224, 8226, 8228, 8232, 8256, 270400, 1056, 1058, 1060, 1064, 1088, 33856, 80, 82, 84, 88, 96, 1120},
{28, 32, 36, 40, 44, 64, 32, 8, 20, 32, 8224, 8228, 8232, 8236, 8256, 270400, 1056, 1060, 1064, 1068, 1088, 33856, 80, 84, 88, 92, 96, 2144},
{32, 40, 48, 56, 64, 96, 64, 8, 24, 32, 8224, 8232, 8240, 8248, 8256, 270400, 1056, 1064, 1072, 1080, 1088, 33856, 80, 88, 96, 104, 128, 4224},
{28, 40, 52, 64, 68, 96, 96, 16, 20, 32, 8224, 8236, 8248, 8252, 8256, 532544, 1056, 1068, 1080, 1084, 1088, 66624, 80, 92, 104, 108, 128, 6272},
{32, 56, 80, 104, 112, 128, 192, 24, 24, 64, 8224, 8248, 8272, 8280, 8288, 794720, 1056, 1080, 1104, 1112, 1120, 99424, 80, 104, 128, 136, 160, 12448},
{28, 29, 30, 31, 32, 64, 0, 8, 20, 32, 8224, 8225, 8226, 8227, 8256, 270400, 1056, 1057, 1058, 1059, 1088, 33856, 80, 80, 80, 80, 96, 96},
{28, 30, 32, 36, 40, 64, 16, 8, 20, 32, 8224, 8226, 8228, 8232, 8256, 270400, 1056, 1058, 1060, 1064, 1088, 33856, 80, 82, 84, 88, 96, 1120},
{28, 32, 36, 40, 44, 64, 32, 8, 20, 32, 8224, 8228, 8232, 8236, 8256, 270400, 1056, 1060, 1064, 1068, 1088, 33856, 80, 84, 88, 92, 96, 2144},
{28, 29, 30, 31, 32, 64, 1, 8, 20, 32, 8224, 8225, 8226, 8227, 8256, 270400, 1056, 1057, 1058, 1059, 1088, 33856, 80, 80, 80, 80, 96, 160},
{28, 32, 36, 40, 44, 64, 32, 8, 20, 32, 8224, 8228, 8232, 8236, 8256, 270400, 1056, 1060, 1064, 1068, 1088, 33856, 80, 84, 88, 92, 96, 2144},
{28, 32, 36, 40, 44, 64, 0, 8, 20, 32, 8224, 8228, 8232, 8236, 8256, 270400, 1056, 1060, 1064, 1068, 1088, 33856, 88, 90, 92, 94, 96, 352},
{28, 32, 36, 40, 44, 64, 0, 8, 20, 32, 8224, 8228, 8232, 8236, 8256, 270400, 1056, 1060, 1064, 1068, 1088, 33856, 88, 90, 92, 94, 96, 608},
{28, 32, 36, 40, 44, 64, 0, 8, 20, 32, 8224, 8228, 8232, 8236, 8256, 270400, 1056, 1060, 1064, 1068, 1088, 33856, 88, 90, 92, 94, 96, 1120},
{28, 32, 36, 40, 44, 64, 0, 8, 20, 32, 8224, 8228, 8232, 8236, 8256, 270400, 1056, 1060, 1064, 1068, 1088, 33856, 88, 90, 92, 94, 96, 96},
{28, 44, 60, 76, 80, 96, 128, 16, 20, 64, 8224, 8240, 8256, 8260, 8288, 532576, 1056, 1072, 1088, 1092, 1120, 66656, 80, 96, 112, 116, 128, 8320},
{32, 64, 96, 128, 136, 160, 256, 32, 24, 64, 8224, 8256, 8288, 8296, 8320, 1056896, 1056, 1088, 1120, 1128, 1152, 132224, 80, 112, 144, 152, 160, 16544},
};
// ------------------------------------------------ Basic Lookup -----------------------------------------------------------
PNANOVDB_FORCE_INLINE pnanovdb_gridblindmetadata_handle_t pnanovdb_grid_get_gridblindmetadata(pnanovdb_buf_t buf, pnanovdb_grid_handle_t grid, pnanovdb_uint32_t index)
{
pnanovdb_gridblindmetadata_handle_t meta = { grid.address };
pnanovdb_uint64_t byte_offset = pnanovdb_grid_get_blind_metadata_offset(buf, grid);
meta.address = pnanovdb_address_offset64(meta.address, byte_offset);
meta.address = pnanovdb_address_offset_product(meta.address, PNANOVDB_GRIDBLINDMETADATA_SIZE, index);
return meta;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanodvb_grid_get_gridblindmetadata_value_address(pnanovdb_buf_t buf, pnanovdb_grid_handle_t grid, pnanovdb_uint32_t index)
{
pnanovdb_gridblindmetadata_handle_t meta = pnanovdb_grid_get_gridblindmetadata(buf, grid, index);
pnanovdb_int64_t byte_offset = pnanovdb_gridblindmetadata_get_byte_offset(buf, meta);
pnanovdb_address_t address = grid.address;
address = pnanovdb_address_offset64(address, pnanovdb_int64_as_uint64(byte_offset));
return address;
}
PNANOVDB_FORCE_INLINE pnanovdb_tree_handle_t pnanovdb_grid_get_tree(pnanovdb_buf_t buf, pnanovdb_grid_handle_t grid)
{
pnanovdb_tree_handle_t tree = { grid.address };
tree.address = pnanovdb_address_offset(tree.address, PNANOVDB_GRID_SIZE);
return tree;
}
PNANOVDB_FORCE_INLINE pnanovdb_root_handle_t pnanovdb_tree_get_root(pnanovdb_buf_t buf, pnanovdb_tree_handle_t tree)
{
pnanovdb_root_handle_t root = { tree.address };
pnanovdb_uint64_t byte_offset = pnanovdb_tree_get_node_offset_root(buf, tree);
root.address = pnanovdb_address_offset64(root.address, byte_offset);
return root;
}
PNANOVDB_FORCE_INLINE pnanovdb_root_tile_handle_t pnanovdb_root_get_tile(pnanovdb_grid_type_t grid_type, pnanovdb_root_handle_t root, pnanovdb_uint32_t n)
{
pnanovdb_root_tile_handle_t tile = { root.address };
tile.address = pnanovdb_address_offset(tile.address, PNANOVDB_GRID_TYPE_GET(grid_type, root_size));
tile.address = pnanovdb_address_offset_product(tile.address, PNANOVDB_GRID_TYPE_GET(grid_type, root_tile_size), n);
return tile;
}
PNANOVDB_FORCE_INLINE pnanovdb_root_tile_handle_t pnanovdb_root_get_tile_zero(pnanovdb_grid_type_t grid_type, pnanovdb_root_handle_t root)
{
pnanovdb_root_tile_handle_t tile = { root.address };
tile.address = pnanovdb_address_offset(tile.address, PNANOVDB_GRID_TYPE_GET(grid_type, root_size));
return tile;
}
PNANOVDB_FORCE_INLINE pnanovdb_upper_handle_t pnanovdb_root_get_child(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_root_handle_t root, pnanovdb_root_tile_handle_t tile)
{
pnanovdb_upper_handle_t upper = { root.address };
upper.address = pnanovdb_address_offset64(upper.address, pnanovdb_int64_as_uint64(pnanovdb_root_tile_get_child(buf, tile)));
return upper;
}
PNANOVDB_FORCE_INLINE pnanovdb_uint64_t pnanovdb_coord_to_key(PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
#if defined(PNANOVDB_NATIVE_64)
pnanovdb_uint64_t iu = pnanovdb_int32_as_uint32(PNANOVDB_DEREF(ijk).x) >> 12u;
pnanovdb_uint64_t ju = pnanovdb_int32_as_uint32(PNANOVDB_DEREF(ijk).y) >> 12u;
pnanovdb_uint64_t ku = pnanovdb_int32_as_uint32(PNANOVDB_DEREF(ijk).z) >> 12u;
return (ku) | (ju << 21u) | (iu << 42u);
#else
pnanovdb_uint32_t iu = pnanovdb_int32_as_uint32(PNANOVDB_DEREF(ijk).x) >> 12u;
pnanovdb_uint32_t ju = pnanovdb_int32_as_uint32(PNANOVDB_DEREF(ijk).y) >> 12u;
pnanovdb_uint32_t ku = pnanovdb_int32_as_uint32(PNANOVDB_DEREF(ijk).z) >> 12u;
pnanovdb_uint32_t key_x = ku | (ju << 21);
pnanovdb_uint32_t key_y = (iu << 10) | (ju >> 11);
return pnanovdb_uint32_as_uint64(key_x, key_y);
#endif
}
PNANOVDB_FORCE_INLINE pnanovdb_root_tile_handle_t pnanovdb_root_find_tile(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_root_handle_t root, PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
pnanovdb_uint32_t tile_count = pnanovdb_uint32_as_int32(pnanovdb_root_get_tile_count(buf, root));
pnanovdb_root_tile_handle_t tile = pnanovdb_root_get_tile_zero(grid_type, root);
pnanovdb_uint64_t key = pnanovdb_coord_to_key(ijk);
for (pnanovdb_uint32_t i = 0u; i < tile_count; i++)
{
if (pnanovdb_uint64_is_equal(key, pnanovdb_root_tile_get_key(buf, tile)))
{
return tile;
}
tile.address = pnanovdb_address_offset(tile.address, PNANOVDB_GRID_TYPE_GET(grid_type, root_tile_size));
}
pnanovdb_root_tile_handle_t null_handle = { pnanovdb_address_null() };
return null_handle;
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_leaf_coord_to_offset(PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
return (((PNANOVDB_DEREF(ijk).x & 7) >> 0) << (2 * 3)) +
(((PNANOVDB_DEREF(ijk).y & 7) >> 0) << (3)) +
((PNANOVDB_DEREF(ijk).z & 7) >> 0);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_leaf_get_min_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_leaf_handle_t node)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, leaf_off_min);
return pnanovdb_address_offset(node.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_leaf_get_max_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_leaf_handle_t node)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, leaf_off_max);
return pnanovdb_address_offset(node.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_leaf_get_ave_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_leaf_handle_t node)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, leaf_off_ave);
return pnanovdb_address_offset(node.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_leaf_get_stddev_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_leaf_handle_t node)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, leaf_off_stddev);
return pnanovdb_address_offset(node.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_leaf_get_table_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_leaf_handle_t node, pnanovdb_uint32_t n)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, leaf_off_table) + ((PNANOVDB_GRID_TYPE_GET(grid_type, value_stride_bits) * n) >> 3u);
return pnanovdb_address_offset(node.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_leaf_get_value_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_leaf_handle_t leaf, PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
pnanovdb_uint32_t n = pnanovdb_leaf_coord_to_offset(ijk);
return pnanovdb_leaf_get_table_address(grid_type, buf, leaf, n);
}
PNANOVDB_FORCE_INLINE float pnanovdb_leaf_fp_read_float(pnanovdb_buf_t buf, pnanovdb_address_t address, PNANOVDB_IN(pnanovdb_coord_t) ijk, pnanovdb_uint32_t value_log_bits)
{
// value_log_bits // 2 3 4
pnanovdb_uint32_t value_bits = 1u << value_log_bits; // 4 8 16
pnanovdb_uint32_t value_mask = (1u << value_bits) - 1u; // 0xF 0xFF 0xFFFF
pnanovdb_uint32_t values_per_word_bits = 5u - value_log_bits; // 3 2 1
pnanovdb_uint32_t values_per_word_mask = (1u << values_per_word_bits) - 1u; // 7 3 1
pnanovdb_uint32_t n = pnanovdb_leaf_coord_to_offset(ijk);
float minimum = pnanovdb_read_float(buf, pnanovdb_address_offset_neg(address, PNANOVDB_LEAF_TABLE_NEG_OFF_MINIMUM));
float quantum = pnanovdb_read_float(buf, pnanovdb_address_offset_neg(address, PNANOVDB_LEAF_TABLE_NEG_OFF_QUANTUM));
pnanovdb_uint32_t raw = pnanovdb_read_uint32(buf, pnanovdb_address_offset(address, ((n >> values_per_word_bits) << 2u)));
pnanovdb_uint32_t value_compressed = (raw >> ((n & values_per_word_mask) << value_log_bits)) & value_mask;
return pnanovdb_uint32_to_float(value_compressed) * quantum + minimum;
}
PNANOVDB_FORCE_INLINE float pnanovdb_leaf_fp4_read_float(pnanovdb_buf_t buf, pnanovdb_address_t address, PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
return pnanovdb_leaf_fp_read_float(buf, address, ijk, 2u);
}
PNANOVDB_FORCE_INLINE float pnanovdb_leaf_fp8_read_float(pnanovdb_buf_t buf, pnanovdb_address_t address, PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
return pnanovdb_leaf_fp_read_float(buf, address, ijk, 3u);
}
PNANOVDB_FORCE_INLINE float pnanovdb_leaf_fp16_read_float(pnanovdb_buf_t buf, pnanovdb_address_t address, PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
return pnanovdb_leaf_fp_read_float(buf, address, ijk, 4u);
}
PNANOVDB_FORCE_INLINE float pnanovdb_leaf_fpn_read_float(pnanovdb_buf_t buf, pnanovdb_address_t address, PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
pnanovdb_uint32_t bbox_dif_and_flags = pnanovdb_read_uint32(buf, pnanovdb_address_offset_neg(address, PNANOVDB_LEAF_TABLE_NEG_OFF_BBOX_DIF_AND_FLAGS));
pnanovdb_uint32_t flags = bbox_dif_and_flags >> 24u;
pnanovdb_uint32_t value_log_bits = flags >> 5; // b = 0, 1, 2, 3, 4 corresponding to 1, 2, 4, 8, 16 bits
return pnanovdb_leaf_fp_read_float(buf, address, ijk, value_log_bits);
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_lower_coord_to_offset(PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
return (((PNANOVDB_DEREF(ijk).x & 127) >> 3) << (2 * 4)) +
(((PNANOVDB_DEREF(ijk).y & 127) >> 3) << (4)) +
((PNANOVDB_DEREF(ijk).z & 127) >> 3);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_lower_get_min_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_lower_handle_t node)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, lower_off_min);
return pnanovdb_address_offset(node.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_lower_get_max_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_lower_handle_t node)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, lower_off_max);
return pnanovdb_address_offset(node.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_lower_get_ave_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_lower_handle_t node)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, lower_off_ave);
return pnanovdb_address_offset(node.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_lower_get_stddev_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_lower_handle_t node)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, lower_off_stddev);
return pnanovdb_address_offset(node.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_lower_get_table_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_lower_handle_t node, pnanovdb_uint32_t n)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, lower_off_table) + PNANOVDB_GRID_TYPE_GET(grid_type, table_stride) * n;
return pnanovdb_address_offset(node.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_int64_t pnanovdb_lower_get_table_child(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_lower_handle_t node, pnanovdb_uint32_t n)
{
pnanovdb_address_t table_address = pnanovdb_lower_get_table_address(grid_type, buf, node, n);
return pnanovdb_read_int64(buf, table_address);
}
PNANOVDB_FORCE_INLINE pnanovdb_leaf_handle_t pnanovdb_lower_get_child(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_lower_handle_t lower, pnanovdb_uint32_t n)
{
pnanovdb_leaf_handle_t leaf = { lower.address };
leaf.address = pnanovdb_address_offset64(leaf.address, pnanovdb_int64_as_uint64(pnanovdb_lower_get_table_child(grid_type, buf, lower, n)));
return leaf;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_lower_get_value_address_and_level(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_lower_handle_t lower, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_uint32_t) level)
{
pnanovdb_uint32_t n = pnanovdb_lower_coord_to_offset(ijk);
pnanovdb_address_t value_address;
if (pnanovdb_lower_get_child_mask(buf, lower, n))
{
pnanovdb_leaf_handle_t child = pnanovdb_lower_get_child(grid_type, buf, lower, n);
value_address = pnanovdb_leaf_get_value_address(grid_type, buf, child, ijk);
PNANOVDB_DEREF(level) = 0u;
}
else
{
value_address = pnanovdb_lower_get_table_address(grid_type, buf, lower, n);
PNANOVDB_DEREF(level) = 1u;
}
return value_address;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_lower_get_value_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_lower_handle_t lower, PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
pnanovdb_uint32_t level;
return pnanovdb_lower_get_value_address_and_level(grid_type, buf, lower, ijk, PNANOVDB_REF(level));
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_upper_coord_to_offset(PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
return (((PNANOVDB_DEREF(ijk).x & 4095) >> 7) << (2 * 5)) +
(((PNANOVDB_DEREF(ijk).y & 4095) >> 7) << (5)) +
((PNANOVDB_DEREF(ijk).z & 4095) >> 7);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_upper_get_min_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_upper_handle_t node)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, upper_off_min);
return pnanovdb_address_offset(node.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_upper_get_max_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_upper_handle_t node)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, upper_off_max);
return pnanovdb_address_offset(node.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_upper_get_ave_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_upper_handle_t node)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, upper_off_ave);
return pnanovdb_address_offset(node.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_upper_get_stddev_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_upper_handle_t node)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, upper_off_stddev);
return pnanovdb_address_offset(node.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_upper_get_table_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_upper_handle_t node, pnanovdb_uint32_t n)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, upper_off_table) + PNANOVDB_GRID_TYPE_GET(grid_type, table_stride) * n;
return pnanovdb_address_offset(node.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_int64_t pnanovdb_upper_get_table_child(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_upper_handle_t node, pnanovdb_uint32_t n)
{
pnanovdb_address_t bufAddress = pnanovdb_upper_get_table_address(grid_type, buf, node, n);
return pnanovdb_read_int64(buf, bufAddress);
}
PNANOVDB_FORCE_INLINE pnanovdb_lower_handle_t pnanovdb_upper_get_child(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_upper_handle_t upper, pnanovdb_uint32_t n)
{
pnanovdb_lower_handle_t lower = { upper.address };
lower.address = pnanovdb_address_offset64(lower.address, pnanovdb_int64_as_uint64(pnanovdb_upper_get_table_child(grid_type, buf, upper, n)));
return lower;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_upper_get_value_address_and_level(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_upper_handle_t upper, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_uint32_t) level)
{
pnanovdb_uint32_t n = pnanovdb_upper_coord_to_offset(ijk);
pnanovdb_address_t value_address;
if (pnanovdb_upper_get_child_mask(buf, upper, n))
{
pnanovdb_lower_handle_t child = pnanovdb_upper_get_child(grid_type, buf, upper, n);
value_address = pnanovdb_lower_get_value_address_and_level(grid_type, buf, child, ijk, level);
}
else
{
value_address = pnanovdb_upper_get_table_address(grid_type, buf, upper, n);
PNANOVDB_DEREF(level) = 2u;
}
return value_address;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_upper_get_value_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_upper_handle_t upper, PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
pnanovdb_uint32_t level;
return pnanovdb_upper_get_value_address_and_level(grid_type, buf, upper, ijk, PNANOVDB_REF(level));
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_root_get_min_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_root_handle_t root)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, root_off_min);
return pnanovdb_address_offset(root.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_root_get_max_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_root_handle_t root)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, root_off_max);
return pnanovdb_address_offset(root.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_root_get_ave_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_root_handle_t root)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, root_off_ave);
return pnanovdb_address_offset(root.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_root_get_stddev_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_root_handle_t root)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, root_off_stddev);
return pnanovdb_address_offset(root.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_root_tile_get_value_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_root_tile_handle_t root_tile)
{
pnanovdb_uint32_t byte_offset = PNANOVDB_GRID_TYPE_GET(grid_type, root_tile_off_value);
return pnanovdb_address_offset(root_tile.address, byte_offset);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_root_get_value_address_and_level(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_root_handle_t root, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_uint32_t) level)
{
pnanovdb_root_tile_handle_t tile = pnanovdb_root_find_tile(grid_type, buf, root, ijk);
pnanovdb_address_t ret;
if (pnanovdb_address_is_null(tile.address))
{
ret = pnanovdb_address_offset(root.address, PNANOVDB_GRID_TYPE_GET(grid_type, root_off_background));
PNANOVDB_DEREF(level) = 4u;
}
else if (pnanovdb_int64_is_zero(pnanovdb_root_tile_get_child(buf, tile)))
{
ret = pnanovdb_address_offset(tile.address, PNANOVDB_GRID_TYPE_GET(grid_type, root_tile_off_value));
PNANOVDB_DEREF(level) = 3u;
}
else
{
pnanovdb_upper_handle_t child = pnanovdb_root_get_child(grid_type, buf, root, tile);
ret = pnanovdb_upper_get_value_address_and_level(grid_type, buf, child, ijk, level);
}
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_root_get_value_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_root_handle_t root, PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
pnanovdb_uint32_t level;
return pnanovdb_root_get_value_address_and_level(grid_type, buf, root, ijk, PNANOVDB_REF(level));
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_root_get_value_address_bit(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_root_handle_t root, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_uint32_t) bit_index)
{
pnanovdb_uint32_t level;
pnanovdb_address_t address = pnanovdb_root_get_value_address_and_level(grid_type, buf, root, ijk, PNANOVDB_REF(level));
PNANOVDB_DEREF(bit_index) = level == 0u ? pnanovdb_int32_as_uint32(PNANOVDB_DEREF(ijk).x & 7) : 0u;
return address;
}
PNANOVDB_FORCE_INLINE float pnanovdb_root_fp4_read_float(pnanovdb_buf_t buf, pnanovdb_address_t address, PNANOVDB_IN(pnanovdb_coord_t) ijk, pnanovdb_uint32_t level)
{
float ret;
if (level == 0)
{
ret = pnanovdb_leaf_fp4_read_float(buf, address, ijk);
}
else
{
ret = pnanovdb_read_float(buf, address);
}
return ret;
}
PNANOVDB_FORCE_INLINE float pnanovdb_root_fp8_read_float(pnanovdb_buf_t buf, pnanovdb_address_t address, PNANOVDB_IN(pnanovdb_coord_t) ijk, pnanovdb_uint32_t level)
{
float ret;
if (level == 0)
{
ret = pnanovdb_leaf_fp8_read_float(buf, address, ijk);
}
else
{
ret = pnanovdb_read_float(buf, address);
}
return ret;
}
PNANOVDB_FORCE_INLINE float pnanovdb_root_fp16_read_float(pnanovdb_buf_t buf, pnanovdb_address_t address, PNANOVDB_IN(pnanovdb_coord_t) ijk, pnanovdb_uint32_t level)
{
float ret;
if (level == 0)
{
ret = pnanovdb_leaf_fp16_read_float(buf, address, ijk);
}
else
{
ret = pnanovdb_read_float(buf, address);
}
return ret;
}
PNANOVDB_FORCE_INLINE float pnanovdb_root_fpn_read_float(pnanovdb_buf_t buf, pnanovdb_address_t address, PNANOVDB_IN(pnanovdb_coord_t) ijk, pnanovdb_uint32_t level)
{
float ret;
if (level == 0)
{
ret = pnanovdb_leaf_fpn_read_float(buf, address, ijk);
}
else
{
ret = pnanovdb_read_float(buf, address);
}
return ret;
}
// ------------------------------------------------ ReadAccessor -----------------------------------------------------------
struct pnanovdb_readaccessor_t
{
pnanovdb_coord_t key;
pnanovdb_leaf_handle_t leaf;
pnanovdb_lower_handle_t lower;
pnanovdb_upper_handle_t upper;
pnanovdb_root_handle_t root;
};
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_readaccessor_t)
PNANOVDB_FORCE_INLINE void pnanovdb_readaccessor_init(PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc, pnanovdb_root_handle_t root)
{
PNANOVDB_DEREF(acc).key.x = 0x7FFFFFFF;
PNANOVDB_DEREF(acc).key.y = 0x7FFFFFFF;
PNANOVDB_DEREF(acc).key.z = 0x7FFFFFFF;
PNANOVDB_DEREF(acc).leaf.address = pnanovdb_address_null();
PNANOVDB_DEREF(acc).lower.address = pnanovdb_address_null();
PNANOVDB_DEREF(acc).upper.address = pnanovdb_address_null();
PNANOVDB_DEREF(acc).root = root;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_readaccessor_iscached0(PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc, int dirty)
{
if (pnanovdb_address_is_null(PNANOVDB_DEREF(acc).leaf.address)) { return PNANOVDB_FALSE; }
if ((dirty & ~((1u << 3) - 1u)) != 0)
{
PNANOVDB_DEREF(acc).leaf.address = pnanovdb_address_null();
return PNANOVDB_FALSE;
}
return PNANOVDB_TRUE;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_readaccessor_iscached1(PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc, int dirty)
{
if (pnanovdb_address_is_null(PNANOVDB_DEREF(acc).lower.address)) { return PNANOVDB_FALSE; }
if ((dirty & ~((1u << 7) - 1u)) != 0)
{
PNANOVDB_DEREF(acc).lower.address = pnanovdb_address_null();
return PNANOVDB_FALSE;
}
return PNANOVDB_TRUE;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_readaccessor_iscached2(PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc, int dirty)
{
if (pnanovdb_address_is_null(PNANOVDB_DEREF(acc).upper.address)) { return PNANOVDB_FALSE; }
if ((dirty & ~((1u << 12) - 1u)) != 0)
{
PNANOVDB_DEREF(acc).upper.address = pnanovdb_address_null();
return PNANOVDB_FALSE;
}
return PNANOVDB_TRUE;
}
PNANOVDB_FORCE_INLINE int pnanovdb_readaccessor_computedirty(PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc, PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
return (PNANOVDB_DEREF(ijk).x ^ PNANOVDB_DEREF(acc).key.x) | (PNANOVDB_DEREF(ijk).y ^ PNANOVDB_DEREF(acc).key.y) | (PNANOVDB_DEREF(ijk).z ^ PNANOVDB_DEREF(acc).key.z);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_leaf_get_value_address_and_cache(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_leaf_handle_t leaf, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc)
{
pnanovdb_uint32_t n = pnanovdb_leaf_coord_to_offset(ijk);
return pnanovdb_leaf_get_table_address(grid_type, buf, leaf, n);
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_lower_get_value_address_and_level_and_cache(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_lower_handle_t lower, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc, PNANOVDB_INOUT(pnanovdb_uint32_t) level)
{
pnanovdb_uint32_t n = pnanovdb_lower_coord_to_offset(ijk);
pnanovdb_address_t value_address;
if (pnanovdb_lower_get_child_mask(buf, lower, n))
{
pnanovdb_leaf_handle_t child = pnanovdb_lower_get_child(grid_type, buf, lower, n);
PNANOVDB_DEREF(acc).leaf = child;
PNANOVDB_DEREF(acc).key = PNANOVDB_DEREF(ijk);
value_address = pnanovdb_leaf_get_value_address_and_cache(grid_type, buf, child, ijk, acc);
PNANOVDB_DEREF(level) = 0u;
}
else
{
value_address = pnanovdb_lower_get_table_address(grid_type, buf, lower, n);
PNANOVDB_DEREF(level) = 1u;
}
return value_address;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_lower_get_value_address_and_cache(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_lower_handle_t lower, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc)
{
pnanovdb_uint32_t level;
return pnanovdb_lower_get_value_address_and_level_and_cache(grid_type, buf, lower, ijk, acc, PNANOVDB_REF(level));
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_upper_get_value_address_and_level_and_cache(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_upper_handle_t upper, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc, PNANOVDB_INOUT(pnanovdb_uint32_t) level)
{
pnanovdb_uint32_t n = pnanovdb_upper_coord_to_offset(ijk);
pnanovdb_address_t value_address;
if (pnanovdb_upper_get_child_mask(buf, upper, n))
{
pnanovdb_lower_handle_t child = pnanovdb_upper_get_child(grid_type, buf, upper, n);
PNANOVDB_DEREF(acc).lower = child;
PNANOVDB_DEREF(acc).key = PNANOVDB_DEREF(ijk);
value_address = pnanovdb_lower_get_value_address_and_level_and_cache(grid_type, buf, child, ijk, acc, level);
}
else
{
value_address = pnanovdb_upper_get_table_address(grid_type, buf, upper, n);
PNANOVDB_DEREF(level) = 2u;
}
return value_address;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_upper_get_value_address_and_cache(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_upper_handle_t upper, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc)
{
pnanovdb_uint32_t level;
return pnanovdb_upper_get_value_address_and_level_and_cache(grid_type, buf, upper, ijk, acc, PNANOVDB_REF(level));
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_root_get_value_address_and_level_and_cache(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_root_handle_t root, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc, PNANOVDB_INOUT(pnanovdb_uint32_t) level)
{
pnanovdb_root_tile_handle_t tile = pnanovdb_root_find_tile(grid_type, buf, root, ijk);
pnanovdb_address_t ret;
if (pnanovdb_address_is_null(tile.address))
{
ret = pnanovdb_address_offset(root.address, PNANOVDB_GRID_TYPE_GET(grid_type, root_off_background));
PNANOVDB_DEREF(level) = 4u;
}
else if (pnanovdb_int64_is_zero(pnanovdb_root_tile_get_child(buf, tile)))
{
ret = pnanovdb_address_offset(tile.address, PNANOVDB_GRID_TYPE_GET(grid_type, root_tile_off_value));
PNANOVDB_DEREF(level) = 3u;
}
else
{
pnanovdb_upper_handle_t child = pnanovdb_root_get_child(grid_type, buf, root, tile);
PNANOVDB_DEREF(acc).upper = child;
PNANOVDB_DEREF(acc).key = PNANOVDB_DEREF(ijk);
ret = pnanovdb_upper_get_value_address_and_level_and_cache(grid_type, buf, child, ijk, acc, level);
}
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_root_get_value_address_and_cache(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_root_handle_t root, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc)
{
pnanovdb_uint32_t level;
return pnanovdb_root_get_value_address_and_level_and_cache(grid_type, buf, root, ijk, acc, PNANOVDB_REF(level));
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_readaccessor_get_value_address_and_level(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_uint32_t) level)
{
int dirty = pnanovdb_readaccessor_computedirty(acc, ijk);
pnanovdb_address_t value_address;
if (pnanovdb_readaccessor_iscached0(acc, dirty))
{
value_address = pnanovdb_leaf_get_value_address_and_cache(grid_type, buf, PNANOVDB_DEREF(acc).leaf, ijk, acc);
PNANOVDB_DEREF(level) = 0u;
}
else if (pnanovdb_readaccessor_iscached1(acc, dirty))
{
value_address = pnanovdb_lower_get_value_address_and_level_and_cache(grid_type, buf, PNANOVDB_DEREF(acc).lower, ijk, acc, level);
}
else if (pnanovdb_readaccessor_iscached2(acc, dirty))
{
value_address = pnanovdb_upper_get_value_address_and_level_and_cache(grid_type, buf, PNANOVDB_DEREF(acc).upper, ijk, acc, level);
}
else
{
value_address = pnanovdb_root_get_value_address_and_level_and_cache(grid_type, buf, PNANOVDB_DEREF(acc).root, ijk, acc, level);
}
return value_address;
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_readaccessor_get_value_address(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc, PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
pnanovdb_uint32_t level;
return pnanovdb_readaccessor_get_value_address_and_level(grid_type, buf, acc, ijk, PNANOVDB_REF(level));
}
PNANOVDB_FORCE_INLINE pnanovdb_address_t pnanovdb_readaccessor_get_value_address_bit(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_uint32_t) bit_index)
{
pnanovdb_uint32_t level;
pnanovdb_address_t address = pnanovdb_readaccessor_get_value_address_and_level(grid_type, buf, acc, ijk, PNANOVDB_REF(level));
PNANOVDB_DEREF(bit_index) = level == 0u ? pnanovdb_int32_as_uint32(PNANOVDB_DEREF(ijk).x & 7) : 0u;
return address;
}
// ------------------------------------------------ ReadAccessor GetDim -----------------------------------------------------------
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_leaf_get_dim_and_cache(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_leaf_handle_t leaf, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc)
{
return 1u;
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_lower_get_dim_and_cache(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_lower_handle_t lower, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc)
{
pnanovdb_uint32_t n = pnanovdb_lower_coord_to_offset(ijk);
pnanovdb_uint32_t ret;
if (pnanovdb_lower_get_child_mask(buf, lower, n))
{
pnanovdb_leaf_handle_t child = pnanovdb_lower_get_child(grid_type, buf, lower, n);
PNANOVDB_DEREF(acc).leaf = child;
PNANOVDB_DEREF(acc).key = PNANOVDB_DEREF(ijk);
ret = pnanovdb_leaf_get_dim_and_cache(grid_type, buf, child, ijk, acc);
}
else
{
ret = (1u << (3u)); // node 0 dim
}
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_upper_get_dim_and_cache(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_upper_handle_t upper, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc)
{
pnanovdb_uint32_t n = pnanovdb_upper_coord_to_offset(ijk);
pnanovdb_uint32_t ret;
if (pnanovdb_upper_get_child_mask(buf, upper, n))
{
pnanovdb_lower_handle_t child = pnanovdb_upper_get_child(grid_type, buf, upper, n);
PNANOVDB_DEREF(acc).lower = child;
PNANOVDB_DEREF(acc).key = PNANOVDB_DEREF(ijk);
ret = pnanovdb_lower_get_dim_and_cache(grid_type, buf, child, ijk, acc);
}
else
{
ret = (1u << (4u + 3u)); // node 1 dim
}
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_root_get_dim_and_cache(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_root_handle_t root, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc)
{
pnanovdb_root_tile_handle_t tile = pnanovdb_root_find_tile(grid_type, buf, root, ijk);
pnanovdb_uint32_t ret;
if (pnanovdb_address_is_null(tile.address))
{
ret = 1u << (5u + 4u + 3u); // background, node 2 dim
}
else if (pnanovdb_int64_is_zero(pnanovdb_root_tile_get_child(buf, tile)))
{
ret = 1u << (5u + 4u + 3u); // tile value, node 2 dim
}
else
{
pnanovdb_upper_handle_t child = pnanovdb_root_get_child(grid_type, buf, root, tile);
PNANOVDB_DEREF(acc).upper = child;
PNANOVDB_DEREF(acc).key = PNANOVDB_DEREF(ijk);
ret = pnanovdb_upper_get_dim_and_cache(grid_type, buf, child, ijk, acc);
}
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_uint32_t pnanovdb_readaccessor_get_dim(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc, PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
int dirty = pnanovdb_readaccessor_computedirty(acc, ijk);
pnanovdb_uint32_t dim;
if (pnanovdb_readaccessor_iscached0(acc, dirty))
{
dim = pnanovdb_leaf_get_dim_and_cache(grid_type, buf, PNANOVDB_DEREF(acc).leaf, ijk, acc);
}
else if (pnanovdb_readaccessor_iscached1(acc, dirty))
{
dim = pnanovdb_lower_get_dim_and_cache(grid_type, buf, PNANOVDB_DEREF(acc).lower, ijk, acc);
}
else if (pnanovdb_readaccessor_iscached2(acc, dirty))
{
dim = pnanovdb_upper_get_dim_and_cache(grid_type, buf, PNANOVDB_DEREF(acc).upper, ijk, acc);
}
else
{
dim = pnanovdb_root_get_dim_and_cache(grid_type, buf, PNANOVDB_DEREF(acc).root, ijk, acc);
}
return dim;
}
// ------------------------------------------------ ReadAccessor IsActive -----------------------------------------------------------
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_leaf_is_active_and_cache(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_leaf_handle_t leaf, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc)
{
pnanovdb_uint32_t n = pnanovdb_leaf_coord_to_offset(ijk);
return pnanovdb_leaf_get_value_mask(buf, leaf, n);
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_lower_is_active_and_cache(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_lower_handle_t lower, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc)
{
pnanovdb_uint32_t n = pnanovdb_lower_coord_to_offset(ijk);
pnanovdb_bool_t is_active;
if (pnanovdb_lower_get_child_mask(buf, lower, n))
{
pnanovdb_leaf_handle_t child = pnanovdb_lower_get_child(grid_type, buf, lower, n);
PNANOVDB_DEREF(acc).leaf = child;
PNANOVDB_DEREF(acc).key = PNANOVDB_DEREF(ijk);
is_active = pnanovdb_leaf_is_active_and_cache(grid_type, buf, child, ijk, acc);
}
else
{
is_active = pnanovdb_lower_get_value_mask(buf, lower, n);
}
return is_active;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_upper_is_active_and_cache(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_upper_handle_t upper, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc)
{
pnanovdb_uint32_t n = pnanovdb_upper_coord_to_offset(ijk);
pnanovdb_bool_t is_active;
if (pnanovdb_upper_get_child_mask(buf, upper, n))
{
pnanovdb_lower_handle_t child = pnanovdb_upper_get_child(grid_type, buf, upper, n);
PNANOVDB_DEREF(acc).lower = child;
PNANOVDB_DEREF(acc).key = PNANOVDB_DEREF(ijk);
is_active = pnanovdb_lower_is_active_and_cache(grid_type, buf, child, ijk, acc);
}
else
{
is_active = pnanovdb_upper_get_value_mask(buf, upper, n);
}
return is_active;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_root_is_active_and_cache(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, pnanovdb_root_handle_t root, PNANOVDB_IN(pnanovdb_coord_t) ijk, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc)
{
pnanovdb_root_tile_handle_t tile = pnanovdb_root_find_tile(grid_type, buf, root, ijk);
pnanovdb_bool_t is_active;
if (pnanovdb_address_is_null(tile.address))
{
is_active = PNANOVDB_FALSE; // background
}
else if (pnanovdb_int64_is_zero(pnanovdb_root_tile_get_child(buf, tile)))
{
pnanovdb_uint32_t state = pnanovdb_root_tile_get_state(buf, tile);
is_active = state != 0u; // tile value
}
else
{
pnanovdb_upper_handle_t child = pnanovdb_root_get_child(grid_type, buf, root, tile);
PNANOVDB_DEREF(acc).upper = child;
PNANOVDB_DEREF(acc).key = PNANOVDB_DEREF(ijk);
is_active = pnanovdb_upper_is_active_and_cache(grid_type, buf, child, ijk, acc);
}
return is_active;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_readaccessor_is_active(pnanovdb_grid_type_t grid_type, pnanovdb_buf_t buf, PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc, PNANOVDB_IN(pnanovdb_coord_t) ijk)
{
int dirty = pnanovdb_readaccessor_computedirty(acc, ijk);
pnanovdb_bool_t is_active;
if (pnanovdb_readaccessor_iscached0(acc, dirty))
{
is_active = pnanovdb_leaf_is_active_and_cache(grid_type, buf, PNANOVDB_DEREF(acc).leaf, ijk, acc);
}
else if (pnanovdb_readaccessor_iscached1(acc, dirty))
{
is_active = pnanovdb_lower_is_active_and_cache(grid_type, buf, PNANOVDB_DEREF(acc).lower, ijk, acc);
}
else if (pnanovdb_readaccessor_iscached2(acc, dirty))
{
is_active = pnanovdb_upper_is_active_and_cache(grid_type, buf, PNANOVDB_DEREF(acc).upper, ijk, acc);
}
else
{
is_active = pnanovdb_root_is_active_and_cache(grid_type, buf, PNANOVDB_DEREF(acc).root, ijk, acc);
}
return is_active;
}
// ------------------------------------------------ Map Transforms -----------------------------------------------------------
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_map_apply(pnanovdb_buf_t buf, pnanovdb_map_handle_t map, PNANOVDB_IN(pnanovdb_vec3_t) src)
{
pnanovdb_vec3_t dst;
float sx = PNANOVDB_DEREF(src).x;
float sy = PNANOVDB_DEREF(src).y;
float sz = PNANOVDB_DEREF(src).z;
dst.x = sx * pnanovdb_map_get_matf(buf, map, 0) + sy * pnanovdb_map_get_matf(buf, map, 1) + sz * pnanovdb_map_get_matf(buf, map, 2) + pnanovdb_map_get_vecf(buf, map, 0);
dst.y = sx * pnanovdb_map_get_matf(buf, map, 3) + sy * pnanovdb_map_get_matf(buf, map, 4) + sz * pnanovdb_map_get_matf(buf, map, 5) + pnanovdb_map_get_vecf(buf, map, 1);
dst.z = sx * pnanovdb_map_get_matf(buf, map, 6) + sy * pnanovdb_map_get_matf(buf, map, 7) + sz * pnanovdb_map_get_matf(buf, map, 8) + pnanovdb_map_get_vecf(buf, map, 2);
return dst;
}
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_map_apply_inverse(pnanovdb_buf_t buf, pnanovdb_map_handle_t map, PNANOVDB_IN(pnanovdb_vec3_t) src)
{
pnanovdb_vec3_t dst;
float sx = PNANOVDB_DEREF(src).x - pnanovdb_map_get_vecf(buf, map, 0);
float sy = PNANOVDB_DEREF(src).y - pnanovdb_map_get_vecf(buf, map, 1);
float sz = PNANOVDB_DEREF(src).z - pnanovdb_map_get_vecf(buf, map, 2);
dst.x = sx * pnanovdb_map_get_invmatf(buf, map, 0) + sy * pnanovdb_map_get_invmatf(buf, map, 1) + sz * pnanovdb_map_get_invmatf(buf, map, 2);
dst.y = sx * pnanovdb_map_get_invmatf(buf, map, 3) + sy * pnanovdb_map_get_invmatf(buf, map, 4) + sz * pnanovdb_map_get_invmatf(buf, map, 5);
dst.z = sx * pnanovdb_map_get_invmatf(buf, map, 6) + sy * pnanovdb_map_get_invmatf(buf, map, 7) + sz * pnanovdb_map_get_invmatf(buf, map, 8);
return dst;
}
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_map_apply_jacobi(pnanovdb_buf_t buf, pnanovdb_map_handle_t map, PNANOVDB_IN(pnanovdb_vec3_t) src)
{
pnanovdb_vec3_t dst;
float sx = PNANOVDB_DEREF(src).x;
float sy = PNANOVDB_DEREF(src).y;
float sz = PNANOVDB_DEREF(src).z;
dst.x = sx * pnanovdb_map_get_matf(buf, map, 0) + sy * pnanovdb_map_get_matf(buf, map, 1) + sz * pnanovdb_map_get_matf(buf, map, 2);
dst.y = sx * pnanovdb_map_get_matf(buf, map, 3) + sy * pnanovdb_map_get_matf(buf, map, 4) + sz * pnanovdb_map_get_matf(buf, map, 5);
dst.z = sx * pnanovdb_map_get_matf(buf, map, 6) + sy * pnanovdb_map_get_matf(buf, map, 7) + sz * pnanovdb_map_get_matf(buf, map, 8);
return dst;
}
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_map_apply_inverse_jacobi(pnanovdb_buf_t buf, pnanovdb_map_handle_t map, PNANOVDB_IN(pnanovdb_vec3_t) src)
{
pnanovdb_vec3_t dst;
float sx = PNANOVDB_DEREF(src).x;
float sy = PNANOVDB_DEREF(src).y;
float sz = PNANOVDB_DEREF(src).z;
dst.x = sx * pnanovdb_map_get_invmatf(buf, map, 0) + sy * pnanovdb_map_get_invmatf(buf, map, 1) + sz * pnanovdb_map_get_invmatf(buf, map, 2);
dst.y = sx * pnanovdb_map_get_invmatf(buf, map, 3) + sy * pnanovdb_map_get_invmatf(buf, map, 4) + sz * pnanovdb_map_get_invmatf(buf, map, 5);
dst.z = sx * pnanovdb_map_get_invmatf(buf, map, 6) + sy * pnanovdb_map_get_invmatf(buf, map, 7) + sz * pnanovdb_map_get_invmatf(buf, map, 8);
return dst;
}
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_grid_world_to_indexf(pnanovdb_buf_t buf, pnanovdb_grid_handle_t grid, PNANOVDB_IN(pnanovdb_vec3_t) src)
{
pnanovdb_map_handle_t map = pnanovdb_grid_get_map(buf, grid);
return pnanovdb_map_apply_inverse(buf, map, src);
}
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_grid_index_to_worldf(pnanovdb_buf_t buf, pnanovdb_grid_handle_t grid, PNANOVDB_IN(pnanovdb_vec3_t) src)
{
pnanovdb_map_handle_t map = pnanovdb_grid_get_map(buf, grid);
return pnanovdb_map_apply(buf, map, src);
}
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_grid_world_to_index_dirf(pnanovdb_buf_t buf, pnanovdb_grid_handle_t grid, PNANOVDB_IN(pnanovdb_vec3_t) src)
{
pnanovdb_map_handle_t map = pnanovdb_grid_get_map(buf, grid);
return pnanovdb_map_apply_inverse_jacobi(buf, map, src);
}
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_grid_index_to_world_dirf(pnanovdb_buf_t buf, pnanovdb_grid_handle_t grid, PNANOVDB_IN(pnanovdb_vec3_t) src)
{
pnanovdb_map_handle_t map = pnanovdb_grid_get_map(buf, grid);
return pnanovdb_map_apply_jacobi(buf, map, src);
}
// ------------------------------------------------ DitherLUT -----------------------------------------------------------
// This table was generated with
/**************
static constexpr inline uint32
SYSwang_inthash(uint32 key)
{
// From http://www.concentric.net/~Ttwang/tech/inthash.htm
key += ~(key << 16);
key ^= (key >> 5);
key += (key << 3);
key ^= (key >> 13);
key += ~(key << 9);
key ^= (key >> 17);
return key;
}
static void
ut_initDitherR(float *pattern, float offset,
int x, int y, int z, int res, int goalres)
{
// These offsets are designed to maximize the difference between
// dither values in nearby voxels within a given 2x2x2 cell, without
// producing axis-aligned artifacts. The are organized in row-major
// order.
static const float theDitherOffset[] = {0,4,6,2,5,1,3,7};
static const float theScale = 0.125F;
int key = (((z << res) + y) << res) + x;
if (res == goalres)
{
pattern[key] = offset;
return;
}
// Randomly flip (on each axis) the dithering patterns used by the
// subcells. This key is xor'd with the subcell index below before
// looking up in the dither offset list.
key = SYSwang_inthash(key) & 7;
x <<= 1;
y <<= 1;
z <<= 1;
offset *= theScale;
for (int i = 0; i < 8; i++)
ut_initDitherR(pattern, offset+theDitherOffset[i ^ key]*theScale,
x+(i&1), y+((i&2)>>1), z+((i&4)>>2), res+1, goalres);
}
// This is a compact algorithm that accomplishes essentially the same thing
// as ut_initDither() above. We should eventually switch to use this and
// clean the dead code.
static fpreal32 *
ut_initDitherRecursive(int goalres)
{
const int nfloat = 1 << (goalres*3);
float *pattern = new float[nfloat];
ut_initDitherR(pattern, 1.0F, 0, 0, 0, 0, goalres);
// This has built an even spacing from 1/nfloat to 1.0.
// however, our dither pattern should be 1/(nfloat+1) to nfloat/(nfloat+1)
// So we do a correction here. Note that the earlier calculations are
// done with powers of 2 so are exact, so it does make sense to delay
// the renormalization to this pass.
float correctionterm = nfloat / (nfloat+1.0F);
for (int i = 0; i < nfloat; i++)
pattern[i] *= correctionterm;
return pattern;
}
theDitherMatrix = ut_initDitherRecursive(3);
for (int i = 0; i < 512/8; i ++)
{
for (int j = 0; j < 8; j ++)
std::cout << theDitherMatrix[i*8+j] << "f, ";
std::cout << std::endl;
}
**************/
PNANOVDB_STATIC_CONST float pnanovdb_dither_lut[512] =
{
0.14425f, 0.643275f, 0.830409f, 0.331384f, 0.105263f, 0.604289f, 0.167641f, 0.666667f,
0.892788f, 0.393762f, 0.0818713f, 0.580897f, 0.853801f, 0.354776f, 0.916179f, 0.417154f,
0.612086f, 0.11306f, 0.79922f, 0.300195f, 0.510721f, 0.0116959f, 0.947368f, 0.448343f,
0.362573f, 0.861598f, 0.0506823f, 0.549708f, 0.261209f, 0.760234f, 0.19883f, 0.697856f,
0.140351f, 0.639376f, 0.576998f, 0.0779727f, 0.522417f, 0.0233918f, 0.460039f, 0.959064f,
0.888889f, 0.389864f, 0.327485f, 0.826511f, 0.272904f, 0.77193f, 0.709552f, 0.210526f,
0.483431f, 0.982456f, 0.296296f, 0.795322f, 0.116959f, 0.615984f, 0.0545809f, 0.553606f,
0.732943f, 0.233918f, 0.545809f, 0.0467836f, 0.865497f, 0.366472f, 0.803119f, 0.304094f,
0.518519f, 0.0194932f, 0.45614f, 0.955166f, 0.729045f, 0.230019f, 0.54191f, 0.042885f,
0.269006f, 0.768031f, 0.705653f, 0.206628f, 0.479532f, 0.978558f, 0.292398f, 0.791423f,
0.237817f, 0.736842f, 0.424951f, 0.923977f, 0.136452f, 0.635478f, 0.323587f, 0.822612f,
0.986355f, 0.487329f, 0.674464f, 0.175439f, 0.88499f, 0.385965f, 0.573099f, 0.0740741f,
0.51462f, 0.0155945f, 0.202729f, 0.701754f, 0.148148f, 0.647174f, 0.834308f, 0.335283f,
0.265107f, 0.764133f, 0.951267f, 0.452242f, 0.896686f, 0.397661f, 0.08577f, 0.584795f,
0.8577f, 0.358674f, 0.920078f, 0.421053f, 0.740741f, 0.241715f, 0.678363f, 0.179337f,
0.109162f, 0.608187f, 0.17154f, 0.670565f, 0.491228f, 0.990253f, 0.42885f, 0.927875f,
0.0662768f, 0.565302f, 0.62768f, 0.128655f, 0.183236f, 0.682261f, 0.744639f, 0.245614f,
0.814815f, 0.315789f, 0.378168f, 0.877193f, 0.931774f, 0.432749f, 0.495127f, 0.994152f,
0.0350877f, 0.534113f, 0.97076f, 0.471735f, 0.214425f, 0.71345f, 0.526316f, 0.0272904f,
0.783626f, 0.2846f, 0.222222f, 0.721248f, 0.962963f, 0.463938f, 0.276803f, 0.775828f,
0.966862f, 0.467836f, 0.405458f, 0.904483f, 0.0701754f, 0.569201f, 0.881092f, 0.382066f,
0.218324f, 0.717349f, 0.654971f, 0.155945f, 0.818713f, 0.319688f, 0.132554f, 0.631579f,
0.0623782f, 0.561404f, 0.748538f, 0.249513f, 0.912281f, 0.413255f, 0.974659f, 0.475634f,
0.810916f, 0.311891f, 0.499025f, 0.998051f, 0.163743f, 0.662768f, 0.226121f, 0.725146f,
0.690058f, 0.191033f, 0.00389864f, 0.502924f, 0.557505f, 0.0584795f, 0.120858f, 0.619883f,
0.440546f, 0.939571f, 0.752437f, 0.253411f, 0.307992f, 0.807018f, 0.869396f, 0.37037f,
0.658869f, 0.159844f, 0.346979f, 0.846004f, 0.588694f, 0.0896686f, 0.152047f, 0.651072f,
0.409357f, 0.908382f, 0.596491f, 0.0974659f, 0.339181f, 0.838207f, 0.900585f, 0.401559f,
0.34308f, 0.842105f, 0.779727f, 0.280702f, 0.693957f, 0.194932f, 0.25731f, 0.756335f,
0.592593f, 0.0935673f, 0.0311891f, 0.530214f, 0.444444f, 0.94347f, 0.506823f, 0.00779727f,
0.68616f, 0.187135f, 0.124756f, 0.623782f, 0.288499f, 0.787524f, 0.350877f, 0.849903f,
0.436647f, 0.935673f, 0.873294f, 0.374269f, 0.538012f, 0.0389864f, 0.60039f, 0.101365f,
0.57115f, 0.0721248f, 0.758285f, 0.259259f, 0.719298f, 0.220273f, 0.532164f, 0.0331384f,
0.321637f, 0.820663f, 0.00974659f, 0.508772f, 0.469786f, 0.968811f, 0.282651f, 0.781676f,
0.539961f, 0.0409357f, 0.727096f, 0.22807f, 0.500975f, 0.00194932f, 0.563353f, 0.0643275f,
0.290448f, 0.789474f, 0.477583f, 0.976608f, 0.251462f, 0.750487f, 0.31384f, 0.812865f,
0.94152f, 0.442495f, 0.879142f, 0.380117f, 0.37232f, 0.871345f, 0.309942f, 0.808967f,
0.192982f, 0.692008f, 0.130604f, 0.62963f, 0.621832f, 0.122807f, 0.559454f, 0.0604289f,
0.660819f, 0.161793f, 0.723197f, 0.224172f, 0.403509f, 0.902534f, 0.840156f, 0.341131f,
0.411306f, 0.910331f, 0.473684f, 0.97271f, 0.653021f, 0.153996f, 0.0916179f, 0.590643f,
0.196881f, 0.695906f, 0.384016f, 0.883041f, 0.0955166f, 0.594542f, 0.157895f, 0.65692f,
0.945419f, 0.446394f, 0.633528f, 0.134503f, 0.844055f, 0.345029f, 0.906433f, 0.407407f,
0.165692f, 0.664717f, 0.103314f, 0.602339f, 0.126706f, 0.625731f, 0.189084f, 0.688109f,
0.91423f, 0.415205f, 0.851852f, 0.352827f, 0.875244f, 0.376218f, 0.937622f, 0.438596f,
0.317739f, 0.816764f, 0.255361f, 0.754386f, 0.996101f, 0.497076f, 0.933723f, 0.434698f,
0.567251f, 0.0682261f, 0.504873f, 0.00584795f, 0.247563f, 0.746589f, 0.185185f, 0.684211f,
0.037037f, 0.536062f, 0.0994152f, 0.598441f, 0.777778f, 0.278752f, 0.465887f, 0.964912f,
0.785575f, 0.28655f, 0.847953f, 0.348928f, 0.0292398f, 0.528265f, 0.7154f, 0.216374f,
0.39961f, 0.898636f, 0.961014f, 0.461988f, 0.0487329f, 0.547758f, 0.111111f, 0.610136f,
0.649123f, 0.150097f, 0.212476f, 0.711501f, 0.797271f, 0.298246f, 0.859649f, 0.360624f,
0.118908f, 0.617934f, 0.0565302f, 0.555556f, 0.329435f, 0.82846f, 0.516569f, 0.0175439f,
0.867446f, 0.368421f, 0.805068f, 0.306043f, 0.578947f, 0.079922f, 0.267057f, 0.766082f,
0.270955f, 0.76998f, 0.707602f, 0.208577f, 0.668616f, 0.169591f, 0.606238f, 0.107212f,
0.520468f, 0.0214425f, 0.45809f, 0.957115f, 0.419103f, 0.918129f, 0.356725f, 0.855751f,
0.988304f, 0.489279f, 0.426901f, 0.925926f, 0.450292f, 0.949318f, 0.512671f, 0.0136452f,
0.239766f, 0.738791f, 0.676413f, 0.177388f, 0.699805f, 0.20078f, 0.263158f, 0.762183f,
0.773879f, 0.274854f, 0.337232f, 0.836257f, 0.672515f, 0.173489f, 0.734893f, 0.235867f,
0.0253411f, 0.524366f, 0.586745f, 0.0877193f, 0.423002f, 0.922027f, 0.48538f, 0.984405f,
0.74269f, 0.243665f, 0.680312f, 0.181287f, 0.953216f, 0.454191f, 0.1423f, 0.641326f,
0.493177f, 0.992203f, 0.430799f, 0.929825f, 0.204678f, 0.703704f, 0.890838f, 0.391813f,
0.894737f, 0.395712f, 0.0838207f, 0.582846f, 0.0448343f, 0.54386f, 0.231969f, 0.730994f,
0.146199f, 0.645224f, 0.832359f, 0.333333f, 0.793372f, 0.294347f, 0.980507f, 0.481481f,
0.364522f, 0.863548f, 0.80117f, 0.302144f, 0.824561f, 0.325536f, 0.138402f, 0.637427f,
0.614035f, 0.11501f, 0.0526316f, 0.551657f, 0.0760234f, 0.575049f, 0.88694f, 0.387914f,
};
PNANOVDB_FORCE_INLINE float pnanovdb_dither_lookup(pnanovdb_bool_t enabled, int offset)
{
return enabled ? pnanovdb_dither_lut[offset & 511] : 0.5f;
}
// ------------------------------------------------ HDDA -----------------------------------------------------------
#ifdef PNANOVDB_HDDA
// Comment out to disable this explicit round-off check
#define PNANOVDB_ENFORCE_FORWARD_STEPPING
#define PNANOVDB_HDDA_FLOAT_MAX 1e38f
struct pnanovdb_hdda_t
{
pnanovdb_int32_t dim;
float tmin;
float tmax;
pnanovdb_coord_t voxel;
pnanovdb_coord_t step;
pnanovdb_vec3_t delta;
pnanovdb_vec3_t next;
};
PNANOVDB_STRUCT_TYPEDEF(pnanovdb_hdda_t)
PNANOVDB_FORCE_INLINE pnanovdb_coord_t pnanovdb_hdda_pos_to_ijk(PNANOVDB_IN(pnanovdb_vec3_t) pos)
{
pnanovdb_coord_t voxel;
voxel.x = pnanovdb_float_to_int32(pnanovdb_floor(PNANOVDB_DEREF(pos).x));
voxel.y = pnanovdb_float_to_int32(pnanovdb_floor(PNANOVDB_DEREF(pos).y));
voxel.z = pnanovdb_float_to_int32(pnanovdb_floor(PNANOVDB_DEREF(pos).z));
return voxel;
}
PNANOVDB_FORCE_INLINE pnanovdb_coord_t pnanovdb_hdda_pos_to_voxel(PNANOVDB_IN(pnanovdb_vec3_t) pos, int dim)
{
pnanovdb_coord_t voxel;
voxel.x = pnanovdb_float_to_int32(pnanovdb_floor(PNANOVDB_DEREF(pos).x)) & (~(dim - 1));
voxel.y = pnanovdb_float_to_int32(pnanovdb_floor(PNANOVDB_DEREF(pos).y)) & (~(dim - 1));
voxel.z = pnanovdb_float_to_int32(pnanovdb_floor(PNANOVDB_DEREF(pos).z)) & (~(dim - 1));
return voxel;
}
PNANOVDB_FORCE_INLINE pnanovdb_vec3_t pnanovdb_hdda_ray_start(PNANOVDB_IN(pnanovdb_vec3_t) origin, float tmin, PNANOVDB_IN(pnanovdb_vec3_t) direction)
{
pnanovdb_vec3_t pos = pnanovdb_vec3_add(
pnanovdb_vec3_mul(PNANOVDB_DEREF(direction), pnanovdb_vec3_uniform(tmin)),
PNANOVDB_DEREF(origin)
);
return pos;
}
PNANOVDB_FORCE_INLINE void pnanovdb_hdda_init(PNANOVDB_INOUT(pnanovdb_hdda_t) hdda, PNANOVDB_IN(pnanovdb_vec3_t) origin, float tmin, PNANOVDB_IN(pnanovdb_vec3_t) direction, float tmax, int dim)
{
PNANOVDB_DEREF(hdda).dim = dim;
PNANOVDB_DEREF(hdda).tmin = tmin;
PNANOVDB_DEREF(hdda).tmax = tmax;
pnanovdb_vec3_t pos = pnanovdb_hdda_ray_start(origin, tmin, direction);
pnanovdb_vec3_t dir_inv = pnanovdb_vec3_div(pnanovdb_vec3_uniform(1.f), PNANOVDB_DEREF(direction));
PNANOVDB_DEREF(hdda).voxel = pnanovdb_hdda_pos_to_voxel(PNANOVDB_REF(pos), dim);
// x
if (PNANOVDB_DEREF(direction).x == 0.f)
{
PNANOVDB_DEREF(hdda).next.x = PNANOVDB_HDDA_FLOAT_MAX;
PNANOVDB_DEREF(hdda).step.x = 0;
PNANOVDB_DEREF(hdda).delta.x = 0.f;
}
else if (dir_inv.x > 0.f)
{
PNANOVDB_DEREF(hdda).step.x = 1;
PNANOVDB_DEREF(hdda).next.x = PNANOVDB_DEREF(hdda).tmin + (PNANOVDB_DEREF(hdda).voxel.x + dim - pos.x) * dir_inv.x;
PNANOVDB_DEREF(hdda).delta.x = dir_inv.x;
}
else
{
PNANOVDB_DEREF(hdda).step.x = -1;
PNANOVDB_DEREF(hdda).next.x = PNANOVDB_DEREF(hdda).tmin + (PNANOVDB_DEREF(hdda).voxel.x - pos.x) * dir_inv.x;
PNANOVDB_DEREF(hdda).delta.x = -dir_inv.x;
}
// y
if (PNANOVDB_DEREF(direction).y == 0.f)
{
PNANOVDB_DEREF(hdda).next.y = PNANOVDB_HDDA_FLOAT_MAX;
PNANOVDB_DEREF(hdda).step.y = 0;
PNANOVDB_DEREF(hdda).delta.y = 0.f;
}
else if (dir_inv.y > 0.f)
{
PNANOVDB_DEREF(hdda).step.y = 1;
PNANOVDB_DEREF(hdda).next.y = PNANOVDB_DEREF(hdda).tmin + (PNANOVDB_DEREF(hdda).voxel.y + dim - pos.y) * dir_inv.y;
PNANOVDB_DEREF(hdda).delta.y = dir_inv.y;
}
else
{
PNANOVDB_DEREF(hdda).step.y = -1;
PNANOVDB_DEREF(hdda).next.y = PNANOVDB_DEREF(hdda).tmin + (PNANOVDB_DEREF(hdda).voxel.y - pos.y) * dir_inv.y;
PNANOVDB_DEREF(hdda).delta.y = -dir_inv.y;
}
// z
if (PNANOVDB_DEREF(direction).z == 0.f)
{
PNANOVDB_DEREF(hdda).next.z = PNANOVDB_HDDA_FLOAT_MAX;
PNANOVDB_DEREF(hdda).step.z = 0;
PNANOVDB_DEREF(hdda).delta.z = 0.f;
}
else if (dir_inv.z > 0.f)
{
PNANOVDB_DEREF(hdda).step.z = 1;
PNANOVDB_DEREF(hdda).next.z = PNANOVDB_DEREF(hdda).tmin + (PNANOVDB_DEREF(hdda).voxel.z + dim - pos.z) * dir_inv.z;
PNANOVDB_DEREF(hdda).delta.z = dir_inv.z;
}
else
{
PNANOVDB_DEREF(hdda).step.z = -1;
PNANOVDB_DEREF(hdda).next.z = PNANOVDB_DEREF(hdda).tmin + (PNANOVDB_DEREF(hdda).voxel.z - pos.z) * dir_inv.z;
PNANOVDB_DEREF(hdda).delta.z = -dir_inv.z;
}
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_hdda_update(PNANOVDB_INOUT(pnanovdb_hdda_t) hdda, PNANOVDB_IN(pnanovdb_vec3_t) origin, PNANOVDB_IN(pnanovdb_vec3_t) direction, int dim)
{
if (PNANOVDB_DEREF(hdda).dim == dim)
{
return PNANOVDB_FALSE;
}
PNANOVDB_DEREF(hdda).dim = dim;
pnanovdb_vec3_t pos = pnanovdb_vec3_add(
pnanovdb_vec3_mul(PNANOVDB_DEREF(direction), pnanovdb_vec3_uniform(PNANOVDB_DEREF(hdda).tmin)),
PNANOVDB_DEREF(origin)
);
pnanovdb_vec3_t dir_inv = pnanovdb_vec3_div(pnanovdb_vec3_uniform(1.f), PNANOVDB_DEREF(direction));
PNANOVDB_DEREF(hdda).voxel = pnanovdb_hdda_pos_to_voxel(PNANOVDB_REF(pos), dim);
if (PNANOVDB_DEREF(hdda).step.x != 0)
{
PNANOVDB_DEREF(hdda).next.x = PNANOVDB_DEREF(hdda).tmin + (PNANOVDB_DEREF(hdda).voxel.x - pos.x) * dir_inv.x;
if (PNANOVDB_DEREF(hdda).step.x > 0)
{
PNANOVDB_DEREF(hdda).next.x += dim * dir_inv.x;
}
}
if (PNANOVDB_DEREF(hdda).step.y != 0)
{
PNANOVDB_DEREF(hdda).next.y = PNANOVDB_DEREF(hdda).tmin + (PNANOVDB_DEREF(hdda).voxel.y - pos.y) * dir_inv.y;
if (PNANOVDB_DEREF(hdda).step.y > 0)
{
PNANOVDB_DEREF(hdda).next.y += dim * dir_inv.y;
}
}
if (PNANOVDB_DEREF(hdda).step.z != 0)
{
PNANOVDB_DEREF(hdda).next.z = PNANOVDB_DEREF(hdda).tmin + (PNANOVDB_DEREF(hdda).voxel.z - pos.z) * dir_inv.z;
if (PNANOVDB_DEREF(hdda).step.z > 0)
{
PNANOVDB_DEREF(hdda).next.z += dim * dir_inv.z;
}
}
return PNANOVDB_TRUE;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_hdda_step(PNANOVDB_INOUT(pnanovdb_hdda_t) hdda)
{
pnanovdb_bool_t ret;
if (PNANOVDB_DEREF(hdda).next.x < PNANOVDB_DEREF(hdda).next.y && PNANOVDB_DEREF(hdda).next.x < PNANOVDB_DEREF(hdda).next.z)
{
#ifdef PNANOVDB_ENFORCE_FORWARD_STEPPING
if (PNANOVDB_DEREF(hdda).next.x <= PNANOVDB_DEREF(hdda).tmin)
{
PNANOVDB_DEREF(hdda).next.x += PNANOVDB_DEREF(hdda).tmin - 0.999999f * PNANOVDB_DEREF(hdda).next.x + 1.0e-6f;
}
#endif
PNANOVDB_DEREF(hdda).tmin = PNANOVDB_DEREF(hdda).next.x;
PNANOVDB_DEREF(hdda).next.x += PNANOVDB_DEREF(hdda).dim * PNANOVDB_DEREF(hdda).delta.x;
PNANOVDB_DEREF(hdda).voxel.x += PNANOVDB_DEREF(hdda).dim * PNANOVDB_DEREF(hdda).step.x;
ret = PNANOVDB_DEREF(hdda).tmin <= PNANOVDB_DEREF(hdda).tmax;
}
else if (PNANOVDB_DEREF(hdda).next.y < PNANOVDB_DEREF(hdda).next.z)
{
#ifdef PNANOVDB_ENFORCE_FORWARD_STEPPING
if (PNANOVDB_DEREF(hdda).next.y <= PNANOVDB_DEREF(hdda).tmin)
{
PNANOVDB_DEREF(hdda).next.y += PNANOVDB_DEREF(hdda).tmin - 0.999999f * PNANOVDB_DEREF(hdda).next.y + 1.0e-6f;
}
#endif
PNANOVDB_DEREF(hdda).tmin = PNANOVDB_DEREF(hdda).next.y;
PNANOVDB_DEREF(hdda).next.y += PNANOVDB_DEREF(hdda).dim * PNANOVDB_DEREF(hdda).delta.y;
PNANOVDB_DEREF(hdda).voxel.y += PNANOVDB_DEREF(hdda).dim * PNANOVDB_DEREF(hdda).step.y;
ret = PNANOVDB_DEREF(hdda).tmin <= PNANOVDB_DEREF(hdda).tmax;
}
else
{
#ifdef PNANOVDB_ENFORCE_FORWARD_STEPPING
if (PNANOVDB_DEREF(hdda).next.z <= PNANOVDB_DEREF(hdda).tmin)
{
PNANOVDB_DEREF(hdda).next.z += PNANOVDB_DEREF(hdda).tmin - 0.999999f * PNANOVDB_DEREF(hdda).next.z + 1.0e-6f;
}
#endif
PNANOVDB_DEREF(hdda).tmin = PNANOVDB_DEREF(hdda).next.z;
PNANOVDB_DEREF(hdda).next.z += PNANOVDB_DEREF(hdda).dim * PNANOVDB_DEREF(hdda).delta.z;
PNANOVDB_DEREF(hdda).voxel.z += PNANOVDB_DEREF(hdda).dim * PNANOVDB_DEREF(hdda).step.z;
ret = PNANOVDB_DEREF(hdda).tmin <= PNANOVDB_DEREF(hdda).tmax;
}
return ret;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_hdda_ray_clip(
PNANOVDB_IN(pnanovdb_vec3_t) bbox_min,
PNANOVDB_IN(pnanovdb_vec3_t) bbox_max,
PNANOVDB_IN(pnanovdb_vec3_t) origin, PNANOVDB_INOUT(float) tmin,
PNANOVDB_IN(pnanovdb_vec3_t) direction, PNANOVDB_INOUT(float) tmax
)
{
pnanovdb_vec3_t dir_inv = pnanovdb_vec3_div(pnanovdb_vec3_uniform(1.f), PNANOVDB_DEREF(direction));
pnanovdb_vec3_t t0 = pnanovdb_vec3_mul(pnanovdb_vec3_sub(PNANOVDB_DEREF(bbox_min), PNANOVDB_DEREF(origin)), dir_inv);
pnanovdb_vec3_t t1 = pnanovdb_vec3_mul(pnanovdb_vec3_sub(PNANOVDB_DEREF(bbox_max), PNANOVDB_DEREF(origin)), dir_inv);
pnanovdb_vec3_t tmin3 = pnanovdb_vec3_min(t0, t1);
pnanovdb_vec3_t tmax3 = pnanovdb_vec3_max(t0, t1);
float tnear = pnanovdb_max(tmin3.x, pnanovdb_max(tmin3.y, tmin3.z));
float tfar = pnanovdb_min(tmax3.x, pnanovdb_min(tmax3.y, tmax3.z));
pnanovdb_bool_t hit = tnear <= tfar;
PNANOVDB_DEREF(tmin) = pnanovdb_max(PNANOVDB_DEREF(tmin), tnear);
PNANOVDB_DEREF(tmax) = pnanovdb_min(PNANOVDB_DEREF(tmax), tfar);
return hit;
}
PNANOVDB_FORCE_INLINE pnanovdb_bool_t pnanovdb_hdda_zero_crossing(
pnanovdb_grid_type_t grid_type,
pnanovdb_buf_t buf,
PNANOVDB_INOUT(pnanovdb_readaccessor_t) acc,
PNANOVDB_IN(pnanovdb_vec3_t) origin, float tmin,
PNANOVDB_IN(pnanovdb_vec3_t) direction, float tmax,
PNANOVDB_INOUT(float) thit,
PNANOVDB_INOUT(float) v
)
{
pnanovdb_coord_t bbox_min = pnanovdb_root_get_bbox_min(buf, PNANOVDB_DEREF(acc).root);
pnanovdb_coord_t bbox_max = pnanovdb_root_get_bbox_max(buf, PNANOVDB_DEREF(acc).root);
pnanovdb_vec3_t bbox_minf = pnanovdb_coord_to_vec3(bbox_min);
pnanovdb_vec3_t bbox_maxf = pnanovdb_coord_to_vec3(pnanovdb_coord_add(bbox_max, pnanovdb_coord_uniform(1)));
pnanovdb_bool_t hit = pnanovdb_hdda_ray_clip(PNANOVDB_REF(bbox_minf), PNANOVDB_REF(bbox_maxf), origin, PNANOVDB_REF(tmin), direction, PNANOVDB_REF(tmax));
if (!hit || tmax > 1.0e20f)
{
return PNANOVDB_FALSE;
}
pnanovdb_vec3_t pos = pnanovdb_hdda_ray_start(origin, tmin, direction);
pnanovdb_coord_t ijk = pnanovdb_hdda_pos_to_ijk(PNANOVDB_REF(pos));
pnanovdb_address_t address = pnanovdb_readaccessor_get_value_address(PNANOVDB_GRID_TYPE_FLOAT, buf, acc, PNANOVDB_REF(ijk));
float v0 = pnanovdb_read_float(buf, address);
pnanovdb_int32_t dim = pnanovdb_uint32_as_int32(pnanovdb_readaccessor_get_dim(PNANOVDB_GRID_TYPE_FLOAT, buf, acc, PNANOVDB_REF(ijk)));
pnanovdb_hdda_t hdda;
pnanovdb_hdda_init(PNANOVDB_REF(hdda), origin, tmin, direction, tmax, dim);
while (pnanovdb_hdda_step(PNANOVDB_REF(hdda)))
{
pnanovdb_vec3_t pos_start = pnanovdb_hdda_ray_start(origin, hdda.tmin + 1.0001f, direction);
ijk = pnanovdb_hdda_pos_to_ijk(PNANOVDB_REF(pos_start));
dim = pnanovdb_uint32_as_int32(pnanovdb_readaccessor_get_dim(PNANOVDB_GRID_TYPE_FLOAT, buf, acc, PNANOVDB_REF(ijk)));
pnanovdb_hdda_update(PNANOVDB_REF(hdda), origin, direction, dim);
if (hdda.dim > 1 || !pnanovdb_readaccessor_is_active(grid_type, buf, acc, PNANOVDB_REF(ijk)))
{
continue;
}
while (pnanovdb_hdda_step(PNANOVDB_REF(hdda)) && pnanovdb_readaccessor_is_active(grid_type, buf, acc, PNANOVDB_REF(hdda.voxel)))
{
ijk = hdda.voxel;
pnanovdb_address_t address = pnanovdb_readaccessor_get_value_address(PNANOVDB_GRID_TYPE_FLOAT, buf, acc, PNANOVDB_REF(ijk));
PNANOVDB_DEREF(v) = pnanovdb_read_float(buf, address);
if (PNANOVDB_DEREF(v) * v0 < 0.f)
{
PNANOVDB_DEREF(thit) = hdda.tmin;
return PNANOVDB_TRUE;
}
}
}
return PNANOVDB_FALSE;
}
#endif
#endif // end of NANOVDB_PNANOVDB_H_HAS_BEEN_INCLUDED
|
NVIDIA-Omniverse/PhysX/flow/include/nvflowext/NvFlowLoader.h | #pragma once
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#ifndef NV_FLOW_LOADER_H
#define NV_FLOW_LOADER_H
#if defined(_WIN32)
#include <Windows.h>
static void* NvFlowLoadLibrary(const char* winName, const char* linuxName)
{
return (void*)LoadLibraryA(winName);
}
static void* NvFlowGetProcAddress(void* module, const char* name)
{
return GetProcAddress((HMODULE)module, name);
}
static void NvFlowFreeLibrary(void* module)
{
FreeLibrary((HMODULE)module);
}
static const char* NvFlowLoadLibraryError()
{
DWORD lastError = GetLastError();
static char buf[1024];
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, sizeof(buf), NULL);
return buf;
}
#else
#include <dlfcn.h>
static void* NvFlowLoadLibrary(const char* winName, const char* linuxName)
{
void* module = dlopen(linuxName, RTLD_NOW);
//if (!module)
//{
// fprintf(stderr, "Module %s failed to load : %s\n", linuxName, dlerror());
//}
return module;
}
static void* NvFlowGetProcAddress(void* module, const char* name)
{
return dlsym(module, name);
}
static void NvFlowFreeLibrary(void* module)
{
dlclose(module);
}
static const char* NvFlowLoadLibraryError()
{
return dlerror();
}
#endif
#include "NvFlowExt.h"
struct NvFlowLoader
{
void* module_nvflow;
void* module_nvflowext;
NvFlowOpList opList;
NvFlowExtOpList extOpList;
NvFlowGridInterface gridInterface;
NvFlowGridParamsInterface gridParamsInterface;
NvFlowContextOptInterface contextOptInterface;
NvFlowDeviceInterface deviceInterface;
};
static void NvFlowLoaderInitDeviceAPI(NvFlowLoader* ptr, void(*printError)(const char* str, void* userdata), void* userdata, NvFlowContextApi deviceAPI)
{
NvFlowReflectClear(ptr, sizeof(NvFlowLoader));
/// Load nvflow and nvflowext
ptr->module_nvflow = NvFlowLoadLibrary("nvflow.dll", "libnvflow.so");
if (ptr->module_nvflow)
{
PFN_NvFlowGetOpList getOpList = (PFN_NvFlowGetOpList)NvFlowGetProcAddress(ptr->module_nvflow, "NvFlowGetOpList");
if (getOpList) { NvFlowOpList_duplicate(&ptr->opList, getOpList()); }
}
else if (printError)
{
printError(NvFlowLoadLibraryError(), userdata);
}
ptr->module_nvflowext = NvFlowLoadLibrary("nvflowext.dll", "libnvflowext.so");
if (ptr->module_nvflowext)
{
PFN_NvFlowGetExtOpList getExtOpList = (PFN_NvFlowGetExtOpList)NvFlowGetProcAddress(ptr->module_nvflowext, "NvFlowGetExtOpList");
PFN_NvFlowGetGridInterface getGridInterface = (PFN_NvFlowGetGridInterface)NvFlowGetProcAddress(ptr->module_nvflowext, "NvFlowGetGridInterface");
PFN_NvFlowGetGridParamsInterface getGridParamsInterface = (PFN_NvFlowGetGridParamsInterface)NvFlowGetProcAddress(ptr->module_nvflowext, "NvFlowGetGridParamsInterface");
PFN_NvFlowGetContextOptInterface getContextOptInterface = (PFN_NvFlowGetContextOptInterface)NvFlowGetProcAddress(ptr->module_nvflowext, "NvFlowGetContextOptInterface");
PFN_NvFlowGetDeviceInterface getDeviceInterface = (PFN_NvFlowGetDeviceInterface)NvFlowGetProcAddress(ptr->module_nvflowext, "NvFlowGetDeviceInterface");
if (getExtOpList) { NvFlowExtOpList_duplicate(&ptr->extOpList, getExtOpList()); }
if (getGridInterface) { NvFlowGridInterface_duplicate(&ptr->gridInterface, getGridInterface()); }
if (getGridParamsInterface) { NvFlowGridParamsInterface_duplicate(&ptr->gridParamsInterface, getGridParamsInterface()); }
if (getContextOptInterface) { NvFlowContextOptInterface_duplicate(&ptr->contextOptInterface, getContextOptInterface()); }
if (getDeviceInterface) { NvFlowDeviceInterface_duplicate(&ptr->deviceInterface, getDeviceInterface(deviceAPI)); }
}
else if (printError)
{
printError(NvFlowLoadLibraryError(), userdata);
}
}
static void NvFlowLoaderInit(NvFlowLoader* ptr, void(*printError)(const char* str, void* userdata), void* userdata)
{
NvFlowLoaderInitDeviceAPI(ptr, printError, userdata, eNvFlowContextApi_vulkan);
}
static void NvFlowLoaderDestroy(NvFlowLoader* ptr)
{
NvFlowFreeLibrary(ptr->module_nvflow);
NvFlowFreeLibrary(ptr->module_nvflowext);
}
#endif |
NVIDIA-Omniverse/PhysX/flow/include/nvflowext/NvFlowExt.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#ifndef NV_FLOW_EXT_H
#define NV_FLOW_EXT_H
#include "NvFlowContext.h"
#include "NvFlow.h"
/// ********************************* EmitterSphere ***************************************
typedef struct NvFlowEmitterSphereParams
{
NvFlowUint64 luid;
NvFlowBool32 enabled;
NvFlowFloat4x4 localToWorld;
NvFlowFloat4x4 localToWorldVelocity;
NvFlowBool32 velocityIsWorldSpace;
NvFlowFloat3 position;
int layer;
float radius;
NvFlowBool32 radiusIsWorldSpace;
float allocationScale;
NvFlowFloat3 velocity;
float divergence;
float temperature;
float fuel;
float burn;
float smoke;
float coupleRateVelocity;
float coupleRateDivergence;
float coupleRateTemperature;
float coupleRateFuel;
float coupleRateBurn;
float coupleRateSmoke;
NvFlowUint numSubSteps;
float physicsVelocityScale;
NvFlowBool32 applyPostPressure;
NvFlowBool32 multisample;
}NvFlowEmitterSphereParams;
#define NvFlowEmitterSphereParams_default_init { \
0llu, /*luid*/ \
NV_FLOW_TRUE, /*enabled*/ \
{ \
1.f, 0.f, 0.f, 0.f, \
0.f, 1.f, 0.f, 0.f, \
0.f, 0.f, 1.f, 0.f, \
0.f, 0.f, 0.f, 1.f \
}, /*localToWorld*/ \
{ \
1.f, 0.f, 0.f, 0.f, \
0.f, 1.f, 0.f, 0.f, \
0.f, 0.f, 1.f, 0.f, \
0.f, 0.f, 0.f, 1.f \
}, /*localToWorldVelocity*/ \
NV_FLOW_FALSE, /*velocityIsWorldSpace*/ \
{0.f, 0.f, 0.f}, /*position*/ \
0, /*layer*/ \
10.f, /*radius*/ \
NV_FLOW_TRUE, /*radiusIsWorldSpace*/ \
1.f, /*allocationScale*/ \
{0.f, 0.f, 400.f}, /*velocity*/ \
0.f, /*divergence*/ \
0.5f, /*temperature*/ \
0.8f, /*fuel*/ \
0.f, /*burn*/ \
0.f, /*smoke*/ \
2.f, /*coupleRateVelocity*/ \
0.f, /*coupleRateDivergence*/ \
2.f, /*coupleRateTemperature*/ \
2.f, /*coupleRateFuel*/ \
0.f, /*coupleRateBurn*/ \
0.f, /*coupleRateSmoke*/ \
1u, /*numSubSteps*/ \
0.f, /*physicsVelocityScale*/ \
NV_FLOW_FALSE, /*applyPostPressure*/ \
NV_FLOW_FALSE, /*multisample*/ \
}
static const NvFlowEmitterSphereParams NvFlowEmitterSphereParams_default = NvFlowEmitterSphereParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterSphereParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint64, luid, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat4x4, localToWorld, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat4x4, localToWorldVelocity, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, velocityIsWorldSpace, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, position, 0, 0)
NV_FLOW_REFLECT_VALUE(int, layer, 0, 0)
NV_FLOW_REFLECT_VALUE(float, radius, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, radiusIsWorldSpace, 0, 0)
NV_FLOW_REFLECT_VALUE(float, allocationScale, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, velocity, 0, 0)
NV_FLOW_REFLECT_VALUE(float, divergence, 0, 0)
NV_FLOW_REFLECT_VALUE(float, temperature, 0, 0)
NV_FLOW_REFLECT_VALUE(float, fuel, 0, 0)
NV_FLOW_REFLECT_VALUE(float, burn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, smoke, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateVelocity, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateDivergence, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateTemperature, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateFuel, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateBurn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateSmoke, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, numSubSteps, 0, 0)
NV_FLOW_REFLECT_VALUE(float, physicsVelocityScale, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, applyPostPressure, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, multisample, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowEmitterSphereParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowEmitterSpherePinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
float deltaTime;
const NvFlowEmitterSphereParams*const* velocityParams;
NvFlowUint64 velocityParamCount;
const NvFlowEmitterSphereParams*const* densityParams;
NvFlowUint64 densityParamCount;
NvFlowSparseTexture value;
NvFlowSparseTexture valueTemp;
NvFlowBool32 isPostPressure;
}NvFlowEmitterSpherePinsIn;
typedef struct NvFlowEmitterSpherePinsOut
{
NvFlowSparseTexture value;
}NvFlowEmitterSpherePinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterSpherePinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterSphereParams, velocityParams, velocityParamCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterSphereParams, densityParams, densityParamCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, value, eNvFlowReflectHint_pinEnabledMutable, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, valueTemp, eNvFlowReflectHint_pinEnabledMutable, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, isPostPressure, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterSpherePinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, value, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowEmitterSphere)
/// ********************************* EmitterSphereAllocate ***************************************
typedef struct NvFlowEmitterSphereAllocatePinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
NvFlowSparseParams sparseParams;
float deltaTime;
const NvFlowEmitterSphereParams*const* params;
NvFlowUint64 paramCount;
}NvFlowEmitterSphereAllocatePinsIn;
typedef struct NvFlowEmitterSphereAllocatePinsOut
{
NvFlowInt4* locations;
NvFlowUint64 locationCount;
}NvFlowEmitterSphereAllocatePinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterSphereAllocatePinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseParams, sparseParams, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterSphereParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterSphereAllocatePinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_ARRAY(NvFlowInt4, locations, locationCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowEmitterSphereAllocate)
/// ********************************* EmitterBox ***************************************
typedef struct NvFlowEmitterBoxParams
{
NvFlowUint64 luid;
NvFlowBool32 enabled;
NvFlowFloat4x4 localToWorld;
NvFlowFloat4x4 localToWorldVelocity;
NvFlowBool32 velocityIsWorldSpace;
NvFlowFloat3 position;
int layer;
NvFlowFloat3 halfSize;
float allocationScale;
NvFlowFloat3 velocity;
float divergence;
float temperature;
float fuel;
float burn;
float smoke;
float coupleRateVelocity;
float coupleRateDivergence;
float coupleRateTemperature;
float coupleRateFuel;
float coupleRateBurn;
float coupleRateSmoke;
float physicsVelocityScale;
NvFlowBool32 applyPostPressure;
NvFlowBool32 multisample;
NvFlowFloat4* clippingPlanes;
NvFlowUint64 clippingPlaneCount;
NvFlowUint* clippingPlaneCounts;
NvFlowUint64 clippingPlaneCountCount;
}NvFlowEmitterBoxParams;
#define NvFlowEmitterBoxParams_default_init { \
0llu, /*luid*/ \
NV_FLOW_TRUE, /*enabled*/ \
{ \
1.f, 0.f, 0.f, 0.f, \
0.f, 1.f, 0.f, 0.f, \
0.f, 0.f, 1.f, 0.f, \
0.f, 0.f, 0.f, 1.f \
}, /*localToWorld*/ \
{ \
1.f, 0.f, 0.f, 0.f, \
0.f, 1.f, 0.f, 0.f, \
0.f, 0.f, 1.f, 0.f, \
0.f, 0.f, 0.f, 1.f \
}, /*localToWorldVelocity*/ \
NV_FLOW_FALSE, /*velocityIsWorldSpace*/ \
{0.f, 0.f, 0.f}, /*position*/ \
0, /*layer*/ \
{10.f, 10.f, 10.f}, /*halfSize*/ \
1.f, /*allocationScale*/ \
{0.f, 0.f, 400.f}, /*velocity*/ \
0.f, /*divergence*/ \
0.5f, /*temperature*/ \
0.8f, /*fuel*/ \
0.f, /*burn*/ \
0.f, /*smoke*/ \
2.f, /*coupleRateVelocity*/ \
0.f, /*coupleRateDivergence*/ \
2.f, /*coupleRateTemperature*/ \
2.f, /*coupleRateFuel*/ \
0.f, /*coupleRateBurn*/ \
0.f, /*coupleRateSmoke*/ \
0.f, /*physicsVelocityScale*/ \
NV_FLOW_FALSE, /*applyPostPressure*/ \
NV_FLOW_FALSE, /*multisample*/ \
0, /*clippingPlanes*/ \
0, /*clippingPlaneCount*/ \
0, /*clippingPlaneCounts*/ \
0 /*clippingPlaneCountCount*/ \
}
static const NvFlowEmitterBoxParams NvFlowEmitterBoxParams_default = NvFlowEmitterBoxParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterBoxParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint64, luid, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat4x4, localToWorld, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat4x4, localToWorldVelocity, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, velocityIsWorldSpace, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, position, 0, 0)
NV_FLOW_REFLECT_VALUE(int, layer, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, halfSize, 0, 0)
NV_FLOW_REFLECT_VALUE(float, allocationScale, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, velocity, 0, 0)
NV_FLOW_REFLECT_VALUE(float, divergence, 0, 0)
NV_FLOW_REFLECT_VALUE(float, temperature, 0, 0)
NV_FLOW_REFLECT_VALUE(float, fuel, 0, 0)
NV_FLOW_REFLECT_VALUE(float, burn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, smoke, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateVelocity, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateDivergence, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateTemperature, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateFuel, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateBurn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateSmoke, 0, 0)
NV_FLOW_REFLECT_VALUE(float, physicsVelocityScale, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, applyPostPressure, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, multisample, 0, 0)
NV_FLOW_REFLECT_ARRAY(NvFlowFloat4, clippingPlanes, clippingPlaneCount, 0, 0)
NV_FLOW_REFLECT_ARRAY(NvFlowUint, clippingPlaneCounts, clippingPlaneCountCount, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowEmitterBoxParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowEmitterBoxPinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
float deltaTime;
const NvFlowEmitterBoxParams*const* velocityParams;
NvFlowUint64 velocityParamCount;
const NvFlowEmitterBoxParams*const* densityParams;
NvFlowUint64 densityParamCount;
NvFlowSparseTexture value;
NvFlowSparseTexture valueTemp;
NvFlowBool32 isPostPressure;
}NvFlowEmitterBoxPinsIn;
typedef struct NvFlowEmitterBoxPinsOut
{
NvFlowSparseTexture value;
}NvFlowEmitterBoxPinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterBoxPinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterBoxParams, velocityParams, velocityParamCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterBoxParams, densityParams, densityParamCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, value, eNvFlowReflectHint_pinEnabledMutable, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, valueTemp, eNvFlowReflectHint_pinEnabledMutable, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, isPostPressure, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterBoxPinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, value, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowEmitterBox)
/// ********************************* EmitterBoxAllocate ***************************************
typedef struct NvFlowEmitterBoxAllocatePinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
NvFlowSparseParams sparseParams;
float deltaTime;
const NvFlowEmitterBoxParams*const* params;
NvFlowUint64 paramCount;
}NvFlowEmitterBoxAllocatePinsIn;
typedef struct NvFlowEmitterBoxAllocatePinsOut
{
NvFlowInt4* locations;
NvFlowUint64 locationCount;
}NvFlowEmitterBoxAllocatePinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterBoxAllocatePinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseParams, sparseParams, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterBoxParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterBoxAllocatePinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_ARRAY(NvFlowInt4, locations, locationCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowEmitterBoxAllocate)
/// ********************************* EmitterPoint ***************************************
typedef struct NvFlowEmitterPointParams
{
NvFlowUint64 luid;
NvFlowBool32 enabled;
NvFlowFloat4x4 localToWorld;
NvFlowFloat4x4 localToWorldVelocity;
NvFlowBool32 velocityIsWorldSpace;
NvFlowUint numSubSteps;
int layer;
NvFlowBool32 allocateMask;
NvFlowFloat3 velocity;
float divergence;
float temperature;
float fuel;
float burn;
float smoke;
NvFlowBool32 colorIsSrgb;
float velocityScale;
float divergenceScale;
float temperatureScale;
float fuelScale;
float burnScale;
float smokeScale;
float coupleRateVelocity;
float coupleRateDivergence;
float coupleRateTemperature;
float coupleRateFuel;
float coupleRateBurn;
float coupleRateSmoke;
NvFlowFloat3* pointPositions;
NvFlowUint64 pointPositionCount;
NvFlowUint64 pointPositionVersion;
NvFlowBool32* pointAllocateMasks;
NvFlowUint64 pointAllocateMaskCount;
NvFlowUint64 pointAllocateMaskVersion;
NvFlowFloat3* pointVelocities;
NvFlowUint64 pointVelocityCount;
NvFlowUint64 pointVelocityVersion;
float* pointDivergences;
NvFlowUint64 pointDivergenceCount;
NvFlowUint64 pointDivergenceVersion;
NvFlowFloat3* pointColors;
NvFlowUint64 pointColorCount;
NvFlowUint64 pointColorVersion;
float* pointTemperatures;
NvFlowUint64 pointTemperatureCount;
NvFlowUint64 pointTemperatureVersion;
float* pointFuels;
NvFlowUint64 pointFuelCount;
NvFlowUint64 pointFuelVersion;
float* pointBurns;
NvFlowUint64 pointBurnCount;
NvFlowUint64 pointBurnVersion;
float* pointSmokes;
NvFlowUint64 pointSmokeCount;
NvFlowUint64 pointSmokeVersion;
float* pointCoupleRateVelocities;
NvFlowUint64 pointCoupleRateVelocityCount;
NvFlowUint64 pointCoupleRateVelocityVersion;
float* pointCoupleRateDivergences;
NvFlowUint64 pointCoupleRateDivergenceCount;
NvFlowUint64 pointCoupleRateDivergenceVersion;
float* pointCoupleRateTemperatures;
NvFlowUint64 pointCoupleRateTemperatureCount;
NvFlowUint64 pointCoupleRateTemperatureVersion;
float* pointCoupleRateFuels;
NvFlowUint64 pointCoupleRateFuelCount;
NvFlowUint64 pointCoupleRateFuelVersion;
float* pointCoupleRateBurns;
NvFlowUint64 pointCoupleRateBurnCount;
NvFlowUint64 pointCoupleRateBurnVersion;
float* pointCoupleRateSmokes;
NvFlowUint64 pointCoupleRateSmokeCount;
NvFlowUint64 pointCoupleRateSmokeVersion;
NvFlowBool32 applyPostPressure;
NvFlowBool32 enableStreaming;
NvFlowBool32 streamOnce;
NvFlowBool32 streamClearAtStart;
NvFlowUint streamingBatchSize;
NvFlowBool32 updateCoarseDensity;
}NvFlowEmitterPointParams;
#define NvFlowEmitterPointParams_default_init { \
0llu, /*luid*/ \
NV_FLOW_TRUE, /*enabled*/ \
{ \
1.f, 0.f, 0.f, 0.f, \
0.f, 1.f, 0.f, 0.f, \
0.f, 0.f, 1.f, 0.f, \
0.f, 0.f, 0.f, 1.f \
}, /*localToWorld*/ \
{ \
1.f, 0.f, 0.f, 0.f, \
0.f, 1.f, 0.f, 0.f, \
0.f, 0.f, 1.f, 0.f, \
0.f, 0.f, 0.f, 1.f \
}, /*localToWorldVelocity*/ \
NV_FLOW_FALSE, /*velocityIsWorldSpace*/ \
1u, /*numSubSteps*/ \
0, /*layer*/ \
NV_FLOW_TRUE, /*allocateMask*/ \
{0.f, 0.f, 100.f}, /*velocity*/ \
0.f, /*divergence*/ \
2.f, /*temperature*/ \
2.f, /*fuel*/ \
0.f, /*burn*/ \
2.f, /*smoke*/ \
NV_FLOW_FALSE, /*colorIsSrgb*/ \
1.f, /*velocityScale*/ \
1.f, /*divergenceScale*/ \
1.f, /*temperatureScale*/ \
1.f, /*fuelScale*/ \
1.f, /*burnScale*/ \
1.f, /*smokeScale*/ \
200.f, /*coupleRateVelocity*/ \
0.f, /*coupleRateDivergence*/ \
200.f, /*coupleRateTemperature*/ \
200.f, /*coupleRateFuel*/ \
0.f, /*coupleRateBurn*/ \
200.f, /*coupleRateSmoke*/ \
0, /*pointPositions*/ \
0, /*pointPositionCount*/ \
0, /*pointPositionVersion*/ \
0, /*pointAllocateMasks*/ \
0, /*pointAllocateMaskCount*/ \
0, /*pointAllocateMaskVersion*/ \
0, /*pointVelocities*/ \
0, /*pointVelocityCount*/ \
0, /*pointVelocityVersion*/ \
0, /*pointDivergences*/ \
0, /*pointDivergenceCount*/ \
0, /*pointDivergenceVersion*/ \
0, /*pointColors*/ \
0, /*pointColorCount*/ \
0, /*pointColorVersion*/ \
0, /*pointTemperatures*/ \
0, /*pointTemperatureCount*/ \
0, /*pointTemperatureVersion*/ \
0, /*pointFuels*/ \
0, /*pointFuelCount*/ \
0, /*pointFuelVersion*/ \
0, /*pointBurns*/ \
0, /*pointBurnCount*/ \
0, /*pointBurnVersion*/ \
0, /*pointSmokes*/ \
0, /*pointSmokeCount*/ \
0, /*pointSmokeVersion*/ \
0, /*pointCoupleRateVelocities*/ \
0, /*pointCoupleRateVelocityCount*/ \
0, /*pointCoupleRateVelocityVersion*/ \
0, /*pointCoupleRateDivergences*/ \
0, /*pointCoupleRateDivergenceCount*/ \
0, /*pointCoupleRateDivergenceVersion*/ \
0, /*pointCoupleRateTemperatures*/ \
0, /*pointCoupleRateTemperatureCount*/ \
0, /*pointCoupleRateTemperatureVersion*/ \
0, /*pointCoupleRateFuels*/ \
0, /*pointCoupleRateFuelCount*/ \
0, /*pointCoupleRateFuelVersion*/ \
0, /*pointCoupleRateBurns*/ \
0, /*pointCoupleRateBurnCount*/ \
0, /*pointCoupleRateBurnVersion*/ \
0, /*pointCoupleRateSmokes*/ \
0, /*pointCoupleRateSmokeCount*/ \
0, /*pointCoupleRateSmokeVersion*/ \
NV_FLOW_FALSE, /*applyPostPressure*/ \
NV_FLOW_FALSE, /*enableStreaming*/ \
NV_FLOW_FALSE, /*streamOnce*/ \
NV_FLOW_FALSE, /*streamClearAtStart*/ \
1048576, /*streamingBatchSize*/ \
NV_FLOW_FALSE, /*updateCoarseDensity*/ \
}
static const NvFlowEmitterPointParams NvFlowEmitterPointParams_default = NvFlowEmitterPointParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterPointParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint64, luid, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat4x4, localToWorld, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat4x4, localToWorldVelocity, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, velocityIsWorldSpace, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, numSubSteps, 0, 0)
NV_FLOW_REFLECT_VALUE(int, layer, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, allocateMask, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, velocity, 0, 0)
NV_FLOW_REFLECT_VALUE(float, divergence, 0, 0)
NV_FLOW_REFLECT_VALUE(float, temperature, 0, 0)
NV_FLOW_REFLECT_VALUE(float, fuel, 0, 0)
NV_FLOW_REFLECT_VALUE(float, burn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, smoke, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, colorIsSrgb, 0, 0)
NV_FLOW_REFLECT_VALUE(float, velocityScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, divergenceScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, temperatureScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, fuelScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, burnScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, smokeScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateVelocity, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateDivergence, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateTemperature, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateFuel, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateBurn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateSmoke, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowFloat3, pointPositions, pointPositionCount, pointPositionVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowBool32, pointAllocateMasks, pointAllocateMaskCount, pointAllocateMaskVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowFloat3, pointVelocities, pointVelocityCount, pointVelocityVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, pointDivergences, pointDivergenceCount, pointDivergenceVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowFloat3, pointColors, pointColorCount, pointColorVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, pointTemperatures, pointTemperatureCount, pointTemperatureVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, pointFuels, pointFuelCount, pointFuelVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, pointBurns, pointBurnCount, pointBurnVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, pointSmokes, pointSmokeCount, pointSmokeVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, pointCoupleRateVelocities, pointCoupleRateVelocityCount, pointCoupleRateVelocityVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, pointCoupleRateDivergences, pointCoupleRateDivergenceCount, pointCoupleRateDivergenceVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, pointCoupleRateTemperatures, pointCoupleRateTemperatureCount, pointCoupleRateTemperatureVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, pointCoupleRateFuels, pointCoupleRateFuelCount, pointCoupleRateFuelVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, pointCoupleRateBurns, pointCoupleRateBurnCount, pointCoupleRateBurnVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, pointCoupleRateSmokes, pointCoupleRateSmokeCount, pointCoupleRateSmokeVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_VALUE(NvFlowBool32, applyPostPressure, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enableStreaming, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, streamOnce, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, streamClearAtStart, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, streamingBatchSize, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, updateCoarseDensity, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowEmitterPointParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowEmitterPointFeedback
{
void* data;
}NvFlowEmitterPointFeedback;
NV_FLOW_REFLECT_STRUCT_OPAQUE_IMPL(NvFlowEmitterPointFeedback)
typedef struct NvFlowEmitterPointPinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
float deltaTime;
const NvFlowEmitterPointParams*const* velocityParams;
NvFlowUint64 velocityParamCount;
const NvFlowEmitterPointParams*const* densityParams;
NvFlowUint64 densityParamCount;
NvFlowSparseTexture value;
NvFlowSparseTexture valueTemp;
NvFlowSparseTexture coarseDensity;
NvFlowBool32 isPostPressure;
NvFlowEmitterPointFeedback feedback;
}NvFlowEmitterPointPinsIn;
typedef struct NvFlowEmitterPointPinsOut
{
NvFlowSparseTexture value;
}NvFlowEmitterPointPinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterPointPinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterPointParams, velocityParams, velocityParamCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterPointParams, densityParams, densityParamCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, value, eNvFlowReflectHint_pinEnabledMutable, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, valueTemp, eNvFlowReflectHint_pinEnabledMutable, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, coarseDensity, eNvFlowReflectHint_pinEnabledMutable, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, isPostPressure, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowEmitterPointFeedback, feedback, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterPointPinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, value, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowEmitterPoint)
/// ********************************* EmitterPointAllocate ***************************************
typedef struct NvFlowEmitterPointAllocatePinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
NvFlowSparseParams sparseParams;
float deltaTime;
const NvFlowEmitterPointParams*const* params;
NvFlowUint64 paramCount;
NvFlowUint3 baseBlockDimBits;
}NvFlowEmitterPointAllocatePinsIn;
typedef struct NvFlowEmitterPointAllocatePinsOut
{
NvFlowInt4* locations;
NvFlowUint64 locationCount;
NvFlowEmitterPointFeedback feedback;
int* clearLayers;
NvFlowUint64 clearLayerCount;
}NvFlowEmitterPointAllocatePinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterPointAllocatePinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseParams, sparseParams, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterPointParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint3, baseBlockDimBits, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterPointAllocatePinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_ARRAY(NvFlowInt4, locations, locationCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowEmitterPointFeedback, feedback, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_ARRAY(int, clearLayers, clearLayerCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowEmitterPointAllocate)
/// ********************************* EmitterMesh ***************************************
typedef struct NvFlowEmitterMeshParams
{
NvFlowUint64 luid;
NvFlowBool32 enabled;
NvFlowFloat4x4 localToWorld;
NvFlowFloat4x4 localToWorldVelocity;
NvFlowBool32 velocityIsWorldSpace;
NvFlowUint numSubSteps;
int layer;
float minDistance;
float maxDistance;
NvFlowBool32 allocateMask;
NvFlowFloat3 velocity;
float divergence;
float temperature;
float fuel;
float burn;
float smoke;
NvFlowBool32 orientationLeftHanded;
NvFlowBool32 colorIsSrgb;
float velocityScale;
float divergenceScale;
float temperatureScale;
float fuelScale;
float burnScale;
float smokeScale;
float coupleRateVelocity;
float coupleRateDivergence;
float coupleRateTemperature;
float coupleRateFuel;
float coupleRateBurn;
float coupleRateSmoke;
int* meshSubsetFaceCounts;
NvFlowUint64 meshSubsetFaceCountCount;
NvFlowUint64 meshSubsetFaceCountVersion;
int* meshSubsetLayers;
NvFlowUint64 meshSubsetLayerCount;
NvFlowUint64 meshSubsetLayerVersion;
NvFlowBool32* meshSubsetEnableds;
NvFlowUint64 meshSubsetEnabledCount;
NvFlowUint64 meshSubsetEnabledVersion;
NvFlowFloat3* meshPositions;
NvFlowUint64 meshPositionCount;
NvFlowUint64 meshPositionVersion;
int* meshFaceVertexIndices;
NvFlowUint64 meshFaceVertexIndexCount;
NvFlowUint64 meshFaceVertexIndexVersion;
int* meshFaceVertexCounts;
NvFlowUint64 meshFaceVertexCountCount;
NvFlowUint64 meshFaceVertexCountVersion;
NvFlowFloat3* meshVelocities;
NvFlowUint64 meshVelocityCount;
NvFlowUint64 meshVelocityVersion;
float* meshDivergences;
NvFlowUint64 meshDivergenceCount;
NvFlowUint64 meshDivergenceVersion;
NvFlowFloat3* meshColors;
NvFlowUint64 meshColorCount;
NvFlowUint64 meshColorVersion;
float* meshTemperatures;
NvFlowUint64 meshTemperatureCount;
NvFlowUint64 meshTemperatureVersion;
float* meshFuels;
NvFlowUint64 meshFuelCount;
NvFlowUint64 meshFuelVersion;
float* meshBurns;
NvFlowUint64 meshBurnCount;
NvFlowUint64 meshBurnVersion;
float* meshSmokes;
NvFlowUint64 meshSmokeCount;
NvFlowUint64 meshSmokeVersion;
float* meshCoupleRateVelocities;
NvFlowUint64 meshCoupleRateVelocityCount;
NvFlowUint64 meshCoupleRateVelocityVersion;
float* meshCoupleRateDivergences;
NvFlowUint64 meshCoupleRateDivergenceCount;
NvFlowUint64 meshCoupleRateDivergenceVersion;
float* meshCoupleRateTemperatures;
NvFlowUint64 meshCoupleRateTemperatureCount;
NvFlowUint64 meshCoupleRateTemperatureVersion;
float* meshCoupleRateFuels;
NvFlowUint64 meshCoupleRateFuelCount;
NvFlowUint64 meshCoupleRateFuelVersion;
float* meshCoupleRateBurns;
NvFlowUint64 meshCoupleRateBurnCount;
NvFlowUint64 meshCoupleRateBurnVersion;
float* meshCoupleRateSmokes;
NvFlowUint64 meshCoupleRateSmokeCount;
NvFlowUint64 meshCoupleRateSmokeVersion;
float physicsVelocityScale;
NvFlowBool32 applyPostPressure;
}NvFlowEmitterMeshParams;
#define NvFlowEmitterMeshParams_default_init { \
0llu, /*luid*/ \
NV_FLOW_TRUE, /*enabled*/ \
{ \
1.f, 0.f, 0.f, 0.f, \
0.f, 1.f, 0.f, 0.f, \
0.f, 0.f, 1.f, 0.f, \
0.f, 0.f, 0.f, 1.f \
}, /*localToWorld*/ \
{ \
1.f, 0.f, 0.f, 0.f, \
0.f, 1.f, 0.f, 0.f, \
0.f, 0.f, 1.f, 0.f, \
0.f, 0.f, 0.f, 1.f \
}, /*localToWorldVelocity*/ \
NV_FLOW_FALSE, /*velocityIsWorldSpace*/ \
1u, /*numSubSteps*/ \
0, /*layer*/ \
-0.8f, /*minDistance*/ \
0.3f, /*minDistance*/ \
NV_FLOW_TRUE, /*allocateMask*/ \
{0.f, 0.f, 100.f}, /*velocity*/ \
0.f, /*divergence*/ \
2.f, /*temperature*/ \
0.8f, /*fuel*/ \
0.f, /*burn*/ \
2.f, /*smoke*/ \
NV_FLOW_FALSE, /*orientationLeftHanded*/ \
NV_FLOW_FALSE, /*colorIsSrgb*/ \
1.f, /*velocityScale*/ \
1.f, /*divergenceScale*/ \
1.f, /*temperatureScale*/ \
1.f, /*fuelScale*/ \
1.f, /*burnScale*/ \
1.f, /*smokeScale*/ \
2.f, /*coupleRateVelocity*/ \
0.f, /*coupleRateDivergence*/ \
10.f, /*coupleRateTemperature*/ \
2.f, /*coupleRateFuel*/ \
0.f, /*coupleRateBurn*/ \
2.f, /*coupleRateSmoke*/ \
0, /*meshSubsetFaceCounts*/ \
0, /*meshSubsetFaceCountCount*/ \
0, /*meshSubsetFaceCountVersion*/ \
0, /*meshSubsetLayers*/ \
0, /*meshSubsetLayerCount*/ \
0, /*meshSubsetLayerVersion*/ \
0, /*meshSubsetEnableds*/ \
0, /*meshSubsetEnabledCount*/ \
0, /*meshSubsetEnabledVersion*/ \
0, /*meshPositions*/ \
0, /*meshPositionCount*/ \
0, /*meshPositionVersion*/ \
0, /*meshFaceVertexIndices*/ \
0, /*meshFaceVertexIndexCount;*/ \
0, /*meshFaceVertexIndexVersion*/ \
0, /*meshFaceVertexCounts*/ \
0, /*meshFaceVertexCountCount*/ \
0, /*meshFaceVertexCountVersion*/ \
0, /*meshVelocities*/ \
0, /*meshVelocityCount*/ \
0, /*meshVelocityVersion*/ \
0, /*meshDivergences*/ \
0, /*meshDivergenceCount*/ \
0, /*meshDivergenceVersion*/ \
0, /*meshColors*/ \
0, /*meshColorCount*/ \
0, /*meshColorVersion*/ \
0, /*meshTemperatures*/ \
0, /*meshTemperatureCount*/ \
0, /*meshTemperatureVersion*/ \
0, /*meshFuels*/ \
0, /*meshFuelCount*/ \
0, /*meshFuelVersion*/ \
0, /*meshBurns*/ \
0, /*meshBurnCount*/ \
0, /*meshBurnVersion*/ \
0, /*meshSmokes*/ \
0, /*meshSmokeCount*/ \
0, /*meshSmokeVersion*/ \
0, /*meshCoupleRateVelocities*/ \
0, /*meshCoupleRateVelocityCount*/ \
0, /*meshCoupleRateVelocityVersion*/ \
0, /*meshCoupleRateDivergences*/ \
0, /*meshCoupleRateDivergenceCount*/ \
0, /*meshCoupleRateDivergenceVersion*/ \
0, /*meshCoupleRateTemperatures*/ \
0, /*meshCoupleRateTemperatureCount*/ \
0, /*meshCoupleRateTemperatureVersion*/ \
0, /*meshCoupleRateFuels*/ \
0, /*meshCoupleRateFuelCount*/ \
0, /*meshCoupleRateFuelVersion*/ \
0, /*meshCoupleRateBurns*/ \
0, /*meshCoupleRateBurnCount*/ \
0, /*meshCoupleRateBurnVersion*/ \
0, /*meshCoupleRateSmokes*/ \
0, /*meshCoupleRateSmokeCount*/ \
0, /*meshCoupleRateSmokeVersion*/ \
0.f, /*physicsVelocityScale*/ \
NV_FLOW_FALSE, /*applyPostPressure*/ \
}
static const NvFlowEmitterMeshParams NvFlowEmitterMeshParams_default = NvFlowEmitterMeshParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterMeshParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint64, luid, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat4x4, localToWorld, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat4x4, localToWorldVelocity, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, velocityIsWorldSpace, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, numSubSteps, 0, 0)
NV_FLOW_REFLECT_VALUE(int, layer, 0, 0)
NV_FLOW_REFLECT_VALUE(float, minDistance, 0, 0)
NV_FLOW_REFLECT_VALUE(float, maxDistance, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, allocateMask, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, velocity, 0, 0)
NV_FLOW_REFLECT_VALUE(float, divergence, 0, 0)
NV_FLOW_REFLECT_VALUE(float, temperature, 0, 0)
NV_FLOW_REFLECT_VALUE(float, fuel, 0, 0)
NV_FLOW_REFLECT_VALUE(float, burn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, smoke, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, orientationLeftHanded, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, colorIsSrgb, 0, 0)
NV_FLOW_REFLECT_VALUE(float, velocityScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, divergenceScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, temperatureScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, fuelScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, burnScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, smokeScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateVelocity, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateDivergence, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateTemperature, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateFuel, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateBurn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateSmoke, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(int, meshSubsetFaceCounts, meshSubsetFaceCountCount, meshSubsetFaceCountVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(int, meshSubsetLayers, meshSubsetLayerCount, meshSubsetLayerVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowBool32, meshSubsetEnableds, meshSubsetEnabledCount, meshSubsetEnabledVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowFloat3, meshPositions, meshPositionCount, meshPositionVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(int, meshFaceVertexIndices, meshFaceVertexIndexCount, meshFaceVertexIndexVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(int, meshFaceVertexCounts, meshFaceVertexCountCount, meshFaceVertexCountVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowFloat3, meshVelocities, meshVelocityCount, meshVelocityVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, meshDivergences, meshDivergenceCount, meshDivergenceVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowFloat3, meshColors, meshColorCount, meshColorVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, meshTemperatures, meshTemperatureCount, meshTemperatureVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, meshFuels, meshFuelCount, meshFuelVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, meshBurns, meshBurnCount, meshBurnVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, meshSmokes, meshSmokeCount, meshSmokeVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, meshCoupleRateVelocities, meshCoupleRateVelocityCount, meshCoupleRateVelocityVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, meshCoupleRateDivergences, meshCoupleRateDivergenceCount, meshCoupleRateDivergenceVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, meshCoupleRateTemperatures, meshCoupleRateTemperatureCount, meshCoupleRateTemperatureVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, meshCoupleRateFuels, meshCoupleRateFuelCount, meshCoupleRateFuelVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, meshCoupleRateBurns, meshCoupleRateBurnCount, meshCoupleRateBurnVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, meshCoupleRateSmokes, meshCoupleRateSmokeCount, meshCoupleRateSmokeVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_VALUE(float, physicsVelocityScale, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, applyPostPressure, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowEmitterMeshParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowEmitterMeshFeedback
{
void* data;
}NvFlowEmitterMeshFeedback;
NV_FLOW_REFLECT_STRUCT_OPAQUE_IMPL(NvFlowEmitterMeshFeedback)
typedef struct NvFlowEmitterMeshPinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
float deltaTime;
const NvFlowEmitterMeshParams*const* velocityParams;
NvFlowUint64 velocityParamCount;
const NvFlowEmitterMeshParams*const* densityParams;
NvFlowUint64 densityParamCount;
NvFlowSparseTexture value;
NvFlowSparseTexture valueTemp;
NvFlowBool32 isPostPressure;
NvFlowEmitterMeshFeedback feedback;
}NvFlowEmitterMeshPinsIn;
typedef struct NvFlowEmitterMeshPinsOut
{
NvFlowSparseTexture value;
}NvFlowEmitterMeshPinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterMeshPinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterMeshParams, velocityParams, velocityParamCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterMeshParams, densityParams, densityParamCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, value, eNvFlowReflectHint_pinEnabledMutable, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, valueTemp, eNvFlowReflectHint_pinEnabledMutable, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, isPostPressure, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowEmitterMeshFeedback, feedback, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterMeshPinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, value, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowEmitterMesh)
/// ********************************* EmitterMeshAllocate ***************************************
typedef struct NvFlowEmitterMeshAllocatePinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
NvFlowSparseParams sparseParams;
float deltaTime;
const NvFlowEmitterMeshParams*const* params;
NvFlowUint64 paramCount;
NvFlowUint3 baseBlockDimBits;
}NvFlowEmitterMeshAllocatePinsIn;
typedef struct NvFlowEmitterMeshAllocatePinsOut
{
NvFlowInt4* locations;
NvFlowUint64 locationCount;
NvFlowEmitterMeshFeedback feedback;
}NvFlowEmitterMeshAllocatePinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterMeshAllocatePinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseParams, sparseParams, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterMeshParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint3, baseBlockDimBits, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterMeshAllocatePinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_ARRAY(NvFlowInt4, locations, locationCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowEmitterMeshFeedback, feedback, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowEmitterMeshAllocate)
/// ********************************* EmitterTexture ***************************************
typedef struct NvFlowEmitterTextureParams
{
NvFlowUint64 luid;
NvFlowBool32 enabled;
NvFlowFloat4x4 localToWorld;
NvFlowFloat4x4 localToWorldVelocity;
NvFlowBool32 velocityIsWorldSpace;
NvFlowFloat3 position;
int layer;
NvFlowFloat3 halfSize;
float allocationScale;
NvFlowFloat3 velocity;
float divergence;
float temperature;
float fuel;
float burn;
float smoke;
NvFlowBool32 colorIsSrgb;
float velocityScale;
float divergenceScale;
float temperatureScale;
float fuelScale;
float burnScale;
float smokeScale;
float coupleRateVelocity;
float coupleRateDivergence;
float coupleRateTemperature;
float coupleRateFuel;
float coupleRateBurn;
float coupleRateSmoke;
NvFlowUint textureWidth;
NvFlowUint textureHeight;
NvFlowUint textureDepth;
NvFlowUint textureFirstElement;
NvFlowFloat3* textureVelocities;
NvFlowUint64 textureVelocityCount;
NvFlowUint64 textureVelocityVersion;
float* textureDivergences;
NvFlowUint64 textureDivergenceCount;
NvFlowUint64 textureDivergenceVersion;
float* textureTemperatures;
NvFlowUint64 textureTemperatureCount;
NvFlowUint64 textureTemperatureVersion;
float* textureFuels;
NvFlowUint64 textureFuelCount;
NvFlowUint64 textureFuelVersion;
float* textureBurns;
NvFlowUint64 textureBurnCount;
NvFlowUint64 textureBurnVersion;
float* textureSmokes;
NvFlowUint64 textureSmokeCount;
NvFlowUint64 textureSmokeVersion;
float* textureCoupleRateVelocities;
NvFlowUint64 textureCoupleRateVelocityCount;
NvFlowUint64 textureCoupleRateVelocityVersion;
float* textureCoupleRateDivergences;
NvFlowUint64 textureCoupleRateDivergenceCount;
NvFlowUint64 textureCoupleRateDivergenceVersion;
float* textureCoupleRateTemperatures;
NvFlowUint64 textureCoupleRateTemperatureCount;
NvFlowUint64 textureCoupleRateTemperatureVersion;
float* textureCoupleRateFuels;
NvFlowUint64 textureCoupleRateFuelCount;
NvFlowUint64 textureCoupleRateFuelVersion;
float* textureCoupleRateBurns;
NvFlowUint64 textureCoupleRateBurnCount;
NvFlowUint64 textureCoupleRateBurnVersion;
float* textureCoupleRateSmokes;
NvFlowUint64 textureCoupleRateSmokeCount;
NvFlowUint64 textureCoupleRateSmokeVersion;
NvFlowBool32 applyPostPressure;
}NvFlowEmitterTextureParams;
#define NvFlowEmitterTextureParams_default_init { \
0llu, /*luid*/ \
NV_FLOW_TRUE, /*enabled*/ \
{ \
1.f, 0.f, 0.f, 0.f, \
0.f, 1.f, 0.f, 0.f, \
0.f, 0.f, 1.f, 0.f, \
0.f, 0.f, 0.f, 1.f \
}, /*localToWorld*/ \
{ \
1.f, 0.f, 0.f, 0.f, \
0.f, 1.f, 0.f, 0.f, \
0.f, 0.f, 1.f, 0.f, \
0.f, 0.f, 0.f, 1.f \
}, /*localToWorldVelocity*/ \
NV_FLOW_FALSE, /*velocityIsWorldSpace*/ \
{0.f, 0.f, 0.f}, /*position*/ \
0, /*layer*/ \
{10.f, 10.f, 10.f}, /*halfSize*/ \
1.f, /*fallocationScale*/ \
{0.f, 0.f, 400.f}, /*velocity*/ \
0.f, /*divergence*/ \
0.5f, /*temperature*/ \
0.8f, /*fuel*/ \
0.f, /*burn*/ \
0.f, /*smoke*/ \
NV_FLOW_FALSE, /*colorIsSrgb*/ \
1.f, /*velocityScale*/ \
1.f, /*divergenceScale*/ \
1.f, /*temperatureScale*/ \
1.f, /*fuelScale*/ \
1.f, /*burnScale*/ \
1.f, /*smokeScale*/ \
2.f, /*coupleRateVelocity*/ \
0.f, /*coupleRateDivergence*/ \
2.f, /*coupleRateTemperature*/ \
2.f, /*coupleRateFuel*/ \
0.f, /*coupleRateBurn*/ \
0.f, /*coupleRateSmoke*/ \
0u, /*textureWidth*/ \
0u, /*textureHeight*/ \
0u, /*textureDepth*/ \
0u, /*textureFirstElement*/ \
0, /*textureVelocities*/ \
0, /*textureVelocityCount*/ \
0, /*textureVelocityVersion*/ \
0, /*textureDivergences*/ \
0, /*textureDivergenceCount*/ \
0, /*textureDivergenceVersion*/ \
0, /*textureTemperatures*/ \
0, /*textureTemperatureCount*/ \
0, /*textureTemperatureVersion*/ \
0, /*textureFuels*/ \
0, /*textureFuelCount*/ \
0, /*textureFuelVersion*/ \
0, /*textureBurns*/ \
0, /*textureBurnCount*/ \
0, /*textureBurnVersion*/ \
0, /*textureSmokes*/ \
0, /*textureSmokeCount*/ \
0, /*textureSmokeVersion*/ \
0, /*textureCoupleRateVelocities*/ \
0, /*textureCoupleRateVelocityCount*/ \
0, /*textureCoupleRateVelocityVersion*/ \
0, /*textureCoupleRateDivergences*/ \
0, /*textureCoupleRateDivergenceCount*/ \
0, /*textureCoupleRateDivergenceVersion*/ \
0, /*textureCoupleRateTemperatures*/ \
0, /*textureCoupleRateTemperatureCount*/ \
0, /*textureCoupleRateTemperatureVersion*/ \
0, /*textureCoupleRateFuels*/ \
0, /*textureCoupleRateFuelCount*/ \
0, /*textureCoupleRateFuelVersion*/ \
0, /*textureCoupleRateBurns*/ \
0, /*textureCoupleRateBurnCount*/ \
0, /*textureCoupleRateBurnVersion*/ \
0, /*textureCoupleRateSmokes*/ \
0, /*textureCoupleRateSmokeCount*/ \
0, /*textureCoupleRateSmokeVersion*/ \
NV_FLOW_FALSE /*applyPostPressure*/ \
}
static const NvFlowEmitterTextureParams NvFlowEmitterTextureParams_default = NvFlowEmitterTextureParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterTextureParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint64, luid, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat4x4, localToWorld, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat4x4, localToWorldVelocity, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, velocityIsWorldSpace, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, position, 0, 0)
NV_FLOW_REFLECT_VALUE(int, layer, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, halfSize, 0, 0)
NV_FLOW_REFLECT_VALUE(float, allocationScale, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, velocity, 0, 0)
NV_FLOW_REFLECT_VALUE(float, divergence, 0, 0)
NV_FLOW_REFLECT_VALUE(float, temperature, 0, 0)
NV_FLOW_REFLECT_VALUE(float, fuel, 0, 0)
NV_FLOW_REFLECT_VALUE(float, burn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, smoke, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, colorIsSrgb, 0, 0)
NV_FLOW_REFLECT_VALUE(float, velocityScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, divergenceScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, temperatureScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, fuelScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, burnScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, smokeScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateVelocity, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateDivergence, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateTemperature, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateFuel, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateBurn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateSmoke, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, textureWidth, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, textureHeight, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, textureDepth, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, textureFirstElement, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowFloat3, textureVelocities, textureVelocityCount, textureVelocityVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, textureDivergences, textureDivergenceCount, textureDivergenceVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, textureTemperatures, textureTemperatureCount, textureTemperatureVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, textureFuels, textureFuelCount, textureFuelVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, textureBurns, textureBurnCount, textureBurnVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, textureSmokes, textureSmokeCount, textureSmokeVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, textureCoupleRateVelocities, textureCoupleRateVelocityCount, textureCoupleRateVelocityVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, textureCoupleRateDivergences, textureCoupleRateDivergenceCount, textureCoupleRateDivergenceVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, textureCoupleRateTemperatures, textureCoupleRateTemperatureCount, textureCoupleRateTemperatureVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, textureCoupleRateFuels, textureCoupleRateFuelCount, textureCoupleRateFuelVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, textureCoupleRateBurns, textureCoupleRateBurnCount, textureCoupleRateBurnVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY_VERSIONED(float, textureCoupleRateSmokes, textureCoupleRateSmokeCount, textureCoupleRateSmokeVersion, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_VALUE(NvFlowBool32, applyPostPressure, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowEmitterTextureParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowEmitterTexturePinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
float deltaTime;
const NvFlowEmitterTextureParams*const* velocityParams;
NvFlowUint64 velocityParamCount;
const NvFlowEmitterTextureParams*const* densityParams;
NvFlowUint64 densityParamCount;
NvFlowSparseTexture value;
NvFlowSparseTexture valueTemp;
NvFlowBool32 isPostPressure;
}NvFlowEmitterTexturePinsIn;
typedef struct NvFlowEmitterTexturePinsOut
{
NvFlowSparseTexture value;
}NvFlowEmitterTexturePinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterTexturePinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterTextureParams, velocityParams, velocityParamCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterTextureParams, densityParams, densityParamCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, value, eNvFlowReflectHint_pinEnabledMutable, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, valueTemp, eNvFlowReflectHint_pinEnabledMutable, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, isPostPressure, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterTexturePinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, value, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowEmitterTexture)
/// ********************************* EmitterTextureAllocate ***************************************
typedef struct NvFlowEmitterTextureAllocatePinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
NvFlowSparseParams sparseParams;
float deltaTime;
const NvFlowEmitterTextureParams*const* params;
NvFlowUint64 paramCount;
}NvFlowEmitterTextureAllocatePinsIn;
typedef struct NvFlowEmitterTextureAllocatePinsOut
{
NvFlowInt4* locations;
NvFlowUint64 locationCount;
}NvFlowEmitterTextureAllocatePinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterTextureAllocatePinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseParams, sparseParams, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterTextureParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterTextureAllocatePinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_ARRAY(NvFlowInt4, locations, locationCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowEmitterTextureAllocate)
/// ********************************* EmitterNanoVdb ***************************************
typedef struct NvFlowEmitterNanoVdbParams
{
NvFlowUint64 luid;
NvFlowBool32 enabled;
NvFlowFloat4x4 localToWorld;
NvFlowFloat4x4 localToWorldVelocity;
NvFlowBool32 velocityIsWorldSpace;
int layer;
float allocationScale;
NvFlowFloat3 velocity;
float divergence;
float temperature;
float fuel;
float burn;
float smoke;
NvFlowBool32 colorIsSrgb;
float velocityScale;
float divergenceScale;
float temperatureScale;
float fuelScale;
float burnScale;
float smokeScale;
float coupleRateVelocity;
float coupleRateDivergence;
float coupleRateTemperature;
float coupleRateFuel;
float coupleRateBurn;
float coupleRateSmoke;
float minDistance;
float maxDistance;
NvFlowUint* nanoVdbDistances;
NvFlowUint64 nanoVdbDistanceCount;
NvFlowUint64 nanoVdbDistanceVersion;
NvFlowUint64 nanoVdbDistanceFirstElement;
NvFlowUint* nanoVdbVelocities;
NvFlowUint64 nanoVdbVelocityCount;
NvFlowUint64 nanoVdbVelocityVersion;
NvFlowUint64 nanoVdbVelocityFirstElement;
NvFlowUint* nanoVdbDivergences;
NvFlowUint64 nanoVdbDivergenceCount;
NvFlowUint64 nanoVdbDivergenceVersion;
NvFlowUint64 nanoVdbDivergenceFirstElement;
NvFlowUint* nanoVdbTemperatures;
NvFlowUint64 nanoVdbTemperatureCount;
NvFlowUint64 nanoVdbTemperatureVersion;
NvFlowUint64 nanoVdbTemperatureFirstElement;
NvFlowUint* nanoVdbFuels;
NvFlowUint64 nanoVdbFuelCount;
NvFlowUint64 nanoVdbFuelVersion;
NvFlowUint64 nanoVdbFuelFirstElement;
NvFlowUint* nanoVdbBurns;
NvFlowUint64 nanoVdbBurnCount;
NvFlowUint64 nanoVdbBurnVersion;
NvFlowUint64 nanoVdbBurnFirstElement;
NvFlowUint* nanoVdbSmokes;
NvFlowUint64 nanoVdbSmokeCount;
NvFlowUint64 nanoVdbSmokeVersion;
NvFlowUint64 nanoVdbSmokeFirstElement;
NvFlowUint* nanoVdbCoupleRateVelocities;
NvFlowUint64 nanoVdbCoupleRateVelocityCount;
NvFlowUint64 nanoVdbCoupleRateVelocityVersion;
NvFlowUint64 nanoVdbCoupleRateVelocityFirstElement;
NvFlowUint* nanoVdbCoupleRateDivergences;
NvFlowUint64 nanoVdbCoupleRateDivergenceCount;
NvFlowUint64 nanoVdbCoupleRateDivergenceVersion;
NvFlowUint64 nanoVdbCoupleRateDivergenceFirstElement;
NvFlowUint* nanoVdbCoupleRateTemperatures;
NvFlowUint64 nanoVdbCoupleRateTemperatureCount;
NvFlowUint64 nanoVdbCoupleRateTemperatureVersion;
NvFlowUint64 nanoVdbCoupleRateTemperatureFirstElement;
NvFlowUint* nanoVdbCoupleRateFuels;
NvFlowUint64 nanoVdbCoupleRateFuelCount;
NvFlowUint64 nanoVdbCoupleRateFuelVersion;
NvFlowUint64 nanoVdbCoupleRateFuelFirstElement;
NvFlowUint* nanoVdbCoupleRateBurns;
NvFlowUint64 nanoVdbCoupleRateBurnCount;
NvFlowUint64 nanoVdbCoupleRateBurnVersion;
NvFlowUint64 nanoVdbCoupleRateBurnFirstElement;
NvFlowUint* nanoVdbCoupleRateSmokes;
NvFlowUint64 nanoVdbCoupleRateSmokeCount;
NvFlowUint64 nanoVdbCoupleRateSmokeVersion;
NvFlowUint64 nanoVdbCoupleRateSmokeFirstElement;
NvFlowUint* nanoVdbRgba8s;
NvFlowUint64 nanoVdbRgba8Count;
NvFlowUint64 nanoVdbRgba8Version;
NvFlowUint64 nanoVdbRgba8FirstElement;
NvFlowBool32 applyPostPressure;
NvFlowBool32 allocateActiveLeaves;
}NvFlowEmitterNanoVdbParams;
#define NvFlowEmitterNanoVdbParams_default_init { \
0llu, /*luid*/ \
NV_FLOW_TRUE, /*enabled*/ \
{ \
1.f, 0.f, 0.f, 0.f, \
0.f, 1.f, 0.f, 0.f, \
0.f, 0.f, 1.f, 0.f, \
0.f, 0.f, 0.f, 1.f \
}, /*localToWorld*/ \
{ \
1.f, 0.f, 0.f, 0.f, \
0.f, 1.f, 0.f, 0.f, \
0.f, 0.f, 1.f, 0.f, \
0.f, 0.f, 0.f, 1.f \
}, /*localToWorldVelocity*/ \
NV_FLOW_FALSE, /*velocityIsWorldSpace*/ \
0, /*layer*/ \
1.f, /*fallocationScale*/ \
{0.f, 0.f, 0.f}, /*velocity*/ \
0.f, /*divergence*/ \
2.f, /*temperature*/ \
0.0f, /*fuel*/ \
0.f, /*burn*/ \
10.f, /*smoke*/ \
NV_FLOW_FALSE, /*colorIsSrgb*/ \
1.f, /*velocityScale*/ \
1.f, /*divergenceScale*/ \
1.f, /*temperatureScale*/ \
1.f, /*fuelScale*/ \
1.f, /*burnScale*/ \
1.f, /*smokeScale*/ \
2.f, /*coupleRateVelocity*/ \
0.f, /*coupleRateDivergence*/ \
2.f, /*coupleRateTemperature*/ \
0.f, /*coupleRateFuel*/ \
0.f, /*coupleRateBurn*/ \
2.f, /*coupleRateSmoke*/ \
-0.25f, /*minDistance*/ \
0.25f, /*maxDistance*/ \
0, /*nanoVdbDistances*/ \
0, /*nanoVdbDistanceCount*/ \
0, /*nanoVdbDistanceVersion*/ \
0, /*nanoVdbDistanceFirstElement*/ \
0, /*nanoVdbVelocities*/ \
0, /*nanoVdbVelocityCount*/ \
0, /*nanoVdbVelocityVersion*/ \
0, /*nanoVdbVelocityFirstElement*/ \
0, /*nanoVdbDivergences*/ \
0, /*nanoVdbDivergenceCount*/ \
0, /*nanoVdbDivergenceVersion*/ \
0, /*nanoVdbDivergenceFirstElement*/ \
0, /*nanoVdbTemperatures*/ \
0, /*nanoVdbTemperatureCount*/ \
0, /*nanoVdbTemperatureVersion*/ \
0, /*nanoVdbTemperatureFirstElement*/ \
0, /*nanoVdbFuels*/ \
0, /*nanoVdbFuelCount*/ \
0, /*nanoVdbFuelVersion*/ \
0, /*nanoVdbFuelFirstElement*/ \
0, /*nanoVdbBurns*/ \
0, /*nanoVdbBurnCount*/ \
0, /*nanoVdbBurnVersion*/ \
0, /*nanoVdbBurnFirstElement*/ \
0, /*nanoVdbSmokes*/ \
0, /*nanoVdbSmokeCount*/ \
0, /*nanoVdbSmokeVersion*/ \
0, /*nanoVdbSmokeFirstElement*/ \
0, /*nanoVdbCoupleRateVelocities*/ \
0, /*nanoVdbCoupleRateVelocityCount*/ \
0, /*nanoVdbCoupleRateVelocityVersion*/ \
0, /*nanoVdbCoupleRateVelocityFirstElement*/ \
0, /*nanoVdbCoupleRateDivergences*/ \
0, /*nanoVdbCoupleRateDivergenceCount*/ \
0, /*nanoVdbCoupleRateDivergenceVersion*/ \
0, /*nanoVdbCoupleRateDivergenceFirstElement*/ \
0, /*nanoVdbCoupleRateTemperatures*/ \
0, /*nanoVdbCoupleRateTemperatureCount*/ \
0, /*nanoVdbCoupleRateTemperatureVersion*/ \
0, /*nanoVdbCoupleRateTemperatureFirstElement*/ \
0, /*nanoVdbCoupleRateFuels*/ \
0, /*nanoVdbCoupleRateFuelCount*/ \
0, /*nanoVdbCoupleRateFuelVersion*/ \
0, /*nanoVdbCoupleRateFuelFirstElement*/ \
0, /*nanoVdbCoupleRateBurns*/ \
0, /*nanoVdbCoupleRateBurnCount*/ \
0, /*nanoVdbCoupleRateBurnVersion*/ \
0, /*nanoVdbCoupleRateBurnFirstElement*/ \
0, /*nanoVdbCoupleRateSmokes*/ \
0, /*nanoVdbCoupleRateSmokeCount*/ \
0, /*nanoVdbCoupleRateSmokeVersion*/ \
0, /*nanoVdbCoupleRateSmokeFirstElement*/ \
0, /*nanoVdbRgba8s*/ \
0, /*nanoVdbRgba8Count*/ \
0, /*nanoVdbRgba8Version*/ \
0, /*nanoVdbRgba8FirstElement*/ \
NV_FLOW_FALSE, /*applyPostPressure*/ \
NV_FLOW_TRUE, /*allocateActiveLeaves*/ \
}
static const NvFlowEmitterNanoVdbParams NvFlowEmitterNanoVdbParams_default = NvFlowEmitterNanoVdbParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterNanoVdbParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint64, luid, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat4x4, localToWorld, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat4x4, localToWorldVelocity, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, velocityIsWorldSpace, 0, 0)
NV_FLOW_REFLECT_VALUE(int, layer, 0, 0)
NV_FLOW_REFLECT_VALUE(float, allocationScale, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, velocity, 0, 0)
NV_FLOW_REFLECT_VALUE(float, divergence, 0, 0)
NV_FLOW_REFLECT_VALUE(float, temperature, 0, 0)
NV_FLOW_REFLECT_VALUE(float, fuel, 0, 0)
NV_FLOW_REFLECT_VALUE(float, burn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, smoke, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, colorIsSrgb, 0, 0)
NV_FLOW_REFLECT_VALUE(float, velocityScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, divergenceScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, temperatureScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, fuelScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, burnScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, smokeScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateVelocity, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateDivergence, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateTemperature, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateFuel, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateBurn, 0, 0)
NV_FLOW_REFLECT_VALUE(float, coupleRateSmoke, 0, 0)
NV_FLOW_REFLECT_VALUE(float, minDistance, 0, 0)
NV_FLOW_REFLECT_VALUE(float, maxDistance, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowUint, nanoVdbDistances, nanoVdbDistanceCount, nanoVdbDistanceVersion, eNvFlowReflectHint_asset, "asset(nanovdb)")
NV_FLOW_REFLECT_VALUE(NvFlowUint64, nanoVdbDistanceFirstElement, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowUint, nanoVdbVelocities, nanoVdbVelocityCount, nanoVdbVelocityVersion, eNvFlowReflectHint_asset, "asset(nanovdb)")
NV_FLOW_REFLECT_VALUE(NvFlowUint64, nanoVdbVelocityFirstElement, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowUint, nanoVdbDivergences, nanoVdbDivergenceCount, nanoVdbDivergenceVersion, eNvFlowReflectHint_asset, "asset(nanovdb)")
NV_FLOW_REFLECT_VALUE(NvFlowUint64, nanoVdbDivergenceFirstElement, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowUint, nanoVdbTemperatures, nanoVdbTemperatureCount, nanoVdbTemperatureVersion, eNvFlowReflectHint_asset, "asset(nanovdb)")
NV_FLOW_REFLECT_VALUE(NvFlowUint64, nanoVdbTemperatureFirstElement, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowUint, nanoVdbFuels, nanoVdbFuelCount, nanoVdbFuelVersion, eNvFlowReflectHint_asset, "asset(nanovdb)")
NV_FLOW_REFLECT_VALUE(NvFlowUint64, nanoVdbFuelFirstElement, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowUint, nanoVdbBurns, nanoVdbBurnCount, nanoVdbBurnVersion, eNvFlowReflectHint_asset, "asset(nanovdb)")
NV_FLOW_REFLECT_VALUE(NvFlowUint64, nanoVdbBurnFirstElement, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowUint, nanoVdbSmokes, nanoVdbSmokeCount, nanoVdbSmokeVersion, eNvFlowReflectHint_asset, "asset(nanovdb)")
NV_FLOW_REFLECT_VALUE(NvFlowUint64, nanoVdbSmokeFirstElement, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowUint, nanoVdbCoupleRateVelocities, nanoVdbCoupleRateVelocityCount, nanoVdbCoupleRateVelocityVersion, eNvFlowReflectHint_asset, "asset(nanovdb)")
NV_FLOW_REFLECT_VALUE(NvFlowUint64, nanoVdbCoupleRateVelocityFirstElement, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowUint, nanoVdbCoupleRateDivergences, nanoVdbCoupleRateDivergenceCount, nanoVdbCoupleRateDivergenceVersion, eNvFlowReflectHint_asset, "asset(nanovdb)")
NV_FLOW_REFLECT_VALUE(NvFlowUint64, nanoVdbCoupleRateDivergenceFirstElement, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowUint, nanoVdbCoupleRateTemperatures, nanoVdbCoupleRateTemperatureCount, nanoVdbCoupleRateTemperatureVersion, eNvFlowReflectHint_asset, "asset(nanovdb)")
NV_FLOW_REFLECT_VALUE(NvFlowUint64, nanoVdbCoupleRateTemperatureFirstElement, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowUint, nanoVdbCoupleRateFuels, nanoVdbCoupleRateFuelCount, nanoVdbCoupleRateFuelVersion, eNvFlowReflectHint_asset, "asset(nanovdb)")
NV_FLOW_REFLECT_VALUE(NvFlowUint64, nanoVdbCoupleRateFuelFirstElement, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowUint, nanoVdbCoupleRateBurns, nanoVdbCoupleRateBurnCount, nanoVdbCoupleRateBurnVersion, eNvFlowReflectHint_asset, "asset(nanovdb)")
NV_FLOW_REFLECT_VALUE(NvFlowUint64, nanoVdbCoupleRateBurnFirstElement, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowUint, nanoVdbCoupleRateSmokes, nanoVdbCoupleRateSmokeCount, nanoVdbCoupleRateSmokeVersion, eNvFlowReflectHint_asset, "asset(nanovdb)")
NV_FLOW_REFLECT_VALUE(NvFlowUint64, nanoVdbCoupleRateSmokeFirstElement, 0, 0)
NV_FLOW_REFLECT_ARRAY_VERSIONED(NvFlowUint, nanoVdbRgba8s, nanoVdbRgba8Count, nanoVdbRgba8Version, eNvFlowReflectHint_asset, "asset(nanovdb)")
NV_FLOW_REFLECT_VALUE(NvFlowUint64, nanoVdbRgba8FirstElement, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, applyPostPressure, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, allocateActiveLeaves, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowEmitterNanoVdbParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowEmitterNanoVdbPinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
float deltaTime;
const NvFlowEmitterNanoVdbParams*const* velocityParams;
NvFlowUint64 velocityParamCount;
const NvFlowEmitterNanoVdbParams*const* densityParams;
NvFlowUint64 densityParamCount;
NvFlowSparseTexture value;
NvFlowSparseTexture valueTemp;
NvFlowBool32 isPostPressure;
}NvFlowEmitterNanoVdbPinsIn;
typedef struct NvFlowEmitterNanoVdbPinsOut
{
NvFlowSparseTexture value;
}NvFlowEmitterNanoVdbPinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterNanoVdbPinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterNanoVdbParams, velocityParams, velocityParamCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterNanoVdbParams, densityParams, densityParamCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, value, eNvFlowReflectHint_pinEnabledMutable, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, valueTemp, eNvFlowReflectHint_pinEnabledMutable, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, isPostPressure, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterNanoVdbPinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, value, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowEmitterNanoVdb)
/// ********************************* EmitterNanoVdbAllocate ***************************************
typedef struct NvFlowEmitterNanoVdbAllocatePinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
NvFlowSparseParams sparseParams;
float deltaTime;
const NvFlowEmitterNanoVdbParams*const* params;
NvFlowUint64 paramCount;
}NvFlowEmitterNanoVdbAllocatePinsIn;
typedef struct NvFlowEmitterNanoVdbAllocatePinsOut
{
NvFlowInt4* locations;
NvFlowUint64 locationCount;
}NvFlowEmitterNanoVdbAllocatePinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterNanoVdbAllocatePinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseParams, sparseParams, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(float, deltaTime, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEmitterNanoVdbParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowEmitterNanoVdbAllocatePinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_ARRAY(NvFlowInt4, locations, locationCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowEmitterNanoVdbAllocate)
/// ********************************* Ellipsoid Raster ***************************************
typedef struct NvFlowEllipsoidRasterFeedback
{
void* data;
}NvFlowEllipsoidRasterFeedback;
NV_FLOW_REFLECT_STRUCT_OPAQUE_IMPL(NvFlowEllipsoidRasterFeedback)
typedef struct NvFlowEllipsoidRasterParams
{
float scale;
float density;
NvFlowBool32 sdfMode;
const NvFlowFloat4* positions;
NvFlowUint64 positionCount;
const NvFlowFloat3* positionFloat3s;
NvFlowUint64 positionFloat3Count;
const NvFlowFloat4* anisotropyE1s;
NvFlowUint64 anisotropyE1Count;
const NvFlowFloat4* anisotropyE2s;
NvFlowUint64 anisotropyE2Count;
const NvFlowFloat4* anisotropyE3s;
NvFlowUint64 anisotropyE3Count;
NvFlowUint smoothIterations;
float allocationScale;
float allocationOffset;
}NvFlowEllipsoidRasterParams;
#define NvFlowEllipsoidRasterParams_default_init { \
1.f, /*scale*/ \
1.f, /*density*/ \
NV_FLOW_TRUE, /*sdfMode*/ \
0, /*positions*/ \
0u, /*positionsCount*/ \
0, /*positionFloat3s*/ \
0u, /*positionsFloat3Count*/ \
0, /*anisotropyE1s*/ \
0u, /*anisotropyE1Count*/ \
0, /*anisotropyE2s*/ \
0u, /*anisotropyE2Count*/ \
0, /*anisotropyE3s*/ \
0u, /*anisotropyE3Count*/ \
3u, /*smoothIterations*/ \
1.f, /*allocationScale*/ \
0.f /*allocationOffset*/ \
}
static const NvFlowEllipsoidRasterParams NvFlowEllipsoidRasterParams_default = NvFlowEllipsoidRasterParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowEllipsoidRasterParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(float, scale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, density, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, sdfMode, 0, 0)
NV_FLOW_REFLECT_ARRAY(NvFlowFloat4, positions, positionCount, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY(NvFlowFloat3, positionFloat3s, positionFloat3Count, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY(NvFlowFloat4, anisotropyE1s, anisotropyE1Count, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY(NvFlowFloat4, anisotropyE2s, anisotropyE2Count, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_ARRAY(NvFlowFloat4, anisotropyE3s, anisotropyE3Count, eNvFlowReflectHint_asset, "asset(array)")
NV_FLOW_REFLECT_VALUE(NvFlowUint, smoothIterations, 0, 0)
NV_FLOW_REFLECT_VALUE(float, allocationScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, allocationOffset, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowEllipsoidRasterParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowEllipsoidRasterPinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
NvFlowEllipsoidRasterFeedback feedback;
const NvFlowEllipsoidRasterParams** params;
NvFlowUint64 paramCount;
NvFlowSparseTexture layout;
}NvFlowEllipsoidRasterPinsIn;
typedef struct NvFlowEllipsoidRasterPinsOut
{
NvFlowSparseTexture value;
}NvFlowEllipsoidRasterPinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowEllipsoidRasterPinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(NvFlowEllipsoidRasterFeedback, feedback, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEllipsoidRasterParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, layout, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowEllipsoidRasterPinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, value, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowEllipsoidRaster)
typedef struct NvFlowEllipsoidRasterAllocatePinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
NvFlowSparseParams sparseParams;
const NvFlowEllipsoidRasterParams** params;
NvFlowUint64 paramCount;
}NvFlowEllipsoidRasterAllocatePinsIn;
typedef struct NvFlowEllipsoidRasterAllocatePinsOut
{
NvFlowEllipsoidRasterFeedback feedback;
NvFlowInt4* locations;
NvFlowUint64 locationCount;
}NvFlowEllipsoidRasterAllocatePinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowEllipsoidRasterAllocatePinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseParams, sparseParams, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowEllipsoidRasterParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowEllipsoidRasterAllocatePinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowEllipsoidRasterFeedback, feedback, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_ARRAY(NvFlowInt4, locations, locationCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowEllipsoidRasterAllocate)
/// ********************************* Shadow ***************************************
typedef struct NvFlowShadowParams
{
NvFlowBool32 enabled;
NvFlowFloat3 lightDirection;
NvFlowFloat3 lightPosition;
NvFlowBool32 isPointLight;
float attenuation;
float stepSizeScale;
float stepOffsetScale;
float minIntensity;
NvFlowUint numSteps;
NvFlowBool32 coarsePropagate;
}NvFlowShadowParams;
#define NvFlowShadowParams_default_init { \
NV_FLOW_TRUE, /*enabled*/ \
{1.f, 1.f, 1.f}, /*lightDirection*/ \
{0.f, 0.f, 0.f}, /*lightPosition*/ \
NV_FLOW_FALSE, /*isPointLight*/ \
0.045f, /*attenuation*/ \
0.75f, /*stepSizeScale*/ \
1.f, /*stepOffsetScale*/ \
0.125f, /*minIntensity*/ \
16u, /*numSteps*/ \
NV_FLOW_TRUE /*coarsePropagate*/ \
}
static const NvFlowShadowParams NvFlowShadowParams_default = NvFlowShadowParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowShadowParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enabled, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, lightDirection, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, lightPosition, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, isPointLight, 0, 0)
NV_FLOW_REFLECT_VALUE(float, attenuation, 0, 0)
NV_FLOW_REFLECT_VALUE(float, stepSizeScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, stepOffsetScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, minIntensity, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, numSteps, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, coarsePropagate, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowShadowParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowShadowPinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
const NvFlowShadowParams** params;
NvFlowUint64 paramCount;
NvFlowTextureTransient* colormap;
NvFlowSparseTexture density;
NvFlowSparseTexture coarseDensity;
}NvFlowShadowPinsIn;
typedef struct NvFlowShadowPinsOut
{
NvFlowSparseTexture densityShadow;
}NvFlowShadowPinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowShadowPinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowShadowParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER(NvFlowTextureTransient, colormap, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, density, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, coarseDensity, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowShadowPinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, densityShadow, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowShadow)
/// ********************************* DebugVolume ***************************************
typedef struct NvFlowDebugVolumeParams
{
NvFlowBool32 enableSpeedAsTemperature;
NvFlowBool32 enableVelocityAsDensity;
NvFlowFloat3 velocityScale;
}NvFlowDebugVolumeParams;
#define NvFlowDebugVolumeParams_default_init { \
NV_FLOW_FALSE, /*enableSpeedAsTemperature*/ \
NV_FLOW_FALSE, /*enableVelocityAsDensity*/ \
{0.01f, 0.01f, 0.01f} /*velocityScale*/ \
}
static const NvFlowDebugVolumeParams NvFlowDebugVolumeParams_default = NvFlowDebugVolumeParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowDebugVolumeParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enableSpeedAsTemperature, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enableVelocityAsDensity, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, velocityScale, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowDebugVolumeParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowDebugVolumePinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
const NvFlowDebugVolumeParams** params;
NvFlowUint64 paramCount;
NvFlowSparseTexture velocity;
NvFlowSparseTexture densityShadow;
}NvFlowDebugVolumePinsIn;
typedef struct NvFlowDebugVolumePinsOut
{
NvFlowSparseTexture densityShadow;
}NvFlowDebugVolumePinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowDebugVolumePinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowDebugVolumeParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, velocity, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, densityShadow, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowDebugVolumePinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, densityShadow, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowDebugVolume)
/// ********************************* RayMarch ***************************************
typedef struct NvFlowRayMarchCloudParams
{
NvFlowBool32 enableCloudMode;
NvFlowFloat3 sunDirection;
NvFlowFloat3 ambientColor;
float ambientMultiplier;
float densityMultiplier;
NvFlowFloat3 volumeBaseColor;
float volumeColorMultiplier;
float shadowStepMultiplier;
int numShadowSteps;
NvFlowFloat3 attenuationMultiplier;
}NvFlowRayMarchCloudParams;
#define NvFlowRayMarchCloudParams_default_init { \
NV_FLOW_FALSE, /*enableCloudMode*/ \
{1.f, 1.f, 1.f}, /*sunDirection*/ \
{0.4f, 0.55f, 0.9f}, /*ambientColor*/ \
1.0f, /*ambientMultiplier*/ \
0.5f, /*densityMultiplier*/ \
{1.1f, 1.f, 0.95f}, /*volumeBaseColor*/ \
1.0f, /*volumeColorMultiplier*/ \
1.0f, /*shadowStepMultiplier*/ \
10u, /*numShadowSteps*/ \
{1.f, 1.f, 1.f} /*attenuationMultiplier*/ \
}
static const NvFlowRayMarchCloudParams NvFlowRayMarchCloudParams_default = NvFlowRayMarchCloudParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowRayMarchCloudParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enableCloudMode, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, sunDirection, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, ambientColor, 0, 0)
NV_FLOW_REFLECT_VALUE(float, ambientMultiplier, 0, 0)
NV_FLOW_REFLECT_VALUE(float, densityMultiplier, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, volumeBaseColor, 0, 0)
NV_FLOW_REFLECT_VALUE(float, volumeColorMultiplier, 0, 0)
NV_FLOW_REFLECT_VALUE(float, shadowStepMultiplier, 0, 0)
NV_FLOW_REFLECT_VALUE(int, numShadowSteps, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, attenuationMultiplier, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowRayMarchCloudParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowRayMarchParams
{
NvFlowBool32 enableBlockWireframe;
NvFlowBool32 enableRawMode;
float colorScale;
float attenuation;
float stepSizeScale;
float shadowFactor;
NvFlowRayMarchCloudParams cloud;
}NvFlowRayMarchParams;
#define NvFlowRayMarchParams_default_init { \
NV_FLOW_FALSE, /*enableBlockWireframe*/ \
NV_FLOW_FALSE, /*enableRawMode*/ \
1.f, /*colorScale*/ \
0.05f, /*attenuation*/ \
0.75f, /*stepSizeScale*/ \
1.f, /*shadowFactor*/ \
NvFlowRayMarchCloudParams_default_init /*cloud*/ \
}
static const NvFlowRayMarchParams NvFlowRayMarchParams_default = NvFlowRayMarchParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowRayMarchParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enableBlockWireframe, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enableRawMode, 0, 0)
NV_FLOW_REFLECT_VALUE(float, colorScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, attenuation, 0, 0)
NV_FLOW_REFLECT_VALUE(float, stepSizeScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, shadowFactor, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowRayMarchCloudParams, cloud, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowRayMarchParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowRayMarchIsosurfaceParams
{
NvFlowBool32 enableBlockWireframe;
float stepSizeScale;
float densityThreshold;
NvFlowBool32 refractionMode;
NvFlowBool32 visualizeNormals;
float fluidIoR;
NvFlowFloat3 fluidColor;
float fluidAbsorptionCoefficient;
NvFlowFloat3 fluidSpecularReflectance;
NvFlowFloat3 fluidDiffuseReflectance;
NvFlowFloat3 fluidRadiance;
}NvFlowRayMarchIsosurfaceParams;
#define NvFlowRayMarchIsosurfaceParams_default_init { \
NV_FLOW_FALSE, /*enableBlockWireframe*/ \
0.75f, /*stepSizeScale*/ \
0.5f, /*densityThreshold*/ \
NV_FLOW_FALSE, /*refractionMode*/ \
NV_FLOW_FALSE, /*visualizeNormals*/ \
1.333f, /*fluidIoR*/ \
{0.9f, 0.9f, 1.f}, /*fluidColor*/ \
0.0035f, /*fluidAbsorptionCoefficient*/ \
{0.1f, 0.1f, 0.1f}, /*fluidSpecularReflectance*/ \
{0.1f, 0.1f, 0.1f}, /*fluidDiffuseReflectance*/ \
{0.f, 0.f, 0.f} /*fluidRadiance*/ \
}
static const NvFlowRayMarchIsosurfaceParams NvFlowRayMarchIsosurfaceParams_default = NvFlowRayMarchIsosurfaceParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowRayMarchIsosurfaceParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enableBlockWireframe, 0, 0)
NV_FLOW_REFLECT_VALUE(float, stepSizeScale, 0, 0)
NV_FLOW_REFLECT_VALUE(float, densityThreshold, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, refractionMode, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, visualizeNormals, 0, 0)
NV_FLOW_REFLECT_VALUE(float, fluidIoR, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, fluidColor, 0, 0)
NV_FLOW_REFLECT_VALUE(float, fluidAbsorptionCoefficient, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, fluidSpecularReflectance, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, fluidDiffuseReflectance, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowFloat3, fluidRadiance, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowRayMarchIsosurfaceParams_default)
#undef NV_FLOW_REFLECT_TYPE
#define NvFlowRayMarchColormapParams_default_pointCount_init 6u
static const NvFlowUint64 NvFlowRayMarchColormapParams_default_pointCount = NvFlowRayMarchColormapParams_default_pointCount_init;
#define NvFlowRayMarchColormapParams_default_xPoints_init { \
0.000000f, \
0.050000f, \
0.15000f, \
0.600000f, \
0.850000f, \
1.000000f \
}
static const float NvFlowRayMarchColormapParams_default_xPoints[NvFlowRayMarchColormapParams_default_pointCount_init] = NvFlowRayMarchColormapParams_default_xPoints_init;
#define NvFlowRayMarchColormapParams_default_colorScalePoints_init { \
1.000000f, \
1.000000f, \
1.000000f, \
1.000000f, \
1.000000f, \
1.000000f \
}
static const float NvFlowRayMarchColormapParams_default_colorScalePoints[NvFlowRayMarchColormapParams_default_pointCount_init] = NvFlowRayMarchColormapParams_default_colorScalePoints_init;
#define NvFlowRayMarchColormapParams_default_rgbaPoints_smoke_init { \
{ 0.9f, 0.9f, 0.9f, 0.004902f }, \
{ 0.9f, 0.9f, 0.9f, 0.904902f }, \
{ 0.9f, 0.9f, 0.9f, 0.904902f }, \
{ 0.9f, 0.9f, 0.9f, 0.904902f }, \
{ 0.9f, 0.9f, 0.9f, 0.904902f }, \
{ 0.9f, 0.9f, 0.9f, 0.904902f }, \
}
static const NvFlowFloat4 NvFlowRayMarchColormapParams_default_rgbaPoints_smoke[NvFlowRayMarchColormapParams_default_pointCount_init] = NvFlowRayMarchColormapParams_default_rgbaPoints_smoke_init;
#define NvFlowRayMarchColormapParams_default_rgbaPoints_fire_init { \
{ 0.015400f, 0.017700f, 0.015400f, 0.004902f }, \
{ 0.035750f, 0.035750f, 0.035750f, 0.504902f }, \
{ 0.035750f, 0.035750f, 0.035750f, 0.504902f }, \
{ 1.f, 0.1594125f, 0.0135315f, 0.800000f }, \
{ 13.534992f, 2.986956f, 0.125991f, 0.800000f }, \
{ 78.08f, 39.04f, 6.1f, 0.700000f }, \
}
static const NvFlowFloat4 NvFlowRayMarchColormapParams_default_rgbaPoints_fire[NvFlowRayMarchColormapParams_default_pointCount_init] = NvFlowRayMarchColormapParams_default_rgbaPoints_fire_init;
typedef struct NvFlowRayMarchColormapParams
{
NvFlowUint resolution;
const float* xPoints;
NvFlowUint64 xPointCount;
const NvFlowFloat4* rgbaPoints;
NvFlowUint64 rgbaPointCount;
const float* colorScalePoints;
NvFlowUint64 colorScalePointCount;
float colorScale;
}NvFlowRayMarchColormapParams;
#define NvFlowRayMarchColormapParams_default_init { \
32u, /*resolution*/ \
NvFlowRayMarchColormapParams_default_xPoints, /*xPoints*/ \
NvFlowRayMarchColormapParams_default_pointCount_init, /*xPointCount*/ \
NvFlowRayMarchColormapParams_default_rgbaPoints_smoke, /*rgbaPoints*/ \
NvFlowRayMarchColormapParams_default_pointCount_init, /*rgbaPointCount*/ \
NvFlowRayMarchColormapParams_default_colorScalePoints, /*colorScalePoints*/ \
NvFlowRayMarchColormapParams_default_pointCount_init, /*colorScaleCount*/ \
2.5f /*colorScale*/ \
}
static const NvFlowRayMarchColormapParams NvFlowRayMarchColormapParams_default = NvFlowRayMarchColormapParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowRayMarchColormapParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint, resolution, 0, 0)
NV_FLOW_REFLECT_ARRAY(float, xPoints, xPointCount, 0, 0)
NV_FLOW_REFLECT_ARRAY(NvFlowFloat4, rgbaPoints, rgbaPointCount, 0, 0)
NV_FLOW_REFLECT_ARRAY(float, colorScalePoints, colorScalePointCount, 0, 0)
NV_FLOW_REFLECT_VALUE(float, colorScale, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowRayMarchColormapParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowRayMarchTargetTexture
{
const NvFlowFloat4x4* view;
const NvFlowFloat4x4* projection;
const NvFlowFloat4x4* projectionJittered;
NvFlowUint textureWidth;
NvFlowUint textureHeight;
NvFlowUint sceneDepthWidth;
NvFlowUint sceneDepthHeight;
NvFlowTextureTransient* sceneDepthIn;
NvFlowFormat sceneColorFormat;
NvFlowTextureTransient* sceneColorIn;
NvFlowTextureTransient** pSceneColorOut;
}NvFlowRayMarchTargetTexture;
NV_FLOW_REFLECT_STRUCT_OPAQUE_IMPL(NvFlowRayMarchTargetTexture)
typedef struct NvFlowRayMarchPinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
const NvFlowRayMarchParams** params;
NvFlowUint64 paramCount;
NvFlowSparseTexture velocity;
NvFlowSparseTexture density;
NvFlowTextureTransient* colormap;
const NvFlowRayMarchTargetTexture* target;
float compositeColorScale;
}NvFlowRayMarchPinsIn;
typedef struct NvFlowRayMarchPinsOut
{
NvFlowUint unused;
}NvFlowRayMarchPinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowRayMarchPinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowRayMarchParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, velocity, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, density, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER(NvFlowTextureTransient, colormap, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER(NvFlowRayMarchTargetTexture, target, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(float, compositeColorScale, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowRayMarchPinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint, unused, 0, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowRayMarch)
typedef struct NvFlowRayMarchUpdateColormapPinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
const NvFlowRayMarchColormapParams** params;
NvFlowUint64 paramCount;
}NvFlowRayMarchUpdateColormapPinsIn;
typedef struct NvFlowRayMarchUpdateColormapPinsOut
{
NvFlowTextureTransient* colormap;
}NvFlowRayMarchUpdateColormapPinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowRayMarchUpdateColormapPinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowRayMarchColormapParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowRayMarchUpdateColormapPinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowTextureTransient, colormap, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowRayMarchUpdateColormap)
typedef struct NvFlowRayMarchIsosurfacePinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
const NvFlowRayMarchIsosurfaceParams** params;
NvFlowUint64 paramCount;
NvFlowSparseTexture density;
const NvFlowRayMarchTargetTexture* target;
float compositeColorScale;
}NvFlowRayMarchIsosurfacePinsIn;
typedef struct NvFlowRayMarchIsosurfacePinsOut
{
NvFlowUint unused;
}NvFlowRayMarchIsosurfacePinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowRayMarchIsosurfacePinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER_ARRAY(NvFlowRayMarchIsosurfaceParams, params, paramCount, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseTexture, density, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_POINTER(NvFlowRayMarchTargetTexture, target, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(float, compositeColorScale, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowRayMarchIsosurfacePinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint, unused, 0, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowRayMarchIsosurface)
typedef struct NvFlowRayMarchCopyTexturePinsIn
{
NvFlowContextInterface* contextInterface;
NvFlowContext* context;
NvFlowTextureTransient* texture;
NvFlowUint width;
NvFlowUint height;
NvFlowFormat format;
}NvFlowRayMarchCopyTexturePinsIn;
typedef struct NvFlowRayMarchCopyTexturePinsOut
{
NvFlowTextureTransient* texture;
}NvFlowRayMarchCopyTexturePinsOut;
#define NV_FLOW_REFLECT_TYPE NvFlowRayMarchCopyTexturePinsIn
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowContextInterface, contextInterface, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowContext, context, eNvFlowReflectHint_pinEnabledGlobal, 0)
NV_FLOW_REFLECT_POINTER(NvFlowTextureTransient, texture, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, width, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, height, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_ENUM(format, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
#define NV_FLOW_REFLECT_TYPE NvFlowRayMarchCopyTexturePinsOut
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_POINTER(NvFlowTextureTransient, texture, eNvFlowReflectHint_pinEnabled, 0)
NV_FLOW_REFLECT_END(0)
#undef NV_FLOW_REFLECT_TYPE
NV_FLOW_OP_TYPED(NvFlowRayMarchCopyTexture)
/// ********************************* NvFlowExtOpList ***************************************
typedef struct NvFlowExtOpList
{
NV_FLOW_REFLECT_INTERFACE();
NvFlowOpInterface* (NV_FLOW_ABI* pEmitterSphere)();
NvFlowOpInterface* (NV_FLOW_ABI* pEmitterSphereAllocate)();
NvFlowOpInterface* (NV_FLOW_ABI* pEmitterBox)();
NvFlowOpInterface* (NV_FLOW_ABI* pEmitterBoxAllocate)();
NvFlowOpInterface* (NV_FLOW_ABI* pEmitterPoint)();
NvFlowOpInterface* (NV_FLOW_ABI* pEmitterPointAllocate)();
NvFlowOpInterface* (NV_FLOW_ABI* pEmitterMesh)();
NvFlowOpInterface* (NV_FLOW_ABI* pEmitterMeshAllocate)();
NvFlowOpInterface* (NV_FLOW_ABI* pEmitterTexture)();
NvFlowOpInterface* (NV_FLOW_ABI* pEmitterTextureAllocate)();
NvFlowOpInterface* (NV_FLOW_ABI* pEmitterNanoVdb)();
NvFlowOpInterface* (NV_FLOW_ABI* pEmitterNanoVdbAllocate)();
NvFlowOpInterface* (NV_FLOW_ABI* pEllipsoidRaster)();
NvFlowOpInterface* (NV_FLOW_ABI* pEllipsoidRasterAllocate)();
NvFlowOpInterface* (NV_FLOW_ABI* pShadow)();
NvFlowOpInterface* (NV_FLOW_ABI* pDebugVolume)();
NvFlowOpInterface* (NV_FLOW_ABI* pRayMarch)();
NvFlowOpInterface* (NV_FLOW_ABI* pRayMarchUpdateColormap)();
NvFlowOpInterface* (NV_FLOW_ABI* pRayMarchIsosurface)();
NvFlowOpInterface* (NV_FLOW_ABI* pRayMarchCopyTexture)();
}NvFlowExtOpList;
#define NV_FLOW_REFLECT_TYPE NvFlowExtOpList
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_FUNCTION_POINTER(pEmitterSphere, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pEmitterSphereAllocate, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pEmitterBox, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pEmitterBoxAllocate, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pEmitterPoint, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pEmitterPointAllocate, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pEmitterTexture, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pEmitterTextureAllocate, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pEmitterNanoVdb, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pEmitterNanoVdbAllocate, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pEllipsoidRaster, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pEllipsoidRasterAllocate, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pShadow, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pDebugVolume, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pRayMarch, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pRayMarchUpdateColormap, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pRayMarchIsosurface, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(pRayMarchCopyTexture, 0, 0)
NV_FLOW_REFLECT_END(0)
NV_FLOW_REFLECT_INTERFACE_IMPL()
#undef NV_FLOW_REFLECT_TYPE
typedef NvFlowExtOpList* (NV_FLOW_ABI* PFN_NvFlowGetExtOpList)();
NV_FLOW_API NvFlowExtOpList* NvFlowGetExtOpList();
/// ********************************* Grid ***************************************
struct NvFlowGrid;
typedef struct NvFlowGrid NvFlowGrid;
typedef struct NvFlowGridDesc
{
NvFlowUint maxLocations;
NvFlowUint maxLocationsIsosurface;
}NvFlowGridDesc;
#define NvFlowGridDesc_default_init { \
4096u, /*maxLocations*/ \
4096u /*maxLocationsIsosurface*/ \
}
static const NvFlowGridDesc NvFlowGridDesc_default = NvFlowGridDesc_default_init;
NV_FLOW_REFLECT_TYPE_ALIAS(NvFlowEmitterSphereParams, NvFlowGridEmitterSphereParams)
NV_FLOW_REFLECT_TYPE_ALIAS(NvFlowEmitterBoxParams, NvFlowGridEmitterBoxParams)
NV_FLOW_REFLECT_TYPE_ALIAS(NvFlowEmitterPointParams, NvFlowGridEmitterPointParams)
NV_FLOW_REFLECT_TYPE_ALIAS(NvFlowEmitterMeshParams, NvFlowGridEmitterMeshParams)
NV_FLOW_REFLECT_TYPE_ALIAS(NvFlowEmitterTextureParams, NvFlowGridEmitterTextureParams)
NV_FLOW_REFLECT_TYPE_ALIAS(NvFlowEmitterNanoVdbParams, NvFlowGridEmitterNanoVdbParams)
typedef struct NvFlowGridSimulateLayerParams
{
NvFlowUint64 luid;
int layer;
float densityCellSize;
NvFlowBool32 enableSmallBlocks;
NvFlowBool32 enableLowPrecisionVelocity;
NvFlowBool32 enableLowPrecisionDensity;
NvFlowBool32 forceClear;
NvFlowBool32 forceDisableEmitters;
NvFlowBool32 forceDisableCoreSimulation;
NvFlowBool32 simulateWhenPaused;
NvFlowUint blockMinLifetime;
float stepsPerSecond;
float timeScale;
NvFlowUint maxStepsPerSimulate;
NvFlowBool32 enableVariableTimeStep;
NvFlowBool32 interpolateTimeSteps;
NvFlowUint velocitySubSteps;
NvFlowAdvectionCombustionParams advection;
NvFlowVorticityParams vorticity;
NvFlowPressureParams pressure;
NvFlowSummaryAllocateParams summaryAllocate;
NvFlowSparseNanoVdbExportParams nanoVdbExport;
}NvFlowGridSimulateLayerParams;
#define NvFlowGridSimulateLayerParams_default_init { \
0llu, /*luid*/ \
0, /*layer*/ \
0.5f, /*densityCellSize*/ \
NV_FLOW_FALSE, /*enableSmallBlocks*/ \
NV_FLOW_FALSE, /*enableLowPrecisionVelocity*/ \
NV_FLOW_FALSE, /*enableLowPrecisionDensity*/ \
NV_FLOW_FALSE, /*forceClear*/ \
NV_FLOW_FALSE, /*forceDisableEmitters*/ \
NV_FLOW_FALSE, /*forceDisableCoreSimulation*/ \
NV_FLOW_FALSE, /*simulateWhenPaused*/ \
4u, /*blockMinLifetime*/ \
60.f, /*stepsPerSecond*/ \
1.f, /*timeScale*/ \
1u, /*maxStepsPerSimulate*/ \
NV_FLOW_FALSE, /*enableVariableTimeStep*/ \
NV_FLOW_FALSE, /*interpolateTimeSteps*/ \
1u, /*velocitySubSteps*/ \
NvFlowAdvectionCombustionParams_default_init, /*advection*/ \
NvFlowVorticityParams_default_init, /*vorticity*/ \
NvFlowPressureParams_default_init, /*pressure*/ \
NvFlowSummaryAllocateParams_default_init, /*summaryAllocate*/ \
NvFlowSparseNanoVdbExportParams_default_init /*nanoVdbExport*/ \
}
static const NvFlowGridSimulateLayerParams NvFlowGridSimulateLayerParams_default = NvFlowGridSimulateLayerParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowGridSimulateLayerParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint64, luid, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(int, layer, 0, 0)
NV_FLOW_REFLECT_VALUE(float, densityCellSize, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enableSmallBlocks, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enableLowPrecisionVelocity, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enableLowPrecisionDensity, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, forceClear, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, forceDisableEmitters, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, forceDisableCoreSimulation, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, simulateWhenPaused, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, blockMinLifetime, 0, 0)
NV_FLOW_REFLECT_VALUE(float, stepsPerSecond, 0, 0)
NV_FLOW_REFLECT_VALUE(float, timeScale, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, maxStepsPerSimulate, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, enableVariableTimeStep, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowBool32, interpolateTimeSteps, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowUint, velocitySubSteps, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowAdvectionCombustionParams, advection, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowVorticityParams, vorticity, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowPressureParams, pressure, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSummaryAllocateParams, summaryAllocate, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowSparseNanoVdbExportParams, nanoVdbExport, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowGridSimulateLayerParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowGridOffscreenLayerParams
{
NvFlowUint64 luid;
int layer;
NvFlowShadowParams shadow;
NvFlowRayMarchColormapParams colormap;
NvFlowDebugVolumeParams debugVolume;
}NvFlowGridOffscreenLayerParams;
#define NvFlowGridOffscreenLayerParams_default_init { \
0llu, /*luid*/ \
0, /*layer*/ \
NvFlowShadowParams_default_init, /*shadow*/ \
NvFlowRayMarchColormapParams_default_init, /*colormap*/ \
NvFlowDebugVolumeParams_default_init /*debugVolume*/ \
}
static const NvFlowGridOffscreenLayerParams NvFlowGridOffscreenLayerParams_default = NvFlowGridOffscreenLayerParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowGridOffscreenLayerParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint64, luid, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(int, layer, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowShadowParams, shadow, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowRayMarchColormapParams, colormap, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowDebugVolumeParams, debugVolume, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowGridOffscreenLayerParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowGridRenderLayerParams
{
NvFlowUint64 luid;
int layer;
NvFlowRayMarchParams rayMarch;
}NvFlowGridRenderLayerParams;
#define NvFlowGridRenderLayerParams_default_init { \
0llu, /*luid*/ \
0, /*layer*/ \
NvFlowRayMarchParams_default_init /*rayMarch*/ \
}
static const NvFlowGridRenderLayerParams NvFlowGridRenderLayerParams_default = NvFlowGridRenderLayerParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowGridRenderLayerParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint64, luid, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(int, layer, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowRayMarchParams, rayMarch, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowGridRenderLayerParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowGridIsosurfaceLayerParams
{
NvFlowUint64 luid;
int layer;
float densityCellSize;
NvFlowEllipsoidRasterParams ellipsoidRaster;
NvFlowRayMarchIsosurfaceParams rayMarchIsosurface;
}NvFlowGridIsosurfaceLayerParams;
#define NvFlowGridIsosurfaceLayerParams_default_init { \
0llu, /*luid*/ \
0, /*layer*/ \
2.f, /*densityCellSize*/ \
NvFlowEllipsoidRasterParams_default_init, /*ellipsoidRaster*/ \
NvFlowRayMarchIsosurfaceParams_default_init /*rayMarchIsosurface*/ \
}
static const NvFlowGridIsosurfaceLayerParams NvFlowGridIsosurfaceLayerParams_default = NvFlowGridIsosurfaceLayerParams_default_init;
#define NV_FLOW_REFLECT_TYPE NvFlowGridIsosurfaceLayerParams
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_VALUE(NvFlowUint64, luid, eNvFlowReflectHint_transientNoEdit, 0)
NV_FLOW_REFLECT_VALUE(int, layer, 0, 0)
NV_FLOW_REFLECT_VALUE(float, densityCellSize, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowEllipsoidRasterParams, ellipsoidRaster, 0, 0)
NV_FLOW_REFLECT_VALUE(NvFlowRayMarchIsosurfaceParams, rayMarchIsosurface, 0, 0)
NV_FLOW_REFLECT_END(&NvFlowGridIsosurfaceLayerParams_default)
#undef NV_FLOW_REFLECT_TYPE
typedef struct NvFlowGridParamsDescSnapshot
{
NvFlowDatabaseSnapshot snapshot;
double absoluteSimTime;
float deltaTime;
NvFlowBool32 globalForceClear;
const NvFlowUint8* userdata;
NvFlowUint64 userdataSizeInBytes;
}NvFlowGridParamsDescSnapshot;
typedef struct NvFlowGridParamsDesc
{
NvFlowGridParamsDescSnapshot* snapshots;
NvFlowUint64 snapshotCount;
}NvFlowGridParamsDesc;
typedef NvFlowSparseNanoVdbExportPinsOut NvFlowGridRenderDataNanoVdb;
typedef struct NvFlowGridRenderData
{
NvFlowBufferTransient* sparseBuffer;
NvFlowTextureTransient* densityTexture;
NvFlowTextureTransient* velocityTexture;
NvFlowTextureTransient* colormap;
NvFlowSparseParams sparseParams;
NvFlowGridRenderDataNanoVdb nanoVdb;
}NvFlowGridRenderData;
typedef struct NvFlowGridIsosurfaceData
{
NvFlowBufferTransient* sparseBuffer;
NvFlowTextureTransient* densityTexture;
NvFlowSparseParams sparseParams;
}NvFlowGridIsosurfaceData;
typedef struct NvFlowGridInterface
{
NV_FLOW_REFLECT_INTERFACE();
NvFlowGrid*(NV_FLOW_ABI* createGrid)(
NvFlowContextInterface* contextInterface,
NvFlowContext* context,
NvFlowOpList* opList,
NvFlowExtOpList* extOpList,
const NvFlowGridDesc* desc
);
void(NV_FLOW_ABI* destroyGrid)(
NvFlowContext* context,
NvFlowGrid* grid
);
void(NV_FLOW_ABI* resetGrid)(
NvFlowContext* context,
NvFlowGrid* grid,
const NvFlowGridDesc* desc
);
void(NV_FLOW_ABI* simulate)(
NvFlowContext* context,
NvFlowGrid* grid,
const NvFlowGridParamsDesc* params,
NvFlowBool32 globalForceClear
);
void(NV_FLOW_ABI* offscreen)(
NvFlowContext* context,
NvFlowGrid* grid,
const NvFlowGridParamsDesc* params
);
void(NV_FLOW_ABI* getRenderData)(
NvFlowContext* context,
NvFlowGrid* grid,
NvFlowGridRenderData* renderData
);
void(NV_FLOW_ABI* render)(
NvFlowContext* context,
NvFlowGrid* grid,
const NvFlowGridParamsDesc* params,
const NvFlowFloat4x4* view,
const NvFlowFloat4x4* projection,
const NvFlowFloat4x4* projectionJittered,
NvFlowUint width,
NvFlowUint height,
NvFlowUint sceneDepthWidth,
NvFlowUint sceneDepthHeight,
float compositeColorScale,
NvFlowTextureTransient* sceneDepthIn,
NvFlowFormat sceneColorFormat,
NvFlowTextureTransient* sceneColorIn,
NvFlowTextureTransient** pSceneColorOut
);
void(NV_FLOW_ABI* updateIsosurface)(
NvFlowContext* context,
NvFlowGrid* grid,
const NvFlowGridParamsDesc* params
);
void(NV_FLOW_ABI* getIsosurfaceData)(
NvFlowContext* context,
NvFlowGrid* grid,
NvFlowGridIsosurfaceData* isosurfaceData
);
void(NV_FLOW_ABI* renderIsosurface)(
NvFlowContext* context,
NvFlowGrid* grid,
const NvFlowGridParamsDesc* params,
const NvFlowFloat4x4* view,
const NvFlowFloat4x4* projection,
const NvFlowFloat4x4* projectionJittered,
NvFlowUint width,
NvFlowUint height,
NvFlowUint sceneDepthWidth,
NvFlowUint sceneDepthHeight,
float compositeColorScale,
NvFlowTextureTransient* sceneDepthIn,
NvFlowFormat sceneColorFormat,
NvFlowTextureTransient* sceneColorIn,
NvFlowTextureTransient** pSceneColorOut
);
void(NV_FLOW_ABI* copyTexture)(
NvFlowContext* context,
NvFlowGrid* grid,
NvFlowUint width,
NvFlowUint height,
NvFlowFormat sceneColorFormat,
NvFlowTextureTransient* sceneColorIn,
NvFlowTextureTransient** pSceneColorOut
);
NvFlowUint(NV_FLOW_ABI* getActiveBlockCount)(NvFlowGrid* grid);
NvFlowUint(NV_FLOW_ABI* getActiveBlockCountIsosurface)(NvFlowGrid* grid);
void(NV_FLOW_ABI* setResourceMinLifetime)(NvFlowContext* context, NvFlowGrid* grid, NvFlowUint64 minLifetime);
}NvFlowGridInterface;
#define NV_FLOW_REFLECT_TYPE NvFlowGridInterface
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_FUNCTION_POINTER(createGrid, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroyGrid, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(resetGrid, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(simulate, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(offscreen, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getRenderData, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(render, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(updateIsosurface, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getIsosurfaceData, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(renderIsosurface, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(copyTexture, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getActiveBlockCount, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getActiveBlockCountIsosurface, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(setResourceMinLifetime, 0, 0)
NV_FLOW_REFLECT_END(0)
NV_FLOW_REFLECT_INTERFACE_IMPL()
#undef NV_FLOW_REFLECT_TYPE
typedef NvFlowGridInterface* (NV_FLOW_ABI* PFN_NvFlowGetGridInterface)();
NV_FLOW_API NvFlowGridInterface* NvFlowGetGridInterface();
NV_FLOW_API NvFlowGridInterface* NvFlowGetGridInterfaceNoOpt();
/// ********************************* Grid Params ***************************************
struct NvFlowGridParams;
typedef struct NvFlowGridParams NvFlowGridParams;
struct NvFlowGridParamsSnapshot;
typedef struct NvFlowGridParamsSnapshot NvFlowGridParamsSnapshot;
struct NvFlowGridParamsNamed;
typedef struct NvFlowGridParamsNamed NvFlowGridParamsNamed;
typedef struct NvFlowGridParamsInterface
{
NV_FLOW_REFLECT_INTERFACE();
NvFlowGridParams*(NV_FLOW_ABI* createGridParams)();
void(NV_FLOW_ABI* destroyGridParams)(NvFlowGridParams* gridParams);
void(NV_FLOW_ABI* enumerateParamTypes)(
NvFlowGridParams* gridParams,
const char** pTypenames,
const char** pDisplayTypenames,
const NvFlowReflectDataType** pDataTypes,
NvFlowUint64* pCount
);
void(NV_FLOW_ABI* getVersion)(
NvFlowGridParams* gridParams,
NvFlowUint64* pStagingVersion,
NvFlowUint64* pMinActiveVersion
);
void(NV_FLOW_ABI* commitParams)(
NvFlowGridParams* gridParams,
const NvFlowGridParamsDescSnapshot* snapshot
);
NvFlowBool32(NV_FLOW_ABI* resetParams)(NvFlowGridParams* gridParams);
NvFlowGridParamsSnapshot*(NV_FLOW_ABI* getParamsSnapshot)(
NvFlowGridParams* gridParams,
double absoluteSimTime,
NvFlowUint64 pullId
);
NvFlowBool32(NV_FLOW_ABI* mapParamsDesc)(
NvFlowGridParams* gridParams,
NvFlowGridParamsSnapshot* snapshot,
NvFlowGridParamsDesc* pParamsDesc
);
void(NV_FLOW_ABI* unmapParamsDesc)(
NvFlowGridParams* gridParams,
NvFlowGridParamsSnapshot* snapshot
);
NvFlowGridParamsNamed*(NV_FLOW_ABI* createGridParamsNamed)(const char* name);
int(NV_FLOW_ABI* destroyGridParamsNamed)(NvFlowGridParamsNamed* gridParamsNamed);
NvFlowGridParams*(NV_FLOW_ABI* mapGridParamsNamed)(NvFlowGridParamsNamed* gridParamsNamed);
}NvFlowGridParamsInterface;
#define NV_FLOW_REFLECT_TYPE NvFlowGridParamsInterface
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_FUNCTION_POINTER(createGridParams, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroyGridParams, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(enumerateParamTypes, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getVersion, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(commitParams, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(resetParams, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getParamsSnapshot, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(mapParamsDesc, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(unmapParamsDesc, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(createGridParamsNamed, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroyGridParamsNamed, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(mapGridParamsNamed, 0, 0)
NV_FLOW_REFLECT_END(0)
NV_FLOW_REFLECT_INTERFACE_IMPL()
#undef NV_FLOW_REFLECT_TYPE
typedef NvFlowGridParamsInterface* (NV_FLOW_ABI* PFN_NvFlowGetGridParamsInterface)();
NV_FLOW_API NvFlowGridParamsInterface* NvFlowGetGridParamsInterface();
/// ********************************* Thread Pool ***************************************
struct NvFlowThreadPool;
typedef struct NvFlowThreadPool NvFlowThreadPool;
typedef void(*NvFlowThreadPoolTask_t)(NvFlowUint taskIdx, NvFlowUint threadIdx, void* sharedMem, void* userdata);
typedef struct NvFlowThreadPoolInterface
{
NV_FLOW_REFLECT_INTERFACE();
NvFlowUint(NV_FLOW_ABI* getDefaultThreadCount)();
NvFlowThreadPool*(NV_FLOW_ABI* create)(NvFlowUint threadCount, NvFlowUint64 sharedMemorySizeInBytes);
void(NV_FLOW_ABI* destroy)(NvFlowThreadPool* pool);
NvFlowUint(NV_FLOW_ABI* getThreadCount)(NvFlowThreadPool* pool);
void(NV_FLOW_ABI* execute)(NvFlowThreadPool* pool, NvFlowUint taskCount, NvFlowUint taskGranularity, NvFlowThreadPoolTask_t task, void* userdata);
}NvFlowThreadPoolInterface;
#define NV_FLOW_REFLECT_TYPE NvFlowThreadPoolInterface
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_FUNCTION_POINTER(getDefaultThreadCount, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(create, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroy, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getThreadCount, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(execute, 0, 0)
NV_FLOW_REFLECT_END(0)
NV_FLOW_REFLECT_INTERFACE_IMPL()
#undef NV_FLOW_REFLECT_TYPE
typedef NvFlowThreadPoolInterface* (NV_FLOW_ABI* PFN_NvFlowThreadPoolInterface)();
NV_FLOW_API NvFlowThreadPoolInterface* NvFlowGetThreadPoolInterface();
/// ********************************* Optimization Layer ***************************************
struct NvFlowContextOpt;
typedef struct NvFlowContextOpt NvFlowContextOpt;
typedef struct NvFlowContextOptInterface
{
NV_FLOW_REFLECT_INTERFACE();
NvFlowContextOpt*(NV_FLOW_ABI* create)(NvFlowContextInterface* backendContextInterface, NvFlowContext* backendContext);
void(NV_FLOW_ABI* destroy)(NvFlowContextOpt* contextOpt);
void(NV_FLOW_ABI* getContext)(NvFlowContextOpt* contextOpt, NvFlowContextInterface** pContextInterface, NvFlowContext** pContext);
void(NV_FLOW_ABI* flush)(NvFlowContextOpt* contextOpt);
NvFlowBufferTransient*(NV_FLOW_ABI* importBackendBufferTransient)(NvFlowContextOpt* contextOpt, NvFlowBufferTransient* backendBufferTransient);
NvFlowTextureTransient*(NV_FLOW_ABI* importBackendTextureTransient)(NvFlowContextOpt* contextOpt, NvFlowTextureTransient* backendTextureTransient);
void(NV_FLOW_ABI* exportBufferTransient)(NvFlowContextOpt* contextOpt, NvFlowBufferTransient* bufferTransient, NvFlowBufferTransient** pBackendBufferTransient);
void(NV_FLOW_ABI* exportTextureTransient)(NvFlowContextOpt* contextOpt, NvFlowTextureTransient* textureTransient, NvFlowTextureTransient** pBackendTextureTransient);
void(NV_FLOW_ABI* setResourceMinLifetime)(NvFlowContextOpt* contextOpt, NvFlowUint64 minLifetime);
}NvFlowContextOptInterface;
#define NV_FLOW_REFLECT_TYPE NvFlowContextOptInterface
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_FUNCTION_POINTER(create, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroy, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getContext, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(flush, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(importBackendBufferTransient, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(importBackendTextureTransient, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(exportBufferTransient, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(exportTextureTransient, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(setResourceMinLifetime, 0, 0)
NV_FLOW_REFLECT_END(0)
NV_FLOW_REFLECT_INTERFACE_IMPL()
#undef NV_FLOW_REFLECT_TYPE
typedef NvFlowContextOptInterface*(NV_FLOW_ABI* PFN_NvFlowGetContextOptInterface)();
NV_FLOW_API NvFlowContextOptInterface* NvFlowGetContextOptInterface();
/// ********************************* Reference Device ***************************************
struct NvFlowDeviceManager;
typedef struct NvFlowDeviceManager NvFlowDeviceManager;
typedef struct NvFlowPhysicalDeviceDesc
{
NvFlowUint8 deviceUUID[16u];
NvFlowUint8 deviceLUID[8u];
NvFlowUint deviceNodeMask;
NvFlowBool32 deviceLUIDValid;
}NvFlowPhysicalDeviceDesc;
typedef struct NvFlowDeviceDesc
{
NvFlowUint deviceIndex;
NvFlowBool32 enableExternalUsage;
NvFlowLogPrint_t logPrint;
}NvFlowDeviceDesc;
struct NvFlowSwapchainDesc;
typedef struct NvFlowSwapchainDesc NvFlowSwapchainDesc;
#if defined(NV_FLOW_SWAPCHAIN_DESC)
struct NvFlowSwapchainDesc
{
#if defined(_WIN32)
HINSTANCE hinstance;
HWND hwnd;
#else
Display* dpy;
Window window;
#endif
NvFlowFormat format;
};
#endif
struct NvFlowDevice;
typedef struct NvFlowDevice NvFlowDevice;
struct NvFlowDeviceQueue;
typedef struct NvFlowDeviceQueue NvFlowDeviceQueue;
struct NvFlowDeviceSemaphore;
typedef struct NvFlowDeviceSemaphore NvFlowDeviceSemaphore;
struct NvFlowSwapchain;
typedef struct NvFlowSwapchain NvFlowSwapchain;
typedef struct NvFlowProfilerEntry
{
const char* label;
float cpuDeltaTime;
float gpuDeltaTime;
}NvFlowProfilerEntry;
typedef struct NvFlowDeviceInterface
{
NV_FLOW_REFLECT_INTERFACE();
NvFlowDeviceManager*(NV_FLOW_ABI* createDeviceManager)(NvFlowBool32 enableValidationOnDebugBuild, NvFlowThreadPoolInterface* threadPoolInterface, NvFlowUint threadCount);
void(NV_FLOW_ABI* destroyDeviceManager)(NvFlowDeviceManager* manager);
NvFlowBool32(NV_FLOW_ABI* enumerateDevices)(NvFlowDeviceManager* manager, NvFlowUint deviceIndex, NvFlowPhysicalDeviceDesc* pDesc);
NvFlowDevice*(NV_FLOW_ABI* createDevice)(NvFlowDeviceManager* manager, const NvFlowDeviceDesc* desc);
void(NV_FLOW_ABI* destroyDevice)(NvFlowDeviceManager* manager, NvFlowDevice* device);
NvFlowDeviceSemaphore*(NV_FLOW_ABI* createSemaphore)(NvFlowDevice* device);
void(NV_FLOW_ABI* destroySemaphore)(NvFlowDeviceSemaphore* semaphore);
void(NV_FLOW_ABI* getSemaphoreExternalHandle)(NvFlowDeviceSemaphore* semaphore, void* dstHandle, NvFlowUint64 dstHandleSize);
void(NV_FLOW_ABI* closeSemaphoreExternalHandle)(NvFlowDeviceSemaphore* semaphore, const void* srcHandle, NvFlowUint64 srcHandleSize);
NvFlowDeviceQueue*(NV_FLOW_ABI* getDeviceQueue)(NvFlowDevice* device);
int(NV_FLOW_ABI* flush)(NvFlowDeviceQueue* queue, NvFlowUint64* flushedFrameID, NvFlowDeviceSemaphore* waitSemaphore, NvFlowDeviceSemaphore* signalSemaphore);
NvFlowUint64(NV_FLOW_ABI* getLastFrameCompleted)(NvFlowDeviceQueue* queue);
void(NV_FLOW_ABI* waitForFrame)(NvFlowDeviceQueue* queue, NvFlowUint64 frameFrameID);
void(NV_FLOW_ABI* waitIdle)(NvFlowDeviceQueue* queue);
NvFlowContextInterface*(NV_FLOW_ABI* getContextInterface)(NvFlowDeviceQueue* queue);
NvFlowContext*(NV_FLOW_ABI* getContext)(NvFlowDeviceQueue* queue);
NvFlowSwapchain*(NV_FLOW_ABI* createSwapchain)(NvFlowDeviceQueue* queue, const NvFlowSwapchainDesc* desc);
void(NV_FLOW_ABI* destroySwapchain)(NvFlowSwapchain* swapchain);
void(NV_FLOW_ABI* resizeSwapchain)(NvFlowSwapchain* swapchain, NvFlowUint width, NvFlowUint height);
int(NV_FLOW_ABI* presentSwapchain)(NvFlowSwapchain* swapchain, NvFlowBool32 vsync, NvFlowUint64* flushedFrameID);
NvFlowTexture*(NV_FLOW_ABI* getSwapchainFrontTexture)(NvFlowSwapchain* swapchain);
void(NV_FLOW_ABI* enableProfiler)(NvFlowContext* context, void* userdata, void(NV_FLOW_ABI* reportEntries)(void* userdata, NvFlowUint64 captureID, NvFlowUint numEntries, NvFlowProfilerEntry* entries));
void(NV_FLOW_ABI* disableProfiler)(NvFlowContext* context);
NvFlowUint64(NV_FLOW_ABI* registerBufferId)(NvFlowContext* context, NvFlowBuffer* buffer);
NvFlowUint64(NV_FLOW_ABI* registerTextureId)(NvFlowContext* context, NvFlowTexture* texture);
void(NV_FLOW_ABI* unregisterBufferId)(NvFlowContext* context, NvFlowUint64 bufferId);
void(NV_FLOW_ABI* unregisterTextureId)(NvFlowContext* context, NvFlowUint64 textureId);
void(NV_FLOW_ABI* setResourceMinLifetime)(NvFlowContext* context, NvFlowUint64 minLifetime);
void(NV_FLOW_ABI* getBufferExternalHandle)(NvFlowContext* context, NvFlowBuffer* buffer, void* dstHandle, NvFlowUint64 dstHandleSize, NvFlowUint64* pBufferSizeInBytes);
void(NV_FLOW_ABI* closeBufferExternalHandle)(NvFlowContext* context, NvFlowBuffer* buffer, const void* srcHandle, NvFlowUint64 srcHandleSize);
}NvFlowDeviceInterface;
#define NV_FLOW_REFLECT_TYPE NvFlowDeviceInterface
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_FUNCTION_POINTER(createDeviceManager, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroyDeviceManager, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(enumerateDevices, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(createDevice, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroyDevice, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(createSemaphore, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroySemaphore, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getSemaphoreExternalHandle, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(closeSemaphoreExternalHandle, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getDeviceQueue, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(flush, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getLastFrameCompleted, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(waitForFrame, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(waitIdle, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getContextInterface, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getContext, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(createSwapchain, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroySwapchain, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(resizeSwapchain, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(presentSwapchain, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getSwapchainFrontTexture, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(enableProfiler, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(disableProfiler, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(registerBufferId, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(registerTextureId, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(unregisterBufferId, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(unregisterTextureId, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(setResourceMinLifetime, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getBufferExternalHandle, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(closeBufferExternalHandle, 0, 0)
NV_FLOW_REFLECT_END(0)
NV_FLOW_REFLECT_INTERFACE_IMPL()
#undef NV_FLOW_REFLECT_TYPE
typedef NvFlowDeviceInterface* (NV_FLOW_ABI* PFN_NvFlowGetDeviceInterface)(NvFlowContextApi api);
NV_FLOW_API NvFlowDeviceInterface* NvFlowGetDeviceInterface(NvFlowContextApi api);
/// ********************************* RadixSort ***************************************
struct NvFlowRadixSort;
typedef struct NvFlowRadixSort NvFlowRadixSort;
typedef struct NvFlowRadixSortInterface
{
NV_FLOW_REFLECT_INTERFACE();
NvFlowRadixSort*(NV_FLOW_ABI* create)(NvFlowContextInterface* contextInterface, NvFlowContext* context);
void(NV_FLOW_ABI* destroy)(NvFlowContext* context, NvFlowRadixSort* radixSort);
void(NV_FLOW_ABI* reserve)(NvFlowContext* context, NvFlowRadixSort* radixSort, NvFlowUint numKeys);
void(NV_FLOW_ABI* getInputBuffers)(NvFlowContext* context, NvFlowRadixSort* radixSort, NvFlowBufferTransient** pKeyBuffer, NvFlowBufferTransient** pValBuffer);
void(NV_FLOW_ABI* sort)(NvFlowContext* context, NvFlowRadixSort* radixSort, NvFlowUint numKeys, NvFlowUint numKeyBits);
void(NV_FLOW_ABI* getOutputBuffers)(NvFlowContext* context, NvFlowRadixSort* radixSort, NvFlowBufferTransient** pKeyBuffer, NvFlowBufferTransient** pValBuffer);
}NvFlowRadixSortInterface;
#define NV_FLOW_REFLECT_TYPE NvFlowRadixSortInterface
NV_FLOW_REFLECT_BEGIN()
NV_FLOW_REFLECT_FUNCTION_POINTER(create, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(destroy, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(reserve, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getInputBuffers, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(sort, 0, 0)
NV_FLOW_REFLECT_FUNCTION_POINTER(getOutputBuffers, 0, 0)
NV_FLOW_REFLECT_END(0)
NV_FLOW_REFLECT_INTERFACE_IMPL()
#undef NV_FLOW_REFLECT_TYPE
typedef NvFlowRadixSortInterface* (NV_FLOW_ABI* PFN_NvFlowGetRadixSortInterface)();
NV_FLOW_API NvFlowRadixSortInterface* NvFlowGetRadixSortInterface();
#endif |
NVIDIA-Omniverse/PhysX/flow/include/nvflowext/shaders/NvFlowRayMarchUtils.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#ifndef NV_FLOW_RAY_MARCH_UTILS_H
#define NV_FLOW_RAY_MARCH_UTILS_H
#if defined(__cplusplus)
#include "NvFlowExt.h"
#include "NvFlowRayMarchParams.h"
#include "NvFlowMath.h"
NV_FLOW_INLINE void NvFlowRayMarchLayerShaderParams_populate(
NvFlowRayMarchLayerShaderParams* dst,
NvFlowUint velocityLevelIdx,
NvFlowUint densityLevelIdx,
NvFlowUint layerParamIdx,
const NvFlowSparseParams* sparseParams,
const NvFlowRayMarchParams* rayMarchParams
)
{
const NvFlowSparseLevelParams* levelParamsVelocity = &sparseParams->levels[velocityLevelIdx];
const NvFlowSparseLevelParams* levelParamsDensity = &sparseParams->levels[densityLevelIdx];
const NvFlowSparseLayerParams* layerParams = &sparseParams->layers[layerParamIdx];
NvFlowFloat3 blockSizeWorld = layerParams->blockSizeWorld;
NvFlowFloat3 blockSizeWorldInv = layerParams->blockSizeWorldInv;
float minBlockSizeWorld = fminf(blockSizeWorld.x, fminf(blockSizeWorld.y, blockSizeWorld.z));
float maxBlockSizeWorld = fmaxf(blockSizeWorld.x, fmaxf(blockSizeWorld.y, blockSizeWorld.z));
NvFlowFloat3 cellSize = NvFlowFloat3{
blockSizeWorld.x / float(levelParamsDensity->blockDimLessOne.x + 1u),
blockSizeWorld.y / float(levelParamsDensity->blockDimLessOne.y + 1u),
blockSizeWorld.z / float(levelParamsDensity->blockDimLessOne.z + 1u)
};
NvFlowFloat3 cellSizeInv = { 1.f / cellSize.x, 1.f / cellSize.y, 1.f / cellSize.z };
float cellSizeMin = fminf(fminf(cellSize.x, cellSize.y), cellSize.z);
NvFlowFloat3 velocityCellSizeInv = NvFlowFloat3{
float(levelParamsVelocity->blockDimLessOne.x + 1u) / blockSizeWorld.x,
float(levelParamsVelocity->blockDimLessOne.y + 1u) / blockSizeWorld.y,
float(levelParamsVelocity->blockDimLessOne.z + 1u) / blockSizeWorld.z
};
float stepSize = rayMarchParams->stepSizeScale * cellSizeMin;
float stepSizeInv = 1.f / stepSize;
// normalize alphaScale based on stepSize
float alphaScale = 1.f - expf(-rayMarchParams->attenuation * stepSize);
float layerColormapV = (float(layerParamIdx) + 0.5f) / float(sparseParams->layerCount);
dst->blockSizeWorld = blockSizeWorld;
dst->minBlockSizeWorld = minBlockSizeWorld;
dst->blockSizeWorldInv = blockSizeWorldInv;
dst->maxBlockSizeWorld = maxBlockSizeWorld;
dst->cellSize = cellSize;
dst->stepSize = stepSize;
dst->cellSizeInv = cellSizeInv;
dst->stepSizeInv = stepSizeInv;
dst->locationMin = layerParams->locationMin;
dst->locationMax = layerParams->locationMax;
dst->worldMin.x = (layerParams->locationMin.x - 0.5f) * layerParams->blockSizeWorld.x;
dst->worldMin.y = (layerParams->locationMin.y - 0.5f) * layerParams->blockSizeWorld.y;
dst->worldMin.z = (layerParams->locationMin.z - 0.5f) * layerParams->blockSizeWorld.z;
dst->enableBlockWireframe = rayMarchParams->enableBlockWireframe;
dst->worldMax.x = (layerParams->locationMax.x + 0.5f) * layerParams->blockSizeWorld.x;
dst->worldMax.y = (layerParams->locationMax.y + 0.5f) * layerParams->blockSizeWorld.y;
dst->worldMax.z = (layerParams->locationMax.z + 0.5f) * layerParams->blockSizeWorld.z;
dst->enableRawMode = rayMarchParams->enableRawMode;
dst->velocityCellSizeInv = velocityCellSizeInv;
dst->deltaTime = layerParams->deltaTime;
dst->layer = layerParams->layer;
dst->layerColormapV = layerColormapV;
dst->alphaScale = alphaScale;
dst->colorScale = rayMarchParams->colorScale;
dst->shadowFactor = rayMarchParams->shadowFactor;
dst->pad1 = 0.f;
dst->pad2 = 0.f;
dst->pad3 = 0.f;
dst->cloud.densityMultiplier = rayMarchParams->cloud.densityMultiplier;
dst->cloud.enableCloudMode = rayMarchParams->cloud.enableCloudMode;
dst->cloud.pad1 = 0.f;
dst->cloud.pad2 = 0.f;
dst->cloud.ambientColor = rayMarchParams->cloud.ambientColor;
dst->cloud.ambientMultiplier = rayMarchParams->cloud.ambientMultiplier;
dst->cloud.volumeBaseColor = rayMarchParams->cloud.volumeBaseColor;
dst->cloud.volumeColorMultiplier = rayMarchParams->cloud.volumeColorMultiplier;
dst->cloud.sunDirection = rayMarchParams->cloud.sunDirection;
dst->cloud.shadowStepMultiplier = rayMarchParams->cloud.shadowStepMultiplier;
dst->cloud.attenuationMultiplier = rayMarchParams->cloud.attenuationMultiplier;
dst->cloud.numShadowSteps = rayMarchParams->cloud.numShadowSteps;
}
NV_FLOW_INLINE void NvFlowRayMarchIsosurfaceLayerShaderParams_populate(
NvFlowRayMarchIsosurfaceLayerShaderParams* dst,
NvFlowUint densityLevelIdx,
NvFlowUint layerParamIdx,
const NvFlowSparseParams* sparseParams,
const NvFlowRayMarchIsosurfaceParams* rayMarchParams
)
{
const NvFlowSparseLevelParams* levelParams = &sparseParams->levels[densityLevelIdx];
const NvFlowSparseLayerParams* layerParams = &sparseParams->layers[layerParamIdx];
NvFlowFloat3 blockSizeWorld = layerParams->blockSizeWorld;
NvFlowFloat3 blockSizeWorldInv = layerParams->blockSizeWorldInv;
float minBlockSizeWorld = fminf(blockSizeWorld.x, fminf(blockSizeWorld.y, blockSizeWorld.z));
float maxBlockSizeWorld = fmaxf(blockSizeWorld.x, fmaxf(blockSizeWorld.y, blockSizeWorld.z));
NvFlowFloat3 cellSize = NvFlowFloat3{
blockSizeWorld.x / float(levelParams->blockDimLessOne.x + 1u),
blockSizeWorld.y / float(levelParams->blockDimLessOne.y + 1u),
blockSizeWorld.z / float(levelParams->blockDimLessOne.z + 1u)
};
NvFlowFloat3 cellSizeInv = { 1.f / cellSize.x, 1.f / cellSize.y, 1.f / cellSize.z };
float cellSizeMin = fminf(fminf(cellSize.x, cellSize.y), cellSize.z);
float stepSize = rayMarchParams->stepSizeScale * cellSizeMin;
float stepSizeInv = 1.f / stepSize;
dst->blockSizeWorld = blockSizeWorld;
dst->minBlockSizeWorld = minBlockSizeWorld;
dst->blockSizeWorldInv = blockSizeWorldInv;
dst->maxBlockSizeWorld = maxBlockSizeWorld;
dst->cellSize = cellSize;
dst->stepSize = stepSize;
dst->cellSizeInv = cellSizeInv;
dst->stepSizeInv = stepSizeInv;
dst->locationMin = layerParams->locationMin;
dst->locationMax = layerParams->locationMax;
dst->worldMin.x = (layerParams->locationMin.x - 0.5f) * layerParams->blockSizeWorld.x;
dst->worldMin.y = (layerParams->locationMin.y - 0.5f) * layerParams->blockSizeWorld.y;
dst->worldMin.z = (layerParams->locationMin.z - 0.5f) * layerParams->blockSizeWorld.z;
dst->enableBlockWireframe = rayMarchParams->enableBlockWireframe;
dst->worldMax.x = (layerParams->locationMax.x + 0.5f) * layerParams->blockSizeWorld.x;
dst->worldMax.y = (layerParams->locationMax.y + 0.5f) * layerParams->blockSizeWorld.y;
dst->worldMax.z = (layerParams->locationMax.z + 0.5f) * layerParams->blockSizeWorld.z;
dst->visualizeNormals = rayMarchParams->visualizeNormals;
dst->layer = layerParams->layer;
dst->densityThreshold = rayMarchParams->densityThreshold;
dst->refractionMode = rayMarchParams->refractionMode;
dst->pad2 = 0u;
dst->fluidColor = rayMarchParams->fluidColor;
dst->fluidIoR = rayMarchParams->fluidIoR;
dst->fluidSpecularReflectance = rayMarchParams->fluidSpecularReflectance;
dst->fluidAbsorptionCoefficient = rayMarchParams->fluidAbsorptionCoefficient;
dst->fluidDiffuseReflectance = rayMarchParams->fluidDiffuseReflectance;
dst->pad3 = 0.f;
dst->fluidRadiance = rayMarchParams->fluidRadiance;
dst->pad4 = 0.f;
}
NV_FLOW_INLINE void NvFlowRayMarchShaderParams_populate(
NvFlowRayMarchShaderParams* dst,
NvFlowUint velocityLevelIdx,
NvFlowUint densityLevelIdx,
const NvFlowSparseParams* sparseParams,
const NvFlowFloat4x4* view,
const NvFlowFloat4x4* projection,
const NvFlowFloat4x4* projectionJittered,
NvFlowUint textureWidth,
NvFlowUint textureHeight,
NvFlowUint sceneDepthWidth,
NvFlowUint sceneDepthHeight,
float compositeColorScale
)
{
using namespace NvFlowMath;
NvFlowFloat4x4 projectionInv = matrixInverse(*projection);
NvFlowFloat4x4 projectionJitteredInv = matrixInverse(*projectionJittered);
NvFlowFloat4x4 viewInv = matrixInverse(*view);
FrustumRays frustumRays = {};
computeFrustumRays(&frustumRays, viewInv, projectionInv);
const NvFlowSparseLevelParams* levelParamsVelocity = &sparseParams->levels[velocityLevelIdx];
const NvFlowSparseLevelParams* levelParamsDensity = &sparseParams->levels[densityLevelIdx];
dst->levelParamsVelocity = *levelParamsVelocity;
dst->levelParamsDensity = *levelParamsDensity;
dst->projection = NvFlowMath::matrixTranspose(*projection);
dst->view = NvFlowMath::matrixTranspose(*view);
dst->projectionJitteredInv = NvFlowMath::matrixTranspose(projectionJitteredInv);
dst->viewInv = NvFlowMath::matrixTranspose(viewInv);
dst->rayDir00 = frustumRays.rayDir00;
dst->rayDir10 = frustumRays.rayDir10;
dst->rayDir01 = frustumRays.rayDir01;
dst->rayDir11 = frustumRays.rayDir11;
dst->rayOrigin00 = frustumRays.rayOrigin00;
dst->rayOrigin10 = frustumRays.rayOrigin10;
dst->rayOrigin01 = frustumRays.rayOrigin01;
dst->rayOrigin11 = frustumRays.rayOrigin11;
dst->width = float(textureWidth);
dst->height = float(textureHeight);
dst->widthInv = 1.f / float(textureWidth);
dst->heightInv = 1.f / float(textureHeight);
dst->depthWidth = float(sceneDepthWidth);
dst->depthHeight = float(sceneDepthHeight);
dst->depthWidthInv = 1.f / float(sceneDepthWidth);
dst->depthHeightInv = 1.f / float(sceneDepthHeight);
dst->numLayers = sparseParams->layerCount;
dst->maxWorldDistance = INFINITY;
dst->isReverseZ = frustumRays.isReverseZ;
dst->compositeColorScale = compositeColorScale;
}
NV_FLOW_INLINE void NvFlowSelfShadowLayerShaderParams_populate(
NvFlowSelfShadowLayerShaderParams* dst,
NvFlowUint coarseLevelIdx,
NvFlowUint fineLevelIdx,
NvFlowUint layerParamIdx,
const NvFlowSparseParams* sparseParams,
const NvFlowShadowParams* shadowParams
)
{
bool isCoarse = coarseLevelIdx != fineLevelIdx;
const NvFlowSparseLevelParams* coarseDensityLevelParams = &sparseParams->levels[coarseLevelIdx];
const NvFlowSparseLayerParams* layerParams = &sparseParams->layers[layerParamIdx];
int layer = layerParams->layer;
NvFlowFloat3 blockSizeWorld = layerParams->blockSizeWorld;
NvFlowFloat3 blockSizeWorldInv = layerParams->blockSizeWorldInv;
float minBlockSizeWorld = fminf(blockSizeWorld.x, fminf(blockSizeWorld.y, blockSizeWorld.z));
float maxBlockSizeWorld = fmaxf(blockSizeWorld.x, fmaxf(blockSizeWorld.y, blockSizeWorld.z));
NvFlowFloat3 cellSize = NvFlowFloat3{
blockSizeWorld.x / float(coarseDensityLevelParams->blockDimLessOne.x + 1u),
blockSizeWorld.y / float(coarseDensityLevelParams->blockDimLessOne.y + 1u),
blockSizeWorld.z / float(coarseDensityLevelParams->blockDimLessOne.z + 1u)
};
NvFlowFloat3 cellSizeInv = { 1.f / cellSize.x, 1.f / cellSize.y, 1.f / cellSize.z };
float cellSizeMin = fminf(fminf(cellSize.x, cellSize.y), cellSize.z);
float stepSize = shadowParams->stepSizeScale * cellSizeMin;
float stepSizeInv = 1.f / stepSize;
float stepOffset = shadowParams->stepOffsetScale * cellSizeMin;
// normalize alphaScale based on stepSize
float alphaScale = 1.f - expf(-shadowParams->attenuation * stepSize);
float layerColormapV = (float(layerParamIdx) + 0.5f) / float(sparseParams->layerCount);
dst->base.blockSizeWorld = blockSizeWorld;
dst->base.minBlockSizeWorld = minBlockSizeWorld;
dst->base.blockSizeWorldInv = blockSizeWorldInv;
dst->base.maxBlockSizeWorld = maxBlockSizeWorld;
dst->base.cellSize = cellSize;
dst->base.stepSize = stepSize;
dst->base.cellSizeInv = cellSizeInv;
dst->base.stepSizeInv = stepSizeInv;
dst->base.locationMin = layerParams->locationMin;
dst->base.locationMax = layerParams->locationMax;
dst->base.worldMin.x = (layerParams->locationMin.x - 0.5f) * layerParams->blockSizeWorld.x;
dst->base.worldMin.y = (layerParams->locationMin.y - 0.5f) * layerParams->blockSizeWorld.y;
dst->base.worldMin.z = (layerParams->locationMin.z - 0.5f) * layerParams->blockSizeWorld.z;
dst->base.enableBlockWireframe = NV_FLOW_FALSE;
dst->base.worldMax.x = (layerParams->locationMax.x + 0.5f) * layerParams->blockSizeWorld.x;
dst->base.worldMax.y = (layerParams->locationMax.y + 0.5f) * layerParams->blockSizeWorld.y;
dst->base.worldMax.z = (layerParams->locationMax.z + 0.5f) * layerParams->blockSizeWorld.z;
dst->base.enableRawMode = NV_FLOW_FALSE;
dst->base.velocityCellSizeInv = cellSizeInv;
dst->base.deltaTime = layerParams->deltaTime;
dst->base.layer = layer;
dst->base.layerColormapV = layerColormapV;
dst->base.alphaScale = alphaScale;
dst->base.colorScale = 1.f;
dst->base.shadowFactor = 0.f;
dst->base.pad1 = 0.f;
dst->base.pad2 = 0.f;
dst->base.pad3 = 0.f;
// Set cloud mode to default
dst->base.cloud.densityMultiplier = 0.5f;
dst->base.cloud.enableCloudMode = NV_FLOW_FALSE;
dst->base.cloud.pad1 = 0.f;
dst->base.cloud.pad2 = 0.f;
dst->base.cloud.ambientColor.x = 0.4f;
dst->base.cloud.ambientColor.y = 0.55f;
dst->base.cloud.ambientColor.z = 0.9f;
dst->base.cloud.ambientMultiplier = 1.f;
dst->base.cloud.volumeBaseColor.x = 1.1f;
dst->base.cloud.volumeBaseColor.y = 1.f;
dst->base.cloud.volumeBaseColor.z = 0.9f;
dst->base.cloud.volumeColorMultiplier = 1.f;
dst->base.cloud.sunDirection.x = 1.f;
dst->base.cloud.sunDirection.y = 1.f;
dst->base.cloud.sunDirection.z = 1.f;
dst->base.cloud.shadowStepMultiplier = 1.f;
dst->base.cloud.attenuationMultiplier.x = 1.f;
dst->base.cloud.attenuationMultiplier.y = 1.f;
dst->base.cloud.attenuationMultiplier.z = 1.f;
dst->base.cloud.numShadowSteps = 10u;
dst->minIntensity = shadowParams->minIntensity;
dst->numSteps = isCoarse ? (shadowParams->numSteps / 2u) : shadowParams->numSteps;
dst->isPointLight = shadowParams->isPointLight;
dst->stepOffset = stepOffset;
dst->lightDirection = shadowParams->lightDirection;
dst->enabled = shadowParams->enabled;
dst->lightPosition = shadowParams->lightPosition;
dst->pad3 = 0.f;
}
NV_FLOW_INLINE void NvFlowSelfShadowShaderParams_populate(
NvFlowSelfShadowShaderParams* dst,
NvFlowUint coarseLevelIdx,
NvFlowUint fineLevelIdx,
const NvFlowSparseParams* sparseParams,
NvFlowUint blockIdxOffset
)
{
dst->blockIdxOffset = blockIdxOffset;
dst->pad1 = 0u;
dst->pad2 = 0u;
dst->pad3 = 0u;
dst->coarseDensityTable = sparseParams->levels[coarseLevelIdx];
dst->densityTable = sparseParams->levels[fineLevelIdx];
}
#endif
#endif |
NVIDIA-Omniverse/PhysX/flow/include/nvflowext/shaders/NvFlowRayMarchParams.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#ifndef NV_FLOW_RAY_MARCH_PARAMS_H
#define NV_FLOW_RAY_MARCH_PARAMS_H
#include "NvFlowShaderTypes.h"
struct NvFlowRayMarchCloudLayerShaderParams
{
float densityMultiplier;
NvFlowUint enableCloudMode;
float pad1;
float pad2;
NvFlowFloat3 ambientColor;
float ambientMultiplier;
NvFlowFloat3 volumeBaseColor;
float volumeColorMultiplier;
NvFlowFloat3 sunDirection;
float shadowStepMultiplier;
NvFlowFloat3 attenuationMultiplier;
int numShadowSteps;
};
#ifdef NV_FLOW_CPU
typedef struct NvFlowRayMarchCloudLayerShaderParams NvFlowRayMarchCloudLayerShaderParams;
#endif
struct NvFlowRayMarchLayerShaderParams
{
NvFlowFloat3 blockSizeWorld;
float minBlockSizeWorld;
NvFlowFloat3 blockSizeWorldInv;
float maxBlockSizeWorld;
NvFlowFloat3 cellSize;
float stepSize;
NvFlowFloat3 cellSizeInv;
float stepSizeInv;
NvFlowInt4 locationMin;
NvFlowInt4 locationMax;
NvFlowFloat3 worldMin;
NvFlowUint enableBlockWireframe;
NvFlowFloat3 worldMax;
NvFlowUint enableRawMode;
NvFlowFloat3 velocityCellSizeInv;
float deltaTime;
int layer;
float layerColormapV;
float alphaScale;
float colorScale;
float shadowFactor;
float pad1;
float pad2;
float pad3;
NvFlowRayMarchCloudLayerShaderParams cloud;
};
#ifdef NV_FLOW_CPU
typedef struct NvFlowRayMarchLayerShaderParams NvFlowRayMarchLayerShaderParams;
#endif
struct NvFlowRayMarchIsosurfaceLayerShaderParams
{
NvFlowFloat3 blockSizeWorld;
float minBlockSizeWorld;
NvFlowFloat3 blockSizeWorldInv;
float maxBlockSizeWorld;
NvFlowFloat3 cellSize;
float stepSize;
NvFlowFloat3 cellSizeInv;
float stepSizeInv;
NvFlowInt4 locationMin;
NvFlowInt4 locationMax;
NvFlowFloat3 worldMin;
NvFlowUint enableBlockWireframe;
NvFlowFloat3 worldMax;
NvFlowUint visualizeNormals;
int layer;
float densityThreshold;
NvFlowUint refractionMode;
NvFlowUint pad2;
NvFlowFloat3 fluidColor;
float fluidIoR;
NvFlowFloat3 fluidSpecularReflectance;
float fluidAbsorptionCoefficient;
NvFlowFloat3 fluidDiffuseReflectance;
float pad3;
NvFlowFloat3 fluidRadiance;
float pad4;
};
#ifdef NV_FLOW_CPU
typedef struct NvFlowRayMarchIsosurfaceLayerShaderParams NvFlowRayMarchIsosurfaceLayerShaderParams;
#endif
struct NvFlowRayMarchShaderParams
{
NvFlowSparseLevelParams levelParamsVelocity;
NvFlowSparseLevelParams levelParamsDensity;
NvFlowFloat4x4 projection;
NvFlowFloat4x4 view;
NvFlowFloat4x4 projectionJitteredInv;
NvFlowFloat4x4 viewInv;
NvFlowFloat4 rayDir00;
NvFlowFloat4 rayDir10;
NvFlowFloat4 rayDir01;
NvFlowFloat4 rayDir11;
NvFlowFloat4 rayOrigin00;
NvFlowFloat4 rayOrigin10;
NvFlowFloat4 rayOrigin01;
NvFlowFloat4 rayOrigin11;
float width;
float height;
float widthInv;
float heightInv;
float depthWidth;
float depthHeight;
float depthWidthInv;
float depthHeightInv;
NvFlowUint numLayers;
float maxWorldDistance;
NvFlowUint isReverseZ;
float compositeColorScale;
};
#ifdef NV_FLOW_CPU
typedef struct NvFlowRayMarchShaderParams NvFlowRayMarchShaderParams;
#endif
struct NvFlowSelfShadowLayerShaderParams
{
NvFlowRayMarchLayerShaderParams base;
float minIntensity;
NvFlowUint numSteps;
NvFlowUint isPointLight;
float stepOffset;
NvFlowFloat3 lightDirection;
NvFlowUint enabled;
NvFlowFloat3 lightPosition;
float pad3;
};
#ifdef NV_FLOW_CPU
typedef struct NvFlowSelfShadowLayerShaderParams NvFlowSelfShadowLayerShaderParams;
#endif
struct NvFlowSelfShadowShaderParams
{
NvFlowUint blockIdxOffset;
NvFlowUint pad1;
NvFlowUint pad2;
NvFlowUint pad3;
NvFlowSparseLevelParams coarseDensityTable;
NvFlowSparseLevelParams densityTable;
};
#ifdef NV_FLOW_CPU
typedef struct NvFlowSelfShadowShaderParams NvFlowSelfShadowShaderParams;
#endif
#endif |
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowStringHash.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowTypes.h"
#include "NvFlowArray.h"
NV_FLOW_INLINE NvFlowUint NvFlowStringHashFNV(const char* a)
{
// FNV-1a
NvFlowUint hash = 2166136261u;
NvFlowUint idx = 0u;
if (a)
{
while (a[idx])
{
hash = 16777619u * (hash ^ (NvFlowUint)(a[idx]));
idx++;
}
}
return hash;
}
template<class T, NvFlowUint64 staticCapacity = 0u>
struct NvFlowStringHashTable
{
NvFlowArray<NvFlowUint, staticCapacity> hashs;
NvFlowArray<NvFlowArray<char>, staticCapacity> keys;
NvFlowArray<T, staticCapacity> values;
NvFlowUint64 keyCount = 0llu;
NvFlowUint64 find(const char* path, NvFlowUint hash)
{
path = path ? path : "";
NvFlowUint64 beginIdx = hash & (hashs.size - 1u);
for (NvFlowUint64 iterIdx = 0u; iterIdx < hashs.size; iterIdx++)
{
NvFlowUint64 idx = (iterIdx + beginIdx) & (hashs.size - 1u);
if (hashs[idx] == hash &&
keys[idx].size > 0u &&
strcmp(keys[idx].data, path) == 0)
{
return idx;
}
}
return ~0llu;
}
NvFlowUint64 insertNoResize(const char* path, NvFlowUint hash, const T& value, NvFlowBool32* pSuccess = nullptr)
{
path = path ? path : "";
if (pSuccess)
{
*pSuccess = NV_FLOW_FALSE;
}
NvFlowUint64 beginIdx = hash & (hashs.size - 1u);
for (NvFlowUint64 iterIdx = 0u; iterIdx < hashs.size; iterIdx++)
{
NvFlowUint64 idx = (iterIdx + beginIdx) & (hashs.size - 1u);
if (keys[idx].size == 0u)
{
keyCount++;
hashs[idx] = hash;
for (NvFlowUint64 strIdx = 0u; path[strIdx]; strIdx++)
{
keys[idx].pushBack(path[strIdx]);
}
keys[idx].pushBack('\0');
values[idx] = value;
if (pSuccess)
{
*pSuccess = NV_FLOW_TRUE;
}
return idx;
}
else if (hashs[idx] == hash &&
keys[idx].size > 0u &&
strcmp(keys[idx].data, path) == 0)
{
return idx;
}
}
return ~0llu;
}
NvFlowUint64 insert(const char* path, NvFlowUint hash, const T& value, NvFlowBool32* pSuccess = nullptr)
{
// resize if adding key would make 50+% full
if (2u * (keyCount + 1u) >= hashs.size)
{
NvFlowArray<NvFlowUint, staticCapacity> hashs_old(std::move(hashs));
NvFlowArray<NvFlowArray<char>, staticCapacity> keys_old(std::move(keys));
NvFlowArray<T, staticCapacity> values_old(std::move(values));
NvFlowUint64 newSize = 1u;
while (newSize <= hashs_old.size)
{
newSize *= 2u;
}
hashs.reserve(newSize);
keys.reserve(newSize);
values.reserve(newSize);
hashs.size = newSize;
keys.size = newSize;
values.size = newSize;
keyCount = 0u; // reset key count, because insert counts it again
for (NvFlowUint64 idx = 0u; idx < hashs_old.size; idx++)
{
if (keys_old[idx].size > 0u)
{
insertNoResize(keys_old[idx].data, hashs_old[idx], values_old[idx], nullptr);
}
}
}
return insertNoResize(path, hash, value, pSuccess);
}
NvFlowBool32 erase(const char* path, NvFlowUint hash)
{
NvFlowUint64 findIdx = find(path, hash);
if (findIdx != ~0llu)
{
keyCount--;
hashs[findIdx] = 0u;
keys[findIdx].size = 0u;
values[findIdx] = T();
return NV_FLOW_TRUE;
}
return NV_FLOW_FALSE;
}
};
|
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowString.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include "NvFlowString.h"
#include "NvFlowArray.h"
#include <stdio.h>
struct NvFlowStringPool
{
NvFlowArray<NvFlowArray<char>, 16u> heaps;
};
NvFlowStringPool* NvFlowStringPoolCreate()
{
return new NvFlowStringPool();
}
void NvFlowStringPoolAllocate_newHeap(NvFlowStringPool* ptr, NvFlowUint64 allocSize)
{
auto& currentHeap = ptr->heaps[ptr->heaps.allocateBack()];
NvFlowUint64 heapSize = 4096u; // default heap size
while (heapSize < allocSize)
{
heapSize *= 2u;
}
currentHeap.reserve(heapSize);
}
NvFlowUint64 NvFlowStringPool_alignment(NvFlowUint64 size)
{
return 8u * ((size + 7u) / 8u);
}
char* NvFlowStringPoolAllocate_internal(NvFlowStringPool* ptr, NvFlowUint64 size)
{
NvFlowUint64 allocSize = NvFlowStringPool_alignment(size);
if (ptr->heaps.size > 0u)
{
auto& currentHeap = ptr->heaps[ptr->heaps.size - 1u];
if (currentHeap.size + allocSize <= currentHeap.capacity)
{
char* ret = currentHeap.data + currentHeap.size;
ret[size - 1] = 0;
currentHeap.size += allocSize;
return ret;
}
}
NvFlowStringPoolAllocate_newHeap(ptr, allocSize);
return NvFlowStringPoolAllocate_internal(ptr, size);
}
char* NvFlowStringPoolAllocate(NvFlowStringPool* ptr, NvFlowUint64 size)
{
return NvFlowStringPoolAllocate_internal(ptr, size + 1);
}
void NvFlowStringPoolTempAllocate(NvFlowStringPool* ptr, char** p_str_data, NvFlowUint64* p_str_size)
{
if (ptr->heaps.size > 0u)
{
auto& currentHeap = ptr->heaps[ptr->heaps.size - 1u];
char* str_data = currentHeap.data + currentHeap.size;
NvFlowUint64 str_size = currentHeap.capacity - currentHeap.size;
if (str_size > 0)
{
str_data[str_size - 1] = 0;
str_size--;
*p_str_size = str_size;
*p_str_data = str_data;
return;
}
}
NvFlowStringPoolAllocate_newHeap(ptr, 8u);
NvFlowStringPoolTempAllocate(ptr, p_str_data, p_str_size);
}
void NvFlowStringPoolTempAllocateCommit(NvFlowStringPool* ptr, char* str_data, NvFlowUint64 str_size)
{
// to reverse the str_size-- in NvFlowStringPoolTempAllocate()
str_size++;
if (ptr->heaps.size > 0u)
{
auto& currentHeap = ptr->heaps[ptr->heaps.size - 1u];
char* compStr_data = currentHeap.data + currentHeap.size;
NvFlowUint64 compStr_size = currentHeap.capacity - currentHeap.size;
if (str_data == compStr_data && str_size <= compStr_size)
{
NvFlowUint64 allocSize = NvFlowStringPool_alignment(str_size);
currentHeap.size += allocSize;
}
}
}
void NvFlowStringPoolDestroy(NvFlowStringPool* ptr)
{
delete ptr;
}
void NvFlowStringPoolReset(NvFlowStringPool* ptr)
{
for (NvFlowUint64 heapIdx = 0u; heapIdx < ptr->heaps.size; heapIdx++)
{
ptr->heaps[heapIdx].size = 0u;
}
ptr->heaps.size = 0u;
}
char* NvFlowStringPrintV(NvFlowStringPool* pool, const char* format, va_list args)
{
va_list argsCopy;
va_copy(argsCopy, args);
NvFlowUint64 str_size = ~0llu;
char* str_data = nullptr;
NvFlowStringPoolTempAllocate(pool, &str_data, &str_size);
NvFlowUint64 count = (NvFlowUint64)vsnprintf(str_data, str_size + 1, format, args);
if (count <= str_size)
{
str_size = count;
NvFlowStringPoolTempAllocateCommit(pool, str_data, str_size);
}
else
{
str_data = NvFlowStringPoolAllocate(pool, count);
str_size = count;
count = vsnprintf(str_data, str_size + 1, format, argsCopy);
}
va_end(argsCopy);
return str_data;
}
char* NvFlowStringPrint(NvFlowStringPool* pool, const char* format, ...)
{
va_list args;
va_start(args, format);
char* str = NvFlowStringPrintV(pool, format, args);
va_end(args);
return str;
}
/// ************************** File Utils *********************************************
const char* NvFlowTextFileLoad(NvFlowStringPool* pool, const char* filename)
{
FILE* file = nullptr;
#if defined(_WIN32)
fopen_s(&file, filename, "r");
#else
file = fopen(filename, "r");
#endif
if (file == nullptr)
{
return nullptr;
}
NvFlowUint64 chunkSize = 4096u;
NvFlowArray<const char*, 8u> chunks;
size_t readBytes = 0u;
do
{
chunkSize *= 2u;
char* chunkStr = NvFlowStringPoolAllocate(pool, chunkSize);
chunkStr[0] = '\0';
readBytes = fread(chunkStr, 1u, chunkSize, file);
chunkStr[readBytes] = '\0';
chunks.pushBack(chunkStr);
} while(readBytes == chunkSize);
fclose(file);
const char* text_data = (chunks.size == 1u) ? chunks[0u] : NvFlowStringConcatN(pool, chunks.data, chunks.size);
//NvFlowUint64 strLength = NvFlowStringLength(text_data);
//printf("NvFlowTextureFileLoad(%s) %llu bytes in %llu chunks\n", filename, strLength, chunks.size);
return text_data;
}
void NvFlowTextFileStore(const char* text_data, const char* filename)
{
FILE* file = nullptr;
#if defined(_WIN32)
fopen_s(&file, filename, "w");
#else
file = fopen(filename, "w");
#endif
if (file == nullptr)
{
return;
}
NvFlowUint64 text_size = NvFlowStringLength(text_data);
fwrite(text_data, 1u, text_size, file);
fclose(file);
}
NvFlowBool32 NvFlowTextFileTestOpen(const char* filename)
{
FILE* file = nullptr;
#if defined(_WIN32)
fopen_s(&file, filename, "r");
#else
file = fopen(filename, "r");
#endif
if (file)
{
fclose(file);
return NV_FLOW_TRUE;
}
return NV_FLOW_FALSE;
}
void NvFlowTextFileRemove(const char* name)
{
remove(name);
}
void NvFlowTextFileRename(const char* oldName, const char* newName)
{
rename(oldName, newName);
}
NvFlowBool32 NvFlowTextFileDiffAndWriteIfModified(const char* filenameDst, const char* filenameTmp)
{
FILE* fileTmp = nullptr;
FILE* fileDst = nullptr;
bool match = true;
#if defined(_WIN32)
fopen_s(&fileDst, filenameDst, "r");
#else
fileDst = fopen(filenameDst, "r");
#endif
if (fileDst)
{
#if defined(_WIN32)
fopen_s(&fileTmp, filenameTmp, "r");
#else
fileTmp = fopen(filenameTmp, "r");
#endif
if (fileTmp)
{
while (1)
{
int a = fgetc(fileTmp);
int b = fgetc(fileDst);
if (a == EOF && b == EOF)
{
break;
}
else if (a != b)
{
match = false;
break;
}
}
fclose(fileTmp);
}
else
{
match = false;
}
fclose(fileDst);
}
else
{
match = false;
}
if (!match)
{
remove(filenameDst);
rename(filenameTmp, filenameDst);
}
// always cleanup temp file
remove(filenameTmp);
return !match;
}
|
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowArrayBuffer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowUploadBuffer.h"
#include <string.h>
struct NvFlowArrayBufferData
{
const void* data;
NvFlowUint64 elementCount;
NvFlowUint64 version;
};
struct NvFlowArrayBufferState
{
NvFlowBool32 isDirty;
NvFlowUint64 elementCount;
NvFlowUint64 version;
NvFlowUint64 firstElement;
};
struct NvFlowArrayBuffer
{
NvFlowUploadBuffer uploadBuffer = {};
NvFlowArray<NvFlowArrayBufferState> state;
NvFlowArray<NvFlowUploadBufferCopyRange> copyRanges;
NvFlowUint64 totalSizeInBytes = 0llu;
};
NV_FLOW_INLINE void NvFlowArrayBuffer_init_custom(
NvFlowContextInterface* contextInterface,
NvFlowContext* context,
NvFlowArrayBuffer* ptr,
NvFlowBufferUsageFlags flags,
NvFlowFormat format,
NvFlowUint structureStride,
NvFlowBuffer*(NV_FLOW_ABI* createBuffer)(NvFlowContext* context, NvFlowMemoryType memoryType, const NvFlowBufferDesc* desc, void* userdata),
void(NV_FLOW_ABI* addPassCopyBuffer)(NvFlowContext* context, const NvFlowPassCopyBufferParams* params, void* userdata),
void* userdata
)
{
NvFlowUploadBuffer_init_custom(contextInterface, context, &ptr->uploadBuffer, flags, format, structureStride, createBuffer, addPassCopyBuffer, userdata);
}
NV_FLOW_INLINE NvFlowBuffer* NvFlowArrayBuffer_createBuffer(NvFlowContext* context, NvFlowMemoryType memoryType, const NvFlowBufferDesc* desc, void* userdata)
{
NvFlowArrayBuffer* ptr = (NvFlowArrayBuffer*)userdata;
return ptr->uploadBuffer.contextInterface->createBuffer(context, memoryType, desc);
}
NV_FLOW_INLINE void NvFlowArrayBuffer_addPassCopyBuffer(NvFlowContext* context, const NvFlowPassCopyBufferParams* params, void* userdata)
{
NvFlowArrayBuffer* ptr = (NvFlowArrayBuffer*)userdata;
ptr->uploadBuffer.contextInterface->addPassCopyBuffer(context, params);
}
NV_FLOW_INLINE void NvFlowArrayBuffer_init(NvFlowContextInterface* contextInterface, NvFlowContext* context, NvFlowArrayBuffer* ptr, NvFlowBufferUsageFlags flags, NvFlowFormat format, NvFlowUint structureStride)
{
NvFlowArrayBuffer_init_custom(contextInterface, context, ptr, flags, format, structureStride, NvFlowArrayBuffer_createBuffer, NvFlowArrayBuffer_addPassCopyBuffer, ptr);
}
NV_FLOW_INLINE void NvFlowArrayBuffer_destroy(NvFlowContext* context, NvFlowArrayBuffer* ptr)
{
NvFlowUploadBuffer_destroy(context, &ptr->uploadBuffer);
ptr->state.size = 0u;
ptr->copyRanges.size = 0u;
}
NV_FLOW_INLINE NvFlowBufferTransient* NvFlowArrayBuffer_update(
NvFlowContext* context,
NvFlowArrayBuffer* ptr,
const NvFlowArrayBufferData* arrayDatas,
NvFlowUint64* outFirstElements,
NvFlowUint64 arrayCount,
NvFlowUint64* outTotalSizeInBytes,
const char* debugName
)
{
// if arrayCount changes, reset all state
bool shouldResetState = false;
if (ptr->state.size != arrayCount)
{
shouldResetState = true;
}
// if any array size changes, reset all state, since buffer resize might occur
if (!shouldResetState)
{
for (NvFlowUint64 arrayIdx = 0u; arrayIdx < arrayCount; arrayIdx++)
{
if (ptr->state[arrayIdx].elementCount != arrayDatas[arrayIdx].elementCount)
{
shouldResetState = true;
}
}
}
if (shouldResetState)
{
ptr->state.reserve(arrayCount);
ptr->state.size = arrayCount;
for (NvFlowUint64 arrayIdx = 0u; arrayIdx < arrayCount; arrayIdx++)
{
ptr->state[arrayIdx].isDirty = NV_FLOW_TRUE;
ptr->state[arrayIdx].elementCount = 0llu;
ptr->state[arrayIdx].version = 0llu;
ptr->state[arrayIdx].firstElement = 0llu;
}
}
// mark any array dirty if version changes
for (NvFlowUint64 arrayIdx = 0u; arrayIdx < arrayCount; arrayIdx++)
{
if (arrayDatas[arrayIdx].elementCount != 0u || ptr->state[arrayIdx].elementCount != 0u)
{
if (arrayDatas[arrayIdx].version == 0llu || arrayDatas[arrayIdx].version != ptr->state[arrayIdx].version)
{
ptr->state[arrayIdx].isDirty = NV_FLOW_TRUE;
}
}
}
NvFlowBool32 anyDirty = NV_FLOW_FALSE;
for (NvFlowUint64 arrayIdx = 0u; arrayIdx < arrayCount; arrayIdx++)
{
if (ptr->state[arrayIdx].isDirty)
{
anyDirty = NV_FLOW_TRUE;
}
}
// compute total size
NvFlowUint64 totalSizeInBytes = 0llu;
for (NvFlowUint arrayIdx = 0u; arrayIdx < arrayCount; arrayIdx++)
{
totalSizeInBytes += ptr->uploadBuffer.structureStride * arrayDatas[arrayIdx].elementCount;
}
NvFlowUint8* mapped = nullptr;
if (anyDirty)
{
mapped = (NvFlowUint8*)NvFlowUploadBuffer_map(context, &ptr->uploadBuffer, totalSizeInBytes);
}
// update state
NvFlowUint64 globalFirstElement = 0llu;
for (NvFlowUint arrayIdx = 0u; arrayIdx < arrayCount; arrayIdx++)
{
ptr->state[arrayIdx].elementCount = arrayDatas[arrayIdx].elementCount;
ptr->state[arrayIdx].version = arrayDatas[arrayIdx].version;
ptr->state[arrayIdx].firstElement = globalFirstElement;
globalFirstElement += ptr->state[arrayIdx].elementCount;
}
ptr->copyRanges.size = 0u;
for (NvFlowUint arrayIdx = 0u; arrayIdx < arrayCount; arrayIdx++)
{
if (ptr->state[arrayIdx].isDirty)
{
NvFlowUint64 offsetInBytes = ptr->uploadBuffer.structureStride * ptr->state[arrayIdx].firstElement;
NvFlowUint64 sizeInBytes = ptr->uploadBuffer.structureStride * ptr->state[arrayIdx].elementCount;
// copy to host memory
memcpy(mapped + offsetInBytes, arrayDatas[arrayIdx].data, sizeInBytes);
// add copy range
NvFlowUploadBufferCopyRange copyRange = { offsetInBytes, sizeInBytes };
ptr->copyRanges.pushBack(copyRange);
}
}
NvFlowBufferTransient* bufferTransient = nullptr;
if (anyDirty)
{
bufferTransient = NvFlowUploadBuffer_unmapDeviceN(context, &ptr->uploadBuffer, ptr->copyRanges.data, ptr->copyRanges.size, debugName);
}
else
{
bufferTransient = NvFlowUploadBuffer_getDevice(context, &ptr->uploadBuffer, totalSizeInBytes);
}
// mark all arrays as clean
for (NvFlowUint arrayIdx = 0u; arrayIdx < arrayCount; arrayIdx++)
{
ptr->state[arrayIdx].isDirty = NV_FLOW_FALSE;
}
if (outFirstElements)
{
for (NvFlowUint arrayIdx = 0u; arrayIdx < arrayCount; arrayIdx++)
{
outFirstElements[arrayIdx] = ptr->state[arrayIdx].firstElement;
}
}
ptr->totalSizeInBytes = totalSizeInBytes;
if (outTotalSizeInBytes)
{
*outTotalSizeInBytes = totalSizeInBytes;
}
return bufferTransient;
}
|
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowArray.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#define NV_FLOW_ARRAY_CACHE_ENABLED 1
#include <new>
#include <utility>
template<class T, NvFlowUint64 staticCapacity = 0u, void(prerelease)(void* data, NvFlowUint64 size) = nullptr>
struct NvFlowArray
{
#if NV_FLOW_ARRAY_CACHE_ENABLED
static const NvFlowUint64 s_staticCapacity = staticCapacity;
#else
static const NvFlowUint64 s_staticCapacity = 0u;
#endif
T* data = nullptr;
NvFlowUint64 capacity = 0u;
NvFlowUint64 size = 0u;
unsigned char cache[s_staticCapacity * sizeof(T) + 8u];
void release()
{
for (NvFlowUint64 i = 0; i < capacity; i++)
{
data[i].~T();
}
if (data != nullptr && (T*)cache != data)
{
operator delete[](data);
}
data = nullptr;
capacity = 0u;
size = 0u;
}
void move(NvFlowArray& rhs)
{
data = rhs.data;
capacity = rhs.capacity;
size = rhs.size;
if (rhs.data == (T*)rhs.cache)
{
data = (T*)cache;
for (NvFlowUint64 idx = 0u; idx < capacity; idx++)
{
new(data + idx) T(std::move(rhs.data[idx]));
}
}
// to match destructed state
rhs.data = nullptr;
rhs.capacity = 0u;
rhs.size = 0u;
}
void reserve(NvFlowUint64 requestedCapacity)
{
if (requestedCapacity <= capacity)
{
return;
}
NvFlowUint64 newSize = size;
NvFlowUint64 newCapacity = capacity;
if (newCapacity < s_staticCapacity)
{
newCapacity = s_staticCapacity;
}
if (newCapacity == 0u)
{
newCapacity = 1u;
}
while (newCapacity < requestedCapacity)
{
newCapacity *= 2u;
}
T* newData = (T*)(newCapacity <= s_staticCapacity ? (void*)cache : operator new[](newCapacity * sizeof(T)));
// copy to new
for (NvFlowUint64 i = 0; i < newSize; i++)
{
new(newData + i) T(std::move(data[i]));
}
for (NvFlowUint64 i = newSize; i < newCapacity; i++)
{
new(newData + i) T();
}
if (prerelease)
{
prerelease(data + size, capacity - size);
}
// cleanup old
release();
// commit new
data = newData;
capacity = newCapacity;
size = newSize;
}
NvFlowArray()
{
reserve(s_staticCapacity);
}
NvFlowArray(NvFlowArray&& rhs)
{
move(rhs);
}
~NvFlowArray()
{
if (prerelease)
{
prerelease(data, capacity);
}
release();
}
T& operator[](NvFlowUint64 idx)
{
return data[idx];
}
const T& operator[](NvFlowUint64 idx) const
{
return data[idx];
}
NvFlowUint64 allocateBack()
{
reserve(size + 1);
size++;
return size - 1;
}
void pushBack(const T& v)
{
operator[](allocateBack()) = v;
}
T& back()
{
return operator[](size - 1);
}
void popBack()
{
size--;
}
};
/// Copy utility
template <class T, NvFlowUint64 staticCapacity = 0u, void(prerelease)(void* data, NvFlowUint64 size) = nullptr>
NV_FLOW_INLINE void NvFlowArray_copy(NvFlowArray<T, staticCapacity, prerelease>& dst, const NvFlowArray<T, staticCapacity, prerelease>& src)
{
dst.size = 0u;
dst.reserve(src.size);
dst.size = src.size;
for (NvFlowUint64 idx = 0u; idx < dst.size; idx++)
{
dst[idx] = src[idx];
}
}
template<class T>
NV_FLOW_INLINE void NvFlowArrayPointer_prerelease(void* dataIn, NvFlowUint64 size)
{
T* data = (T*)dataIn;
for (NvFlowUint64 idx = 0u; idx < size; idx++)
{
if (data[idx])
{
delete data[idx];
data[idx] = nullptr;
}
}
}
template<class T>
NV_FLOW_INLINE void NvFlowArrayPointer_allocate(T*& ptr)
{
ptr = new T();
}
template<class T, NvFlowUint64 staticCapacity = 0u>
struct NvFlowArrayPointer : public NvFlowArray<T, staticCapacity, NvFlowArrayPointer_prerelease<T>>
{
NvFlowArrayPointer() : NvFlowArray<T, staticCapacity, NvFlowArrayPointer_prerelease<T>>()
{
}
NvFlowArrayPointer(NvFlowArrayPointer&& rhs) : NvFlowArray<T, staticCapacity, NvFlowArrayPointer_prerelease<T>>(std::move(rhs))
{
}
~NvFlowArrayPointer()
{
}
T allocateBackPointer()
{
NvFlowUint64 allocIdx = this->allocateBack();
if (!(*this)[allocIdx])
{
NvFlowArrayPointer_allocate((*this)[allocIdx]);
}
return (*this)[allocIdx];
}
void pushBackPointer(const T& v)
{
NvFlowUint64 allocIdx = this->allocateBack();
deletePointerAtIndex(allocIdx);
(*this)[allocIdx] = v;
}
void swapPointers(NvFlowUint64 idxA, NvFlowUint64 idxB)
{
T temp = (*this)[idxA];
(*this)[idxA] = (*this)[idxB];
(*this)[idxB] = temp;
}
void removeSwapPointerAtIndex(NvFlowUint64 idx)
{
swapPointers(idx, this->size - 1u);
this->size--;
}
void removeSwapPointer(T ptr)
{
for (NvFlowUint64 idx = 0u; idx < this->size; idx++)
{
if ((*this)[idx] == ptr)
{
removeSwapPointerAtIndex(idx);
break;
}
}
}
void deletePointerAtIndex(NvFlowUint64 idx)
{
if ((*this)[idx])
{
delete (*this)[idx];
(*this)[idx] = nullptr;
}
}
void deletePointers()
{
this->size = this->capacity;
for (NvFlowUint64 idx = 0u; idx < this->size; idx++)
{
deletePointerAtIndex(idx);
}
this->size = 0u;
}
};
template<class T, NvFlowUint64 staticCapacity = 0u>
struct NvFlowRingBufferPointer
{
NvFlowArrayPointer<T, staticCapacity> arr;
NvFlowUint64 freeIdx = 0u;
NvFlowUint64 frontIdx = 0u;
NvFlowUint64 backIdx = 0u;
NvFlowRingBufferPointer() : arr()
{
}
NvFlowRingBufferPointer(NvFlowRingBufferPointer&& rhs) :
arr(std::move(rhs.arr)),
freeIdx(rhs.freeIdx),
frontIdx(rhs.frontIdx),
backIdx(rhs.backIdx)
{
}
~NvFlowRingBufferPointer()
{
}
T& front()
{
return arr[frontIdx];
}
T& back()
{
return arr[(backIdx - 1u) & (arr.size - 1)];
}
NvFlowUint64 activeCount()
{
return (backIdx - frontIdx) & (arr.size - 1);
}
NvFlowUint64 freeCount()
{
return (frontIdx - freeIdx) & (arr.size - 1);
}
void popFront()
{
frontIdx = (frontIdx + 1u) & (arr.size - 1);
}
void popFree()
{
freeIdx = (freeIdx + 1u) & (arr.size - 1);
}
T& operator[](NvFlowUint64 idx)
{
return arr[(frontIdx + idx) & (arr.size - 1)];
}
const T& operator[](NvFlowUint64 idx) const
{
return arr[(frontIdx + idx) & (arr.size - 1)];
}
NvFlowUint64 allocateBack()
{
if (arr.size == 0u)
{
arr.allocateBack();
}
if (freeCount() > 0u)
{
auto tmp = arr[freeIdx];
arr[freeIdx] = arr[backIdx];
arr[backIdx] = tmp;
popFree();
}
else if ((activeCount() + 1u) > (arr.size - 1))
{
NvFlowUint64 oldSize = arr.size;
arr.reserve(2u * oldSize);
arr.size = 2u * oldSize;
if (backIdx < frontIdx)
{
for (NvFlowUint64 idx = 0u; idx < backIdx; idx++)
{
auto tmp = arr[idx + oldSize];
arr[idx + oldSize] = arr[idx];
arr[idx] = tmp;
}
backIdx += oldSize;
}
}
NvFlowUint64 allocIdx = backIdx;
backIdx = (backIdx + 1u) & (arr.size - 1);
return allocIdx;
}
void pushBack(const T& v)
{
NvFlowUint64 allocIdx = allocateBack();
arr.deletePointerAtIndex(allocIdx);
arr[allocIdx] = v;
}
T allocateBackPointer()
{
NvFlowUint64 allocIdx = allocateBack();
if (!arr[allocIdx])
{
NvFlowArrayPointer_allocate(arr[allocIdx]);
}
return arr[allocIdx];
}
void deletePointers()
{
arr.deletePointers();
}
}; |
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowResourceCPU.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
// Workaround to scope includes per shader
#ifdef NV_FLOW_CPU_SHADER
#undef NV_FLOW_SHADER_TYPES_H
#undef NV_FLOW_SHADER_HLSLI
#undef NV_FLOW_RAY_MARCH_PARAMS_H
#undef NV_FLOW_RAY_MARCH_HLSLI
#undef NV_FLOW_RAY_MARCH_COMMON_HLSLI
#endif
// Disabled by default, to save build time
#define NV_FLOW_CPU_SHADER_DISABLE
#ifndef NV_FLOW_RESOURCE_CPU_H
#define NV_FLOW_RESOURCE_CPU_H
#include "NvFlowContext.h"
#include <math.h>
#include <atomic>
#include <string.h>
typedef NvFlowUint NvFlowCPU_Uint;
struct NvFlowCPU_Float2;
struct NvFlowCPU_Float3;
struct NvFlowCPU_Float4;
struct NvFlowCPU_Float4x4;
struct NvFlowCPU_Int2;
struct NvFlowCPU_Int3;
struct NvFlowCPU_Int4;
struct NvFlowCPU_Uint2;
struct NvFlowCPU_Uint3;
struct NvFlowCPU_Uint4;
NV_FLOW_INLINE int NvFlowCPU_max(int a, int b)
{
return a > b ? a : b;
}
NV_FLOW_INLINE int NvFlowCPU_min(int a, int b)
{
return a < b ? a : b;
}
NV_FLOW_INLINE float NvFlowCPU_round(float v)
{
return roundf(v);
}
NV_FLOW_INLINE float NvFlowCPU_abs(float v)
{
return fabsf(v);
}
NV_FLOW_INLINE float NvFlowCPU_floor(float v)
{
return floorf(v);
}
NV_FLOW_INLINE int NvFlowCPU_abs(int v)
{
return v < 0 ? -v : v;
}
NV_FLOW_INLINE float NvFlowCPU_sqrt(float v)
{
return sqrtf(v);
}
NV_FLOW_INLINE float NvFlowCPU_exp(float v)
{
return expf(v);
}
NV_FLOW_INLINE float NvFlowCPU_pow(float a, float b)
{
return powf(a, b);
}
NV_FLOW_INLINE float NvFlowCPU_log2(float v)
{
return log2f(v);
}
NV_FLOW_INLINE float NvFlowCPU_min(float a, float b)
{
//return fminf(a, b);
return a < b ? a : b;
}
NV_FLOW_INLINE float NvFlowCPU_max(float a, float b)
{
//return fmaxf(a, b);
return a > b ? a : b;
}
NV_FLOW_INLINE float NvFlowCPU_clamp(float v, float min, float max)
{
return NvFlowCPU_max(min, NvFlowCPU_min(v, max));
}
struct NvFlowCPU_Float2
{
float x, y;
NvFlowCPU_Float2() {}
NvFlowCPU_Float2(float x, float y) : x(x), y(y) {}
NV_FLOW_INLINE NvFlowCPU_Float2(const NvFlowCPU_Int2& rhs);
NvFlowCPU_Float2 operator+(const NvFlowCPU_Float2& rhs) const { return NvFlowCPU_Float2(x + rhs.x, y + rhs.y); }
NvFlowCPU_Float2 operator-(const NvFlowCPU_Float2& rhs) const { return NvFlowCPU_Float2(x - rhs.x, y - rhs.y); }
NvFlowCPU_Float2 operator*(const NvFlowCPU_Float2& rhs) const { return NvFlowCPU_Float2(x * rhs.x, y * rhs.y); }
NvFlowCPU_Float2 operator/(const NvFlowCPU_Float2& rhs) const { return NvFlowCPU_Float2(x / rhs.x, y / rhs.y); }
NvFlowCPU_Float2 operator+(const float& rhs) const { return NvFlowCPU_Float2(x + rhs, y + rhs); }
NvFlowCPU_Float2 operator-(const float& rhs) const { return NvFlowCPU_Float2(x - rhs, y - rhs); }
NvFlowCPU_Float2 operator*(const float& rhs) const { return NvFlowCPU_Float2(x * rhs, y * rhs); }
NvFlowCPU_Float2 operator/(const float& rhs) const { return NvFlowCPU_Float2(x / rhs, y / rhs); }
NvFlowCPU_Float2& operator+=(const NvFlowCPU_Float2& rhs) { x += rhs.x; y += rhs.y; return *this; }
NvFlowCPU_Float2& operator-=(const NvFlowCPU_Float2& rhs) { x -= rhs.x; y -= rhs.y; return *this; }
NvFlowCPU_Float2& operator*=(const NvFlowCPU_Float2& rhs) { x *= rhs.x; y *= rhs.y; return *this; }
NvFlowCPU_Float2& operator/=(const NvFlowCPU_Float2& rhs) { x /= rhs.x; y /= rhs.y; return *this; }
NvFlowCPU_Float2& operator+=(const float& rhs) { x += rhs; y += rhs; return *this; }
NvFlowCPU_Float2& operator-=(const float& rhs) { x -= rhs; y -= rhs; return *this; }
NvFlowCPU_Float2& operator*=(const float& rhs) { x *= rhs; y *= rhs; return *this; }
NvFlowCPU_Float2& operator/=(const float& rhs) { x /= rhs; y /= rhs; return *this; }
NvFlowCPU_Float2 operator+() const { return NvFlowCPU_Float2(+x, +y); }
NvFlowCPU_Float2 operator-() const { return NvFlowCPU_Float2(-x, -y); }
};
NV_FLOW_INLINE NvFlowCPU_Float2 operator+(const float& lhs, const NvFlowCPU_Float2& rhs) { return NvFlowCPU_Float2(lhs + rhs.x, lhs + rhs.y); }
NV_FLOW_INLINE NvFlowCPU_Float2 operator-(const float& lhs, const NvFlowCPU_Float2& rhs) { return NvFlowCPU_Float2(lhs - rhs.x, lhs - rhs.y); }
NV_FLOW_INLINE NvFlowCPU_Float2 operator*(const float& lhs, const NvFlowCPU_Float2& rhs) { return NvFlowCPU_Float2(lhs * rhs.x, lhs * rhs.y); }
NV_FLOW_INLINE NvFlowCPU_Float2 operator/(const float& lhs, const NvFlowCPU_Float2& rhs) { return NvFlowCPU_Float2(lhs / rhs.x, lhs / rhs.y); }
NV_FLOW_INLINE NvFlowCPU_Float2 NvFlowCPU_floor(NvFlowCPU_Float2 v)
{
return NvFlowCPU_Float2(floorf(v.x), floorf(v.y));
}
struct NvFlowCPU_Float3
{
float x, y, z;
NvFlowCPU_Float3() {}
NvFlowCPU_Float3(float x, float y, float z) : x(x), y(y), z(z) {}
NV_FLOW_INLINE NvFlowCPU_Float3(const NvFlowCPU_Int3& v);
NvFlowCPU_Float3 operator+(const NvFlowCPU_Float3& rhs) const { return NvFlowCPU_Float3(x + rhs.x, y + rhs.y, z + rhs.z); }
NvFlowCPU_Float3 operator-(const NvFlowCPU_Float3& rhs) const { return NvFlowCPU_Float3(x - rhs.x, y - rhs.y, z - rhs.z); }
NvFlowCPU_Float3 operator*(const NvFlowCPU_Float3& rhs) const { return NvFlowCPU_Float3(x * rhs.x, y * rhs.y, z * rhs.z); }
NvFlowCPU_Float3 operator/(const NvFlowCPU_Float3& rhs) const { return NvFlowCPU_Float3(x / rhs.x, y / rhs.y, z / rhs.z); }
NvFlowCPU_Float3 operator+(const float& rhs) const { return NvFlowCPU_Float3(x + rhs, y + rhs, z + rhs); }
NvFlowCPU_Float3 operator-(const float& rhs) const { return NvFlowCPU_Float3(x - rhs, y - rhs, z - rhs); }
NvFlowCPU_Float3 operator*(const float& rhs) const { return NvFlowCPU_Float3(x * rhs, y * rhs, z * rhs); }
NvFlowCPU_Float3 operator/(const float& rhs) const { return NvFlowCPU_Float3(x / rhs, y / rhs, z / rhs); }
NvFlowCPU_Float3& operator+=(const NvFlowCPU_Float3& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; }
NvFlowCPU_Float3& operator-=(const NvFlowCPU_Float3& rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; }
NvFlowCPU_Float3& operator*=(const NvFlowCPU_Float3& rhs) { x *= rhs.x; y *= rhs.y; z *= rhs.z; return *this; }
NvFlowCPU_Float3& operator/=(const NvFlowCPU_Float3& rhs) { x /= rhs.x; y /= rhs.y; z /= rhs.z; return *this; }
NvFlowCPU_Float3& operator+=(const float& rhs) { x += rhs; y += rhs; z += rhs; return *this; }
NvFlowCPU_Float3& operator-=(const float& rhs) { x -= rhs; y -= rhs; z -= rhs; return *this; }
NvFlowCPU_Float3& operator*=(const float& rhs) { x *= rhs; y *= rhs; z *= rhs; return *this; }
NvFlowCPU_Float3& operator/=(const float& rhs) { x /= rhs; y /= rhs; z /= rhs; return *this; }
NvFlowCPU_Float3 operator+() const { return NvFlowCPU_Float3(+x, +y, +z); }
NvFlowCPU_Float3 operator-() const { return NvFlowCPU_Float3(-x, -y, -z); }
};
NV_FLOW_INLINE NvFlowCPU_Float3 operator*(const float& lhs, const NvFlowCPU_Float3& rhs) { return NvFlowCPU_Float3(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Float3 NvFlowCPU_abs(NvFlowCPU_Float3 v)
{
return NvFlowCPU_Float3(fabsf(v.x), fabsf(v.y), fabsf(v.z));
}
NV_FLOW_INLINE NvFlowCPU_Float3 NvFlowCPU_floor(NvFlowCPU_Float3 v)
{
return NvFlowCPU_Float3(floorf(v.x), floorf(v.y), floorf(v.z));
}
NV_FLOW_INLINE float NvFlowCPU_length(NvFlowCPU_Float3 v)
{
return sqrtf(v.x * v.x + v.y * v.y + v.z * v.z);
}
NV_FLOW_INLINE NvFlowCPU_Float3 NvFlowCPU_max(NvFlowCPU_Float3 a, NvFlowCPU_Float3 b)
{
return NvFlowCPU_Float3(NvFlowCPU_max(a.x, b.x), NvFlowCPU_max(a.y, b.y), NvFlowCPU_max(a.z, b.z));
}
NV_FLOW_INLINE NvFlowCPU_Float3 NvFlowCPU_min(NvFlowCPU_Float3 a, NvFlowCPU_Float3 b)
{
return NvFlowCPU_Float3(NvFlowCPU_min(a.x, b.x), NvFlowCPU_min(a.y, b.y), NvFlowCPU_min(a.z, b.z));
}
NV_FLOW_INLINE float NvFlowCPU_dot(NvFlowCPU_Float3 a, NvFlowCPU_Float3 b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
NV_FLOW_INLINE NvFlowCPU_Float3 NvFlowCPU_normalize(NvFlowCPU_Float3 v)
{
float length = NvFlowCPU_length(v);
if (length > 0.f)
{
v /= length;
}
return v;
}
struct NvFlowCPU_Float4
{
float x, y, z, w;
NvFlowCPU_Float4() {}
NvFlowCPU_Float4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {}
NvFlowCPU_Float4(const NvFlowCPU_Float3& rhs, float w) : x(rhs.x), y(rhs.y), z(rhs.z), w(w) {}
NvFlowCPU_Float3& rgb() { return *((NvFlowCPU_Float3*)this); }
NvFlowCPU_Float2& rg() { return *((NvFlowCPU_Float2*)this); }
float& r() { return *((float*)this); }
NvFlowCPU_Float2& ba() { return *((NvFlowCPU_Float2*)&z); }
const NvFlowCPU_Float3& rgb() const { return *((const NvFlowCPU_Float3*)this); }
const NvFlowCPU_Float2& rg() const { return *((const NvFlowCPU_Float2*)this); }
const float& r() const { return *((const float*)this); }
const NvFlowCPU_Float2& ba() const { return *((const NvFlowCPU_Float2*)&z); }
NvFlowCPU_Float4 operator+(const NvFlowCPU_Float4& rhs) const { return NvFlowCPU_Float4(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w); }
NvFlowCPU_Float4 operator-(const NvFlowCPU_Float4& rhs) const { return NvFlowCPU_Float4(x - rhs.x, y - rhs.y, z - rhs.z, w - rhs.w); }
NvFlowCPU_Float4 operator*(const NvFlowCPU_Float4& rhs) const { return NvFlowCPU_Float4(x * rhs.x, y * rhs.y, z * rhs.z, w * rhs.w); }
NvFlowCPU_Float4 operator/(const NvFlowCPU_Float4& rhs) const { return NvFlowCPU_Float4(x / rhs.x, y / rhs.y, z / rhs.z, w / rhs.w); }
NvFlowCPU_Float4 operator+(const float& rhs) const { return NvFlowCPU_Float4(x + rhs, y + rhs, z + rhs, w + rhs); }
NvFlowCPU_Float4 operator-(const float& rhs) const { return NvFlowCPU_Float4(x - rhs, y - rhs, z - rhs, w - rhs); }
NvFlowCPU_Float4 operator*(const float& rhs) const { return NvFlowCPU_Float4(x * rhs, y * rhs, z * rhs, w * rhs); }
NvFlowCPU_Float4 operator/(const float& rhs) const { return NvFlowCPU_Float4(x / rhs, y / rhs, z / rhs, w / rhs); }
NvFlowCPU_Float4& operator+=(const NvFlowCPU_Float4& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; w += rhs.w; return *this; }
NvFlowCPU_Float4& operator-=(const NvFlowCPU_Float4& rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; w -= rhs.w; return *this; }
NvFlowCPU_Float4& operator*=(const NvFlowCPU_Float4& rhs) { x *= rhs.x; y *= rhs.y; z *= rhs.z; w *= rhs.w; return *this; }
NvFlowCPU_Float4& operator/=(const NvFlowCPU_Float4& rhs) { x /= rhs.x; y /= rhs.y; z /= rhs.z; w /= rhs.w; return *this; }
NvFlowCPU_Float4& operator*=(const float& rhs) { x *= rhs; y *= rhs; z *= rhs; w *= rhs; return *this; }
};
NV_FLOW_INLINE NvFlowCPU_Float4 operator*(const float& lhs, const NvFlowCPU_Float4& rhs) { return NvFlowCPU_Float4(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z, lhs * rhs.w); }
NV_FLOW_INLINE float NvFlowCPU_dot(NvFlowCPU_Float4 a, NvFlowCPU_Float4 b)
{
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
NV_FLOW_INLINE NvFlowCPU_Float4 NvFlowCPU_max(NvFlowCPU_Float4 a, NvFlowCPU_Float4 b)
{
return NvFlowCPU_Float4(NvFlowCPU_max(a.x, b.x), NvFlowCPU_max(a.y, b.y), NvFlowCPU_max(a.z, b.z), NvFlowCPU_max(a.w, b.w));
}
NV_FLOW_INLINE NvFlowCPU_Float4 NvFlowCPU_min(NvFlowCPU_Float4 a, NvFlowCPU_Float4 b)
{
return NvFlowCPU_Float4(NvFlowCPU_min(a.x, b.x), NvFlowCPU_min(a.y, b.y), NvFlowCPU_min(a.z, b.z), NvFlowCPU_min(a.w, b.w));
}
NV_FLOW_INLINE NvFlowCPU_Float4 NvFlowCPU_sign(NvFlowCPU_Float4 v)
{
return NvFlowCPU_Float4(
v.x == 0.f ? 0.f : (v.x < 0.f ? -1.f : +1.f),
v.y == 0.f ? 0.f : (v.y < 0.f ? -1.f : +1.f),
v.z == 0.f ? 0.f : (v.z < 0.f ? -1.f : +1.f),
v.w == 0.f ? 0.f : (v.w < 0.f ? -1.f : +1.f)
);
}
NV_FLOW_INLINE NvFlowCPU_Float4 NvFlowCPU_abs(NvFlowCPU_Float4 v)
{
return NvFlowCPU_Float4(fabsf(v.x), fabsf(v.y), fabsf(v.z), fabsf(v.w));
}
struct NvFlowCPU_Float4x4
{
NvFlowCPU_Float4 x, y, z, w;
NvFlowCPU_Float4x4() {}
NvFlowCPU_Float4x4(const NvFlowCPU_Float4& x, const NvFlowCPU_Float4& y, const NvFlowCPU_Float4& z, const NvFlowCPU_Float4& w) : x(x), y(y), z(z), w(w) {}
};
NV_FLOW_INLINE NvFlowCPU_Float4 NvFlowCPU_mul(const NvFlowCPU_Float4& x, const NvFlowCPU_Float4x4 A)
{
return NvFlowCPU_Float4(
{ A.x.x * x.x + A.x.y * x.y + A.x.z * x.z + A.x.w * x.w },
{ A.y.x * x.x + A.y.y * x.y + A.y.z * x.z + A.y.w * x.w },
{ A.z.x * x.x + A.z.y * x.y + A.z.z * x.z + A.z.w * x.w },
{ A.w.x * x.x + A.w.y * x.y + A.w.z * x.z + A.w.w * x.w }
);
}
struct NvFlowCPU_Int2
{
int x, y;
NvFlowCPU_Int2() {}
NvFlowCPU_Int2(int x, int y) : x(x), y(y) {}
NvFlowCPU_Int2(const NvFlowCPU_Float2& rhs) : x(int(rhs.x)), y(int(rhs.y)) {}
NV_FLOW_INLINE NvFlowCPU_Int2(const NvFlowCPU_Uint2& rhs);
NvFlowCPU_Int2 operator+(const NvFlowCPU_Int2& rhs) const { return NvFlowCPU_Int2(x + rhs.x, y + rhs.y); }
NvFlowCPU_Int2 operator-(const NvFlowCPU_Int2& rhs) const { return NvFlowCPU_Int2(x - rhs.x, y - rhs.y); }
NvFlowCPU_Int2 operator*(const NvFlowCPU_Int2& rhs) const { return NvFlowCPU_Int2(x * rhs.x, y * rhs.y); }
NvFlowCPU_Int2 operator/(const NvFlowCPU_Int2& rhs) const { return NvFlowCPU_Int2(x / rhs.x, y / rhs.y); }
NvFlowCPU_Int2 operator+(const int& rhs) const { return NvFlowCPU_Int2(x + rhs, y + rhs); }
NvFlowCPU_Int2 operator-(const int& rhs) const { return NvFlowCPU_Int2(x - rhs, y - rhs); }
NvFlowCPU_Int2 operator*(const int& rhs) const { return NvFlowCPU_Int2(x * rhs, y * rhs); }
NvFlowCPU_Int2 operator/(const int& rhs) const { return NvFlowCPU_Int2(x / rhs, y / rhs); }
};
NV_FLOW_INLINE NvFlowCPU_Float2::NvFlowCPU_Float2(const NvFlowCPU_Int2& rhs) : x(float(rhs.x)), y(float(rhs.y)) {}
NV_FLOW_INLINE NvFlowCPU_Int2 NvFlowCPU_max(NvFlowCPU_Int2 a, NvFlowCPU_Int2 b)
{
return NvFlowCPU_Int2(NvFlowCPU_max(a.x, b.x), NvFlowCPU_max(a.y, b.y));
}
NV_FLOW_INLINE NvFlowCPU_Int2 NvFlowCPU_min(NvFlowCPU_Int2 a, NvFlowCPU_Int2 b)
{
return NvFlowCPU_Int2(NvFlowCPU_min(a.x, b.x), NvFlowCPU_min(a.y, b.y));
}
struct NvFlowCPU_Int3
{
int x, y, z;
NvFlowCPU_Int3() {}
NvFlowCPU_Int3(int x, int y, int z) : x(x), y(y), z(z) {}
NV_FLOW_INLINE NvFlowCPU_Int3(const NvFlowCPU_Uint3& v);
NV_FLOW_INLINE NvFlowCPU_Int3(const NvFlowCPU_Float3& v);
NvFlowCPU_Int2& rg() { return *((NvFlowCPU_Int2*)this); }
int& r() { return *((int*)this); }
NvFlowCPU_Int3 operator+(const NvFlowCPU_Int3& rhs) const { return NvFlowCPU_Int3(x + rhs.x, y + rhs.y, z + rhs.z); }
NvFlowCPU_Int3 operator-(const NvFlowCPU_Int3& rhs) const { return NvFlowCPU_Int3(x - rhs.x, y - rhs.y, z - rhs.z); }
NvFlowCPU_Int3 operator*(const NvFlowCPU_Int3& rhs) const { return NvFlowCPU_Int3(x * rhs.x, y * rhs.y, z * rhs.z); }
NvFlowCPU_Int3 operator/(const NvFlowCPU_Int3& rhs) const { return NvFlowCPU_Int3(x / rhs.x, y / rhs.y, z / rhs.z); }
NvFlowCPU_Int3& operator+=(const NvFlowCPU_Int3& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; }
NvFlowCPU_Int3& operator-=(const NvFlowCPU_Int3& rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; }
NvFlowCPU_Int3& operator*=(const NvFlowCPU_Int3& rhs) { x *= rhs.x; y *= rhs.y; z *= rhs.z; return *this; }
NvFlowCPU_Int3& operator/=(const NvFlowCPU_Int3& rhs) { x /= rhs.x; y /= rhs.y; z /= rhs.z; return *this; }
NV_FLOW_INLINE NvFlowCPU_Int3 operator>>(const NvFlowCPU_Int3& rhs) const { return NvFlowCPU_Int3(x >> rhs.x, y >> rhs.y, z >> rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Int3 operator<<(const NvFlowCPU_Int3& rhs) const { return NvFlowCPU_Int3(x << rhs.x, y << rhs.y, z << rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Int3 operator&(const NvFlowCPU_Int3& rhs) const { return NvFlowCPU_Int3(x & rhs.x, y & rhs.y, z & rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Int3 operator|(const NvFlowCPU_Int3& rhs) const { return NvFlowCPU_Int3(x | rhs.x, y | rhs.y, z | rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Int3 operator>>(const int& rhs) const { return NvFlowCPU_Int3(x >> rhs, y >> rhs, z >> rhs); }
NV_FLOW_INLINE NvFlowCPU_Int3 operator<<(const int& rhs) const { return NvFlowCPU_Int3(x << rhs, y << rhs, z << rhs); }
NV_FLOW_INLINE NvFlowCPU_Int3 operator>>(const NvFlowCPU_Uint& rhs) const { return NvFlowCPU_Int3(x >> rhs, y >> rhs, z >> rhs); }
NV_FLOW_INLINE NvFlowCPU_Int3 operator<<(const NvFlowCPU_Uint& rhs) const { return NvFlowCPU_Int3(x << rhs, y << rhs, z << rhs); }
NV_FLOW_INLINE NvFlowCPU_Int3 operator>>(const NvFlowCPU_Uint3& rhs) const;
NV_FLOW_INLINE NvFlowCPU_Int3 operator<<(const NvFlowCPU_Uint3& rhs) const;
};
NV_FLOW_INLINE NvFlowCPU_Int3 NvFlowCPU_max(NvFlowCPU_Int3 a, NvFlowCPU_Int3 b)
{
return NvFlowCPU_Int3(NvFlowCPU_max(a.x, b.x), NvFlowCPU_max(a.y, b.y), NvFlowCPU_max(a.z, b.z));
}
NV_FLOW_INLINE NvFlowCPU_Int3 NvFlowCPU_min(NvFlowCPU_Int3 a, NvFlowCPU_Int3 b)
{
return NvFlowCPU_Int3(NvFlowCPU_min(a.x, b.x), NvFlowCPU_min(a.y, b.y), NvFlowCPU_min(a.z, b.z));
}
struct NvFlowCPU_Int4
{
int x, y, z, w;
NvFlowCPU_Int4() {}
NvFlowCPU_Int4(int x, int y, int z, int w) : x(x), y(y), z(z), w(w) {}
NvFlowCPU_Int4(const NvFlowCPU_Int2& a, const NvFlowCPU_Int2& b) : x(a.x), y(a.y), z(b.x), w(b.y) {}
NvFlowCPU_Int4(const NvFlowCPU_Int3& rhs, int w) : x(rhs.x), y(rhs.y), z(rhs.z), w(w) {}
NvFlowCPU_Int4(const NvFlowCPU_Uint4& rhs);
NvFlowCPU_Int3& rgb() { return *((NvFlowCPU_Int3*)this); }
NvFlowCPU_Int2& rg() { return *((NvFlowCPU_Int2*)this); }
int& r() { return *((int*)this); }
NvFlowCPU_Int2& ba() { return *((NvFlowCPU_Int2*)&z); }
const NvFlowCPU_Int3& rgb()const { return *((const NvFlowCPU_Int3*)this); }
const NvFlowCPU_Int2& rg()const { return *((const NvFlowCPU_Int2*)this); }
const int& r()const { return *((const int*)this); }
const NvFlowCPU_Int2& ba()const { return *((const NvFlowCPU_Int2*)&z); }
NvFlowCPU_Int4 operator+(const NvFlowCPU_Int4& rhs) const { return NvFlowCPU_Int4(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w); }
};
struct NvFlowCPU_Uint2
{
NvFlowUint x, y;
NvFlowCPU_Uint2() {}
NvFlowCPU_Uint2(NvFlowUint x, NvFlowUint y) : x(x), y(y) {}
NvFlowCPU_Uint2(const NvFlowCPU_Int2& rhs) : x(rhs.x), y(rhs.y) {}
};
NV_FLOW_INLINE NvFlowCPU_Int2::NvFlowCPU_Int2(const NvFlowCPU_Uint2& rhs) : x(rhs.x), y(rhs.y) {}
struct NvFlowCPU_Uint3
{
NvFlowUint x, y, z;
NvFlowCPU_Uint3() {}
NvFlowCPU_Uint3(NvFlowUint x, NvFlowUint y, NvFlowUint z) : x(x), y(y), z(z) {}
NV_FLOW_INLINE NvFlowCPU_Uint3(const NvFlowCPU_Int3& v);
NvFlowCPU_Uint2& rg() { return *((NvFlowCPU_Uint2*)this); }
NvFlowCPU_Uint& r() { return *((NvFlowCPU_Uint*)this); }
NvFlowCPU_Uint3 operator+(const NvFlowCPU_Uint3& rhs) const { return NvFlowCPU_Uint3(x + rhs.x, y + rhs.y, z + rhs.z); }
NvFlowCPU_Uint3 operator-(const NvFlowCPU_Uint3& rhs) const { return NvFlowCPU_Uint3(x - rhs.x, y - rhs.y, z - rhs.z); }
NvFlowCPU_Uint3 operator*(const NvFlowCPU_Uint3& rhs) const { return NvFlowCPU_Uint3(x * rhs.x, y * rhs.y, z * rhs.z); }
NvFlowCPU_Uint3 operator/(const NvFlowCPU_Uint3& rhs) const { return NvFlowCPU_Uint3(x / rhs.x, y / rhs.y, z / rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Uint3 operator&(const NvFlowCPU_Uint3& rhs) const { return NvFlowCPU_Uint3(x & rhs.x, y & rhs.y, z & rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Uint3 operator|(const NvFlowCPU_Uint3& rhs) const { return NvFlowCPU_Uint3(x | rhs.x, y | rhs.y, z | rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Uint3 operator>>(const NvFlowCPU_Uint3& rhs) const { return NvFlowCPU_Uint3(x >> rhs.x, y >> rhs.y, z >> rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Uint3 operator<<(const NvFlowCPU_Uint3& rhs) const { return NvFlowCPU_Uint3(x << rhs.x, y << rhs.y, z << rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Uint3 operator>>(const NvFlowCPU_Int3& rhs) const { return NvFlowCPU_Uint3(x >> rhs.x, y >> rhs.y, z >> rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Uint3 operator<<(const NvFlowCPU_Int3& rhs) const { return NvFlowCPU_Uint3(x << rhs.x, y << rhs.y, z << rhs.z); }
};
NV_FLOW_INLINE NvFlowCPU_Uint3 operator>>(const NvFlowCPU_Uint& lhs, const NvFlowCPU_Uint3& rhs) { return NvFlowCPU_Uint3(lhs >> rhs.x, lhs >> rhs.y, lhs >> rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Uint3 operator>>(const NvFlowCPU_Uint3& lhs, const NvFlowCPU_Uint& rhs) { return NvFlowCPU_Uint3(lhs.x >> rhs, lhs.y >> rhs, lhs.z >> rhs); }
NV_FLOW_INLINE NvFlowCPU_Uint3 operator<<(const NvFlowCPU_Uint& lhs, const NvFlowCPU_Uint3& rhs) { return NvFlowCPU_Uint3(lhs << rhs.x, lhs << rhs.y, lhs << rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Uint3 operator<<(const NvFlowCPU_Uint3& lhs, const NvFlowCPU_Uint& rhs) { return NvFlowCPU_Uint3(lhs.x << rhs, lhs.y << rhs, lhs.z << rhs); }
NV_FLOW_INLINE NvFlowCPU_Uint3 operator+(const NvFlowCPU_Uint& lhs, const NvFlowCPU_Uint3& rhs) { return NvFlowCPU_Uint3(lhs + rhs.x, lhs + rhs.y, lhs + rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Uint3 operator+(const NvFlowCPU_Uint3& lhs, const NvFlowCPU_Uint& rhs) { return NvFlowCPU_Uint3(lhs.x + rhs, lhs.y + rhs, lhs.z + rhs); }
NV_FLOW_INLINE NvFlowCPU_Uint3 operator-(const NvFlowCPU_Uint& lhs, const NvFlowCPU_Uint3& rhs) { return NvFlowCPU_Uint3(lhs - rhs.x, lhs - rhs.y, lhs - rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Uint3 operator-(const NvFlowCPU_Uint3& lhs, const NvFlowCPU_Uint& rhs) { return NvFlowCPU_Uint3(lhs.x - rhs, lhs.y - rhs, lhs.z - rhs); }
struct NvFlowCPU_Uint4
{
NvFlowUint x, y, z, w;
NvFlowCPU_Uint4() {}
NvFlowCPU_Uint4(NvFlowUint x, NvFlowUint y, NvFlowUint z, NvFlowUint w) : x(x), y(y), z(z), w(w) {}
NvFlowCPU_Uint4 operator+(const NvFlowCPU_Uint4& rhs) const { return NvFlowCPU_Uint4(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w); }
NvFlowCPU_Uint4 operator-(const NvFlowCPU_Uint4& rhs) const { return NvFlowCPU_Uint4(x - rhs.x, y - rhs.y, z - rhs.z, w - rhs.w); }
NvFlowCPU_Uint4 operator*(const NvFlowCPU_Uint4& rhs) const { return NvFlowCPU_Uint4(x * rhs.x, y * rhs.y, z * rhs.z, w * rhs.w); }
NvFlowCPU_Uint4 operator/(const NvFlowCPU_Uint4& rhs) const { return NvFlowCPU_Uint4(x / rhs.x, y / rhs.y, z / rhs.z, w / rhs.w); }
NvFlowCPU_Uint4& operator+=(const NvFlowCPU_Uint4& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; w += rhs.w; return *this; }
NvFlowCPU_Uint4& operator-=(const NvFlowCPU_Uint4& rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; w -= rhs.w; return *this; }
NvFlowCPU_Uint4& operator*=(const NvFlowCPU_Uint4& rhs) { x *= rhs.x; y *= rhs.y; z *= rhs.z; w *= rhs.w; return *this; }
NvFlowCPU_Uint4& operator/=(const NvFlowCPU_Uint4& rhs) { x /= rhs.x; y /= rhs.y; z /= rhs.z; w /= rhs.w; return *this; }
};
NV_FLOW_INLINE NvFlowCPU_Int3 NvFlowCPU_Int3::operator>>(const NvFlowCPU_Uint3& rhs) const { return NvFlowCPU_Int3(x >> rhs.x, y >> rhs.y, z >> rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Int3 NvFlowCPU_Int3::operator<<(const NvFlowCPU_Uint3& rhs) const { return NvFlowCPU_Int3(x << rhs.x, y << rhs.y, z << rhs.z); }
NV_FLOW_INLINE NvFlowCPU_Float3::NvFlowCPU_Float3(const NvFlowCPU_Int3& v) : x(float(v.x)), y(float(v.y)), z(float(v.z)) {}
NV_FLOW_INLINE NvFlowCPU_Int3::NvFlowCPU_Int3(const NvFlowCPU_Uint3& v) : x(int(v.x)), y(int(v.y)), z(int(v.z)) {}
NV_FLOW_INLINE NvFlowCPU_Int3::NvFlowCPU_Int3(const NvFlowCPU_Float3& v) : x(int(v.x)), y(int(v.y)), z(int(v.z)) {}
NV_FLOW_INLINE NvFlowCPU_Uint3::NvFlowCPU_Uint3(const NvFlowCPU_Int3& v) : x(int(v.x)), y(int(v.y)), z(int(v.z)) {}
NV_FLOW_INLINE NvFlowCPU_Int4::NvFlowCPU_Int4(const NvFlowCPU_Uint4& rhs) : x(int(rhs.x)), y(int(rhs.y)), z(int(rhs.z)), w(int(rhs.w)) {}
NV_FLOW_INLINE NvFlowCPU_Float4 NvFlowCPU_asfloat(NvFlowCPU_Uint4 v) {return *((NvFlowCPU_Float4*)&v);}
NV_FLOW_INLINE NvFlowCPU_Float3 NvFlowCPU_asfloat(NvFlowCPU_Uint3 v) {return *((NvFlowCPU_Float3*)&v);}
NV_FLOW_INLINE NvFlowCPU_Float2 NvFlowCPU_asfloat(NvFlowCPU_Uint2 v) {return *((NvFlowCPU_Float2*)&v);}
NV_FLOW_INLINE float NvFlowCPU_asfloat(NvFlowUint v) {return *((float*)&v);}
NV_FLOW_INLINE NvFlowCPU_Float4 NvFlowCPU_asfloat(NvFlowCPU_Int4 v) {return *((NvFlowCPU_Float4*)&v);}
NV_FLOW_INLINE NvFlowCPU_Float3 NvFlowCPU_asfloat(NvFlowCPU_Int3 v) {return *((NvFlowCPU_Float3*)&v);}
NV_FLOW_INLINE NvFlowCPU_Float2 NvFlowCPU_asfloat(NvFlowCPU_Int2 v) {return *((NvFlowCPU_Float2*)&v);}
NV_FLOW_INLINE float NvFlowCPU_asfloat(int v) {return *((float*)&v);}
NV_FLOW_INLINE NvFlowCPU_Uint4 NvFlowCPU_asuint(NvFlowCPU_Float4 v) {return *((NvFlowCPU_Uint4*)&v);}
NV_FLOW_INLINE NvFlowCPU_Uint3 NvFlowCPU_asuint(NvFlowCPU_Float3 v) {return *((NvFlowCPU_Uint3*)&v);}
NV_FLOW_INLINE NvFlowCPU_Uint2 NvFlowCPU_asuint(NvFlowCPU_Float2 v) {return *((NvFlowCPU_Uint2*)&v);}
NV_FLOW_INLINE NvFlowUint NvFlowCPU_asuint(float v) {return *((NvFlowUint*)&v);}
NV_FLOW_INLINE NvFlowCPU_Int4 NvFlowCPU_asint(NvFlowCPU_Float4 v) {return *((NvFlowCPU_Int4*)&v);}
NV_FLOW_INLINE NvFlowCPU_Int3 NvFlowCPU_asint(NvFlowCPU_Float3 v) {return *((NvFlowCPU_Int3*)&v);}
NV_FLOW_INLINE NvFlowCPU_Int2 NvFlowCPU_asint(NvFlowCPU_Float2 v) {return *((NvFlowCPU_Int2*)&v);}
NV_FLOW_INLINE int NvFlowCPU_asint(float v) {return *((int*)&v);}
struct NvFlowCPU_Resource
{
void* data;
NvFlowUint64 sizeInBytes;
NvFlowUint elementSizeInBytes;
NvFlowUint elementCount;
NvFlowFormat format;
NvFlowUint width;
NvFlowUint height;
NvFlowUint depth;
NvFlowSamplerDesc samplerDesc;
};
template <typename T>
struct NvFlowCPU_ConstantBuffer
{
const T* data;
NV_FLOW_INLINE void bind(NvFlowCPU_Resource* resource)
{
data = (const T*)resource->data;
}
};
template <typename T>
struct NvFlowCPU_StructuredBuffer
{
const T* data;
NvFlowUint count;
NV_FLOW_INLINE void bind(NvFlowCPU_Resource* resource)
{
data = (const T*)resource->data;
count = resource->elementCount;
}
const T& operator[](int index) {
if (index < 0 || index >= int(count)) index = 0;
return data[index];
}
};
template <typename T>
struct NvFlowCPU_RWStructuredBuffer
{
T* data;
NvFlowUint count;
NV_FLOW_INLINE void bind(NvFlowCPU_Resource* resource)
{
data = (T*)resource->data;
count = resource->elementCount;
}
T& operator[](int index) {
if (index < 0 || index >= int(count)) index = 0;
return data[index];
}
};
struct NvFlowCPU_SamplerState
{
NvFlowSamplerDesc desc;
NV_FLOW_INLINE void bind(NvFlowCPU_Resource* resource)
{
desc = resource->samplerDesc;
}
};
template <typename T>
struct NvFlowCPU_Texture1D
{
const T* data;
NvFlowFormat format;
NvFlowUint width;
T out_of_bounds = {};
NV_FLOW_INLINE void bind(NvFlowCPU_Resource* resource)
{
data = (const T*)resource->data;
format = resource->format;
width = resource->width;
memset(&out_of_bounds, 0, sizeof(out_of_bounds));
}
};
template <typename T>
NV_FLOW_FORCE_INLINE const T NvFlowCPU_textureRead(NvFlowCPU_Texture1D<T>& tex, int index)
{
if (index < 0 || index >= int(tex.width))
{
return tex.out_of_bounds;
}
return tex.data[index];
}
template <typename T>
NV_FLOW_FORCE_INLINE T NvFlowCPU_textureSampleLevel(NvFlowCPU_Texture1D<T>& tex, NvFlowCPU_SamplerState state, const float pos, float lod)
{
float posf(float(tex.width) * pos);
// clamp sampler
if (posf < 0.5f) posf = 0.5f;
if (posf > float(tex.width) - 0.5f) posf = float(tex.width) - 0.5f;
int pos0 = int(NvFlowCPU_floor(posf - 0.5f));
float f = posf - 0.5f - float(pos0);
float of = 1.f - f;
T sum = of * NvFlowCPU_textureRead(tex, pos0 + 0);
sum += f * NvFlowCPU_textureRead(tex, pos0 + 1);
return sum;
}
template <typename T>
struct NvFlowCPU_RWTexture1D
{
T* data;
NvFlowFormat format;
NvFlowUint width;
NV_FLOW_INLINE void bind(NvFlowCPU_Resource* resource)
{
data = (T*)resource->data;
format = resource->format;
width = resource->width;
}
};
template <typename T>
NV_FLOW_FORCE_INLINE const T NvFlowCPU_textureRead(NvFlowCPU_RWTexture1D<T>& tex, int index)
{
return tex.data[index];
}
template <typename T>
NV_FLOW_FORCE_INLINE void NvFlowCPU_textureWrite(NvFlowCPU_RWTexture1D<T>& tex, int index, const T value)
{
tex.data[index] = value;
}
template <typename T>
NV_FLOW_FORCE_INLINE void NvFlowCPU_textureWrite(bool pred, NvFlowCPU_RWTexture1D<T>& tex, int index, const T value)
{
if (pred)
{
NvFlowCPU_textureWrite(tex, index, value);
}
}
template <typename T>
struct NvFlowCPU_Texture2D
{
const T* data;
NvFlowFormat format;
NvFlowUint width;
NvFlowUint height;
T out_of_bounds;
NV_FLOW_INLINE void bind(NvFlowCPU_Resource* resource)
{
data = (const T*)resource->data;
format = resource->format;
width = resource->width;
height = resource->height;
memset(&out_of_bounds, 0, sizeof(out_of_bounds));
}
};
template <typename T>
NV_FLOW_FORCE_INLINE const T NvFlowCPU_textureRead(NvFlowCPU_Texture2D<T>& tex, NvFlowCPU_Int2 index)
{
if (index.x < 0 || index.x >= int(tex.width) ||
index.y < 0 || index.y >= int(tex.height))
{
return tex.out_of_bounds;
}
return tex.data[index.y * tex.width + index.x];
}
template <typename T>
NV_FLOW_FORCE_INLINE T NvFlowCPU_textureSampleLevel(NvFlowCPU_Texture2D<T>& tex, NvFlowCPU_SamplerState state, const NvFlowCPU_Float2 pos, float lod)
{
NvFlowCPU_Float2 posf(NvFlowCPU_Float2(float(tex.width), float(tex.height)) * pos);
// clamp sampler
if (posf.x < 0.5f) posf.x = 0.5f;
if (posf.x > float(tex.width) - 0.5f) posf.x = float(tex.width) - 0.5f;
if (posf.y < 0.5f) posf.y = 0.5f;
if (posf.y > float(tex.height) - 0.5f) posf.y = float(tex.height) - 0.5f;
NvFlowCPU_Int2 pos00 = NvFlowCPU_Int2(NvFlowCPU_floor(posf - NvFlowCPU_Float2(0.5f, 0.5f)));
NvFlowCPU_Float2 f = posf - NvFlowCPU_Float2(0.5f, 0.5f) - NvFlowCPU_Float2(pos00);
NvFlowCPU_Float2 of = NvFlowCPU_Float2(1.f, 1.f) - f;
T sum = of.x * of.y * NvFlowCPU_textureRead(tex, pos00 + NvFlowCPU_Int2(0, 0));
sum += f.x * of.y * NvFlowCPU_textureRead(tex, pos00 + NvFlowCPU_Int2(1, 0));
sum += of.x * f.y * NvFlowCPU_textureRead(tex, pos00 + NvFlowCPU_Int2(0, 1));
sum += f.x * f.y * NvFlowCPU_textureRead(tex, pos00 + NvFlowCPU_Int2(1, 1));
return sum;
}
template <typename T>
struct NvFlowCPU_RWTexture2D
{
T* data;
NvFlowFormat format;
NvFlowUint width;
NvFlowUint height;
NV_FLOW_INLINE void bind(NvFlowCPU_Resource* resource)
{
data = (T*)resource->data;
format = resource->format;
width = resource->width;
height = resource->height;
}
};
template <typename T>
NV_FLOW_FORCE_INLINE const T NvFlowCPU_textureRead(NvFlowCPU_RWTexture2D<T>& tex, NvFlowCPU_Int2 index)
{
return tex.data[index.y * tex.width + index.x];
}
template <typename T>
NV_FLOW_FORCE_INLINE void NvFlowCPU_textureWrite(NvFlowCPU_RWTexture2D<T>& tex, NvFlowCPU_Int2 index, const T value)
{
tex.data[index.y * tex.width + index.x] = value;
}
template <typename T>
NV_FLOW_FORCE_INLINE void NvFlowCPU_textureWrite(bool pred, NvFlowCPU_RWTexture2D<T>& tex, NvFlowCPU_Int2 index, const T value)
{
if (pred)
{
NvFlowCPU_textureWrite(tex, index, value);
}
}
template <typename T>
struct NvFlowCPU_Texture3D
{
const T* data;
NvFlowFormat format;
NvFlowUint width;
NvFlowUint height;
NvFlowUint depth;
T out_of_bounds;
NvFlowUint wh;
NvFlowUint whd;
NV_FLOW_INLINE void bind(NvFlowCPU_Resource* resource)
{
data = (const T*)resource->data;
format = resource->format;
width = resource->width;
height = resource->height;
depth = resource->depth;
memset(&out_of_bounds, 0, sizeof(out_of_bounds));
wh = width * height;
whd = wh * depth;
}
};
template <typename T>
NV_FLOW_FORCE_INLINE const T NvFlowCPU_textureRead(NvFlowCPU_Texture3D<T>& tex, NvFlowCPU_Int3 index)
{
if (index.x < 0 || index.x >= int(tex.width) ||
index.y < 0 || index.y >= int(tex.height) ||
index.z < 0 || index.z >= int(tex.depth))
{
return tex.out_of_bounds;
}
return tex.data[(index.z * tex.height + index.y) * tex.width + index.x];
}
template <typename T>
NV_FLOW_FORCE_INLINE T NvFlowCPU_textureSampleLevel(NvFlowCPU_Texture3D<T>& tex, NvFlowCPU_SamplerState state, const NvFlowCPU_Float3 pos, float lod)
{
NvFlowCPU_Float3 posf(NvFlowCPU_Float3(float(tex.width), float(tex.height), float(tex.depth)) * pos);
// clamp sampler
if (posf.x < 0.5f) posf.x = 0.5f;
if (posf.x > float(tex.width) - 0.5f) posf.x = float(tex.width) - 0.5f;
if (posf.y < 0.5f) posf.y = 0.5f;
if (posf.y > float(tex.height) - 0.5f) posf.y = float(tex.height) - 0.5f;
if (posf.z < 0.5f) posf.z = 0.5f;
if (posf.z > float(tex.depth) - 0.5f) posf.z = float(tex.depth) - 0.5f;
NvFlowCPU_Int4 pos000 = NvFlowCPU_Int4(NvFlowCPU_floor(posf - NvFlowCPU_Float3(0.5f, 0.5f, 0.5f)), 0);
NvFlowCPU_Float3 f = posf - NvFlowCPU_Float3(0.5f, 0.5f, 0.5f) - NvFlowCPU_Float3(float(pos000.x), float(pos000.y), float(pos000.z));
NvFlowCPU_Float3 of = NvFlowCPU_Float3(1.f, 1.f, 1.f) - f;
NvFlowCPU_Float4 wl(
of.x * of.y * of.z,
f.x * of.y * of.z,
of.x * f.y * of.z,
f.x * f.y * of.z
);
NvFlowCPU_Float4 wh(
of.x * of.y * f.z,
f.x * of.y * f.z,
of.x * f.y * f.z,
f.x * f.y * f.z
);
T sum;
if (pos000.x >= 0 && pos000.y >= 0 && pos000.z >= 0 &&
pos000.x <= int(tex.width - 2) && pos000.y <= int(tex.height - 2) && pos000.z <= int(tex.depth - 2))
{
NvFlowUint idx000 = pos000.z * tex.wh + pos000.y * tex.width + pos000.x;
sum = wl.x * tex.data[idx000];
sum += wl.y * tex.data[idx000 + 1u];
sum += wl.z * tex.data[idx000 + tex.width];
sum += wl.w * tex.data[idx000 + 1u + tex.width];
sum += wh.x * tex.data[idx000 + tex.wh];
sum += wh.y * tex.data[idx000 + 1u + tex.wh];
sum += wh.z * tex.data[idx000 + tex.width + tex.wh];
sum += wh.w * tex.data[idx000 + 1u + tex.width + tex.wh];
}
else
{
sum = wl.x * NvFlowCPU_textureRead(tex, pos000.rgb() + NvFlowCPU_Int3(0, 0, 0));
sum += wl.y * NvFlowCPU_textureRead(tex, pos000.rgb() + NvFlowCPU_Int3(1, 0, 0));
sum += wl.z * NvFlowCPU_textureRead(tex, pos000.rgb() + NvFlowCPU_Int3(0, 1, 0));
sum += wl.w * NvFlowCPU_textureRead(tex, pos000.rgb() + NvFlowCPU_Int3(1, 1, 0));
sum += wh.x * NvFlowCPU_textureRead(tex, pos000.rgb() + NvFlowCPU_Int3(0, 0, 1));
sum += wh.y * NvFlowCPU_textureRead(tex, pos000.rgb() + NvFlowCPU_Int3(1, 0, 1));
sum += wh.z * NvFlowCPU_textureRead(tex, pos000.rgb() + NvFlowCPU_Int3(0, 1, 1));
sum += wh.w * NvFlowCPU_textureRead(tex, pos000.rgb() + NvFlowCPU_Int3(1, 1, 1));
}
return sum;
}
template <typename T>
struct NvFlowCPU_RWTexture3D
{
T* data;
NvFlowFormat format;
NvFlowUint width;
NvFlowUint height;
NvFlowUint depth;
NV_FLOW_INLINE void bind(NvFlowCPU_Resource* resource)
{
data = (T*)resource->data;
format = resource->format;
width = resource->width;
height = resource->height;
depth = resource->depth;
}
};
template <typename T>
NV_FLOW_FORCE_INLINE const T NvFlowCPU_textureRead(NvFlowCPU_RWTexture3D<T>& tex, NvFlowCPU_Int3 index)
{
return tex.data[(index.z * tex.height + index.y) * tex.width + index.x];
}
template <typename T>
NV_FLOW_FORCE_INLINE void NvFlowCPU_textureWrite(NvFlowCPU_RWTexture3D<T>& tex, NvFlowCPU_Int3 index, const T value)
{
tex.data[(index.z * tex.height + index.y) * tex.width + index.x] = value;
}
template <typename T>
NV_FLOW_FORCE_INLINE void NvFlowCPU_textureWrite(bool pred, NvFlowCPU_RWTexture3D<T>& tex, NvFlowCPU_Int3 index, const T value)
{
if (pred)
{
NvFlowCPU_textureWrite(tex, index, value);
}
}
template <typename T>
NV_FLOW_FORCE_INLINE void NvFlowCPU_InterlockedAdd(NvFlowCPU_RWTexture3D<T>& tex, NvFlowCPU_Int3 index, T value)
{
((std::atomic<T>*)&tex.data[(index.z * tex.height + index.y) * tex.width + index.x])->fetch_add(value);
}
template <typename T>
NV_FLOW_FORCE_INLINE void NvFlowCPU_InterlockedMin(NvFlowCPU_RWTexture3D<T>& tex, NvFlowCPU_Int3 index, T value)
{
((std::atomic<T>*)&tex.data[(index.z * tex.height + index.y) * tex.width + index.x])->fetch_min(value);
}
template <typename T>
NV_FLOW_FORCE_INLINE void NvFlowCPU_InterlockedOr(NvFlowCPU_RWTexture3D<T>& tex, NvFlowCPU_Int3 index, T value)
{
((std::atomic<T>*)&tex.data[(index.z * tex.height + index.y) * tex.width + index.x])->fetch_or(value);
}
template <typename T>
NV_FLOW_FORCE_INLINE void NvFlowCPU_InterlockedAnd(NvFlowCPU_RWTexture3D<T>& tex, NvFlowCPU_Int3 index, T value)
{
((std::atomic<T>*)&tex.data[(index.z * tex.height + index.y) * tex.width + index.x])->fetch_and(value);
}
template <class T>
struct NvFlowCPU_Groupshared
{
T data;
};
template <class T>
NV_FLOW_FORCE_INLINE void NvFlowCPU_swrite(int _groupshared_pass, int _groupshared_sync_count, NvFlowCPU_Groupshared<T>& g, const T& value)
{
if (_groupshared_pass == _groupshared_sync_count)
{
g.data = value;
}
}
template <class T>
NV_FLOW_FORCE_INLINE T NvFlowCPU_sread(NvFlowCPU_Groupshared<T>& g)
{
return g.data;
}
template <class T, unsigned int arraySize>
struct NvFlowCPU_GroupsharedArray
{
T data[arraySize];
};
template <class T, unsigned int arraySize>
NV_FLOW_FORCE_INLINE void NvFlowCPU_swrite(int _groupshared_pass, int _groupshared_sync_count, NvFlowCPU_GroupsharedArray<T, arraySize>& g, int index, const T& value)
{
if (_groupshared_pass == _groupshared_sync_count)
{
g.data[index] = value;
}
}
template <class T, unsigned int arraySize>
NV_FLOW_FORCE_INLINE T NvFlowCPU_sread(NvFlowCPU_GroupsharedArray<T, arraySize>& g, int index)
{
return g.data[index];
}
#endif |
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowDynamicBuffer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowContext.h"
#include "NvFlowArray.h"
struct NvFlowDynamicBuffer
{
NvFlowContextInterface* contextInterface = nullptr;
NvFlowBufferUsageFlags flags = 0u;
NvFlowFormat format = eNvFlowFormat_unknown;
NvFlowUint structureStride = 0u;
NvFlowBuffer* deviceBuffer = nullptr;
NvFlowUint64 deviceNumBytes = 0llu;
NvFlowBufferTransient* transientBuffer = nullptr;
NvFlowUint64 transientFrame = ~0llu;
};
NV_FLOW_INLINE void NvFlowDynamicBuffer_init(NvFlowContextInterface* contextInterface, NvFlowContext* context, NvFlowDynamicBuffer* ptr, NvFlowBufferUsageFlags flags, NvFlowFormat format, NvFlowUint structureStride)
{
ptr->contextInterface = contextInterface;
ptr->flags = flags;
ptr->format = format;
ptr->structureStride = structureStride;
}
NV_FLOW_INLINE void NvFlowDynamicBuffer_destroy(NvFlowContext* context, NvFlowDynamicBuffer* ptr)
{
if (ptr->deviceBuffer)
{
ptr->contextInterface->destroyBuffer(context, ptr->deviceBuffer);
ptr->deviceBuffer = nullptr;
}
}
NV_FLOW_INLINE void NvFlowDynamicBuffer_resize(NvFlowContext* context, NvFlowDynamicBuffer* ptr, NvFlowUint64 numBytes)
{
if (ptr->deviceBuffer && ptr->deviceNumBytes < numBytes)
{
ptr->contextInterface->destroyBuffer(context, ptr->deviceBuffer);
ptr->deviceBuffer = nullptr;
ptr->deviceNumBytes = 0llu;
ptr->transientFrame = ~0llu;
}
if (!ptr->deviceBuffer)
{
NvFlowBufferDesc bufDesc = {};
bufDesc.format = ptr->format;
bufDesc.usageFlags = ptr->flags;
bufDesc.structureStride = ptr->structureStride;
bufDesc.sizeInBytes = 65536u;
while (bufDesc.sizeInBytes < numBytes)
{
bufDesc.sizeInBytes *= 2u;
}
ptr->deviceNumBytes = bufDesc.sizeInBytes;
ptr->deviceBuffer = ptr->contextInterface->createBuffer(context, eNvFlowMemoryType_device, &bufDesc);
}
}
NV_FLOW_INLINE NvFlowBufferTransient* NvFlowDynamicBuffer_getTransient(NvFlowContext* context, NvFlowDynamicBuffer* ptr)
{
if (ptr->transientFrame == ptr->contextInterface->getCurrentFrame(context))
{
return ptr->transientBuffer;
}
if (ptr->deviceBuffer)
{
ptr->transientBuffer = ptr->contextInterface->registerBufferAsTransient(context, ptr->deviceBuffer);
ptr->transientFrame = ptr->contextInterface->getCurrentFrame(context);
}
return ptr->transientBuffer;
} |
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowBufferVariable.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowContext.h"
struct NvFlowBufferVariable
{
NvFlowContextInterface* contextInterface = nullptr;
NvFlowBufferTransient* transientBuffer = nullptr;
NvFlowUint64 transientFrame = ~0llu;
NvFlowBuffer* buffer = nullptr;
NvFlowArray<NvFlowBufferAcquire*, 4u> acquires;
};
NV_FLOW_INLINE void NvFlowBufferVariable_init(NvFlowContextInterface* contextInterface, NvFlowBufferVariable* ptr)
{
ptr->contextInterface = contextInterface;
}
NV_FLOW_INLINE void NvFlowBufferVariable_flush(NvFlowContext* context, NvFlowBufferVariable* ptr)
{
// process acquire queue
NvFlowUint acquireWriteIdx = 0u;
for (NvFlowUint acquireReadIdx = 0u; acquireReadIdx < ptr->acquires.size; acquireReadIdx++)
{
NvFlowBuffer* acquiredBuffer = nullptr;
if (ptr->contextInterface->getAcquiredBuffer(context, ptr->acquires[acquireReadIdx], &acquiredBuffer))
{
if (ptr->buffer)
{
ptr->contextInterface->destroyBuffer(context, ptr->buffer);
ptr->buffer = nullptr;
}
ptr->buffer = acquiredBuffer;
}
else
{
ptr->acquires[acquireWriteIdx++] = ptr->acquires[acquireReadIdx];
}
}
ptr->acquires.size = acquireWriteIdx;
}
NV_FLOW_INLINE NvFlowBufferTransient* NvFlowBufferVariable_get(NvFlowContext* context, NvFlowBufferVariable* ptr)
{
if (ptr->transientFrame == ptr->contextInterface->getCurrentFrame(context))
{
return ptr->transientBuffer;
}
NvFlowBufferVariable_flush(context, ptr);
if (ptr->buffer)
{
ptr->transientBuffer = ptr->contextInterface->registerBufferAsTransient(context, ptr->buffer);
ptr->transientFrame = ptr->contextInterface->getCurrentFrame(context);
}
else
{
ptr->transientBuffer = nullptr;
ptr->transientFrame = ~0llu;
}
return ptr->transientBuffer;
}
NV_FLOW_INLINE void NvFlowBufferVariable_set(NvFlowContext* context, NvFlowBufferVariable* ptr, NvFlowBufferTransient* transientBuffer)
{
NvFlowBufferVariable_flush(context, ptr);
if (ptr->buffer)
{
ptr->contextInterface->destroyBuffer(context, ptr->buffer);
ptr->buffer = nullptr;
}
ptr->transientBuffer = nullptr;
ptr->transientFrame = ~0llu;
if (transientBuffer)
{
ptr->transientBuffer = transientBuffer;
ptr->transientFrame = ptr->contextInterface->getCurrentFrame(context);
// push acquire
ptr->acquires.pushBack(ptr->contextInterface->enqueueAcquireBuffer(context, transientBuffer));
}
}
NV_FLOW_INLINE void NvFlowBufferVariable_destroy(NvFlowContext* context, NvFlowBufferVariable* ptr)
{
NvFlowBufferVariable_set(context, ptr, nullptr);
} |
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowTimer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowTypes.h"
#if defined(_WIN32)
#include <Windows.h>
#else
#include <time.h>
#endif
#include "NvFlowArray.h"
NV_FLOW_INLINE void NvFlowTimeStamp_capture(NvFlowUint64* ptr)
{
#if defined(_WIN32)
LARGE_INTEGER tmpCpuTime = {};
QueryPerformanceCounter(&tmpCpuTime);
(*ptr) = tmpCpuTime.QuadPart;
#else
timespec timeValue = {};
clock_gettime(CLOCK_MONOTONIC, &timeValue);
(*ptr) = 1E9 * NvFlowUint64(timeValue.tv_sec) + NvFlowUint64(timeValue.tv_nsec);
#endif
}
NV_FLOW_INLINE NvFlowUint64 NvFlowTimeStamp_frequency()
{
#if defined(_WIN32)
LARGE_INTEGER tmpCpuFreq = {};
QueryPerformanceFrequency(&tmpCpuFreq);
return tmpCpuFreq.QuadPart;
#else
return 1E9;
#endif
}
NV_FLOW_INLINE float NvFlowTimeStamp_diff(NvFlowUint64 begin, NvFlowUint64 end, NvFlowUint64 freq)
{
return (float)(((double)(end - begin) / (double)(freq)));
}
#if 1
#define NV_FLOW_PROFILE_BEGIN(profileInterval, profileOffset)
#define NV_FLOW_PROFILE_TIMESTAMP(name)
#define NV_FLOW_PROFILE_FLUSH(name, logPrint)
#else
#define NV_FLOW_PROFILE_BEGIN(profileInterval, profileOffset) \
static int profileCount = profileOffset; \
profileCount++; \
if (profileCount >= profileInterval) \
{ \
profileCount = 0; \
} \
NvFlowArray<NvFlowUint64, 32u> profileTimes; \
NvFlowArray<const char*, 32u> profileNames; \
const NvFlowBool32 profileEnabled = (profileCount == 0);
#define NV_FLOW_PROFILE_TIMESTAMP(name) \
if (profileEnabled) \
{ \
NvFlowTimeStamp_capture(&profileTimes[profileTimes.allocateBack()]); \
profileNames.pushBack(#name); \
}
#define NV_FLOW_PROFILE_FLUSH(name, logPrint) \
if (profileEnabled && logPrint && profileTimes.size >= 2u) \
{ \
NvFlowUint64 freq = NvFlowTimeStamp_frequency(); \
float totalTime = NvFlowTimeStamp_diff(profileTimes[0u], profileTimes[profileTimes.size - 1u], freq); \
for (NvFlowUint64 idx = 1u; idx < profileTimes.size; idx++) \
{ \
float time = NvFlowTimeStamp_diff(profileTimes[idx - 1u], profileTimes[idx], freq); \
if (time >= 0.001f * totalTime) \
{ \
logPrint(eNvFlowLogLevel_warning, "[%s] %f ms", profileNames[idx], 1000.f * time); \
} \
} \
logPrint(eNvFlowLogLevel_warning, "Total [%s] %f ms", #name, 1000.f * totalTime); \
}
#endif |
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowTextureVariable.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowContext.h"
struct NvFlowTextureVariable
{
NvFlowContextInterface* contextInterface = nullptr;
NvFlowTextureTransient* transientTexture = nullptr;
NvFlowUint64 transientFrame = ~0llu;
NvFlowFormat transientFormat = eNvFlowFormat_unknown;
NvFlowTexture* texture = nullptr;
NvFlowArray<NvFlowTextureAcquire*, 4u> acquires;
NvFlowTextureDesc hintTexDesc = {};
};
NV_FLOW_INLINE void NvFlowTextureVariable_init(NvFlowContextInterface* contextInterface, NvFlowTextureVariable* ptr)
{
ptr->contextInterface = contextInterface;
}
NV_FLOW_INLINE void NvFlowTextureVariable_flush(NvFlowContext* context, NvFlowTextureVariable* ptr)
{
// process acquire queue
NvFlowUint acquireWriteIdx = 0u;
for (NvFlowUint acquireReadIdx = 0u; acquireReadIdx < ptr->acquires.size; acquireReadIdx++)
{
NvFlowTexture* acquiredTexture = nullptr;
if (ptr->contextInterface->getAcquiredTexture(context, ptr->acquires[acquireReadIdx], &acquiredTexture))
{
if (ptr->texture)
{
ptr->contextInterface->destroyTexture(context, ptr->texture);
ptr->texture = nullptr;
}
ptr->texture = acquiredTexture;
}
else
{
ptr->acquires[acquireWriteIdx++] = ptr->acquires[acquireReadIdx];
}
}
ptr->acquires.size = acquireWriteIdx;
}
NV_FLOW_INLINE NvFlowTextureTransient* NvFlowTextureVariable_get(NvFlowContext* context, NvFlowTextureVariable* ptr, NvFlowFormat* pFormat)
{
if (ptr->transientFrame == ptr->contextInterface->getCurrentFrame(context))
{
if (pFormat)
{
*pFormat = ptr->transientFormat;
}
return ptr->transientTexture;
}
NvFlowTextureVariable_flush(context, ptr);
if (ptr->texture)
{
ptr->transientTexture = ptr->contextInterface->registerTextureAsTransient(context, ptr->texture);
ptr->transientFrame = ptr->contextInterface->getCurrentFrame(context);
}
else
{
ptr->transientTexture = nullptr;
ptr->transientFrame = ~0llu;
ptr->transientFormat = eNvFlowFormat_unknown;
}
if (pFormat)
{
*pFormat = ptr->transientFormat;
}
return ptr->transientTexture;
}
NV_FLOW_INLINE void NvFlowTextureVariable_set(NvFlowContext* context, NvFlowTextureVariable* ptr, NvFlowTextureTransient* transientTexture, NvFlowFormat transientFormat)
{
NvFlowTextureVariable_flush(context, ptr);
if (ptr->texture)
{
ptr->contextInterface->destroyTexture(context, ptr->texture);
ptr->texture = nullptr;
}
ptr->transientTexture = nullptr;
ptr->transientFrame = ~0llu;
ptr->transientFormat = eNvFlowFormat_unknown;
if (transientTexture)
{
ptr->transientTexture = transientTexture;
ptr->transientFrame = ptr->contextInterface->getCurrentFrame(context);
ptr->transientFormat = transientFormat;
// push acquire
ptr->acquires.pushBack(ptr->contextInterface->enqueueAcquireTexture(context, transientTexture));
}
}
NV_FLOW_INLINE void NvFlowTextureVariable_destroy(NvFlowContext* context, NvFlowTextureVariable* ptr)
{
NvFlowTextureVariable_set(context, ptr, nullptr, eNvFlowFormat_unknown);
} |
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowReadbackBuffer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowContext.h"
#include "NvFlowArray.h"
struct NvFlowReadbackBufferInstance
{
NvFlowBuffer* buffer = nullptr;
NvFlowUint64 bufferSizeInBytes = 0llu;
NvFlowBool32 isActive = NV_FLOW_FALSE;
NvFlowUint64 completedFrame = ~0llu;
NvFlowUint64 completedGlobalFrame = ~0llu;
NvFlowUint64 version = ~0llu;
NvFlowUint64 validNumBytes = 0llu;
};
struct NvFlowReadbackBuffer
{
NvFlowContextInterface* contextInterface = nullptr;
NvFlowUint64 versionCounter = 0llu;
NvFlowArray<NvFlowReadbackBufferInstance, 8u> buffers;
NvFlowArray<NvFlowUint64, 8u> activeBuffers;
};
NV_FLOW_INLINE void NvFlowReadbackBuffer_init(NvFlowContextInterface* contextInterface, NvFlowContext* context, NvFlowReadbackBuffer* ptr)
{
ptr->contextInterface = contextInterface;
}
NV_FLOW_INLINE void NvFlowReadbackBuffer_destroy(NvFlowContext* context, NvFlowReadbackBuffer* ptr)
{
for (NvFlowUint idx = 0u; idx < ptr->buffers.size; idx++)
{
if (ptr->buffers[idx].buffer)
{
ptr->contextInterface->destroyBuffer(context, ptr->buffers[idx].buffer);
ptr->buffers[idx].buffer = nullptr;
}
}
ptr->buffers.size = 0u;
}
struct NvFlowReadbackBufferCopyRange
{
NvFlowUint64 offset;
NvFlowUint64 numBytes;
};
NV_FLOW_INLINE void NvFlowReadbackBuffer_copyN(NvFlowContext* context, NvFlowReadbackBuffer* ptr, NvFlowUint64 numBytes, NvFlowBufferTransient* src, const NvFlowReadbackBufferCopyRange* copyRanges, NvFlowUint copyRangeCount, NvFlowUint64* pOutVersion)
{
// find inactive buffer, create as needed
NvFlowUint64 bufferIdx = 0u;
for (; bufferIdx < ptr->buffers.size; bufferIdx++)
{
if (!ptr->buffers[bufferIdx].isActive)
{
break;
}
}
if (bufferIdx == ptr->buffers.size)
{
bufferIdx = ptr->buffers.allocateBack();
}
NvFlowReadbackBufferInstance* inst = &ptr->buffers[bufferIdx];
// resize buffer as needed
if (inst->buffer && inst->bufferSizeInBytes < numBytes)
{
ptr->contextInterface->destroyBuffer(context, inst->buffer);
inst->buffer = nullptr;
inst->bufferSizeInBytes = 0llu;
}
if (!inst->buffer)
{
NvFlowBufferDesc bufDesc = {};
bufDesc.usageFlags = eNvFlowBufferUsage_bufferCopyDst;
bufDesc.format = eNvFlowFormat_unknown;
bufDesc.structureStride = 0u;
bufDesc.sizeInBytes = 65536u;
while (bufDesc.sizeInBytes < numBytes)
{
bufDesc.sizeInBytes *= 2u;
}
inst->buffer = ptr->contextInterface->createBuffer(context, eNvFlowMemoryType_readback, &bufDesc);
inst->bufferSizeInBytes = bufDesc.sizeInBytes;
}
// set active state
ptr->versionCounter++;
inst->isActive = NV_FLOW_TRUE;
inst->completedFrame = ptr->contextInterface->getCurrentFrame(context);
inst->completedGlobalFrame = ptr->contextInterface->getCurrentGlobalFrame(context);
inst->version = ptr->versionCounter;
inst->validNumBytes = numBytes;
if (pOutVersion)
{
*pOutVersion = inst->version;
}
// copy
NvFlowBufferTransient* dst = ptr->contextInterface->registerBufferAsTransient(context, inst->buffer);
for (NvFlowUint copyRangeIdx = 0u; copyRangeIdx < copyRangeCount; copyRangeIdx++)
{
NvFlowPassCopyBufferParams copyParams = {};
copyParams.srcOffset = copyRanges[copyRangeIdx].offset;
copyParams.dstOffset = copyRanges[copyRangeIdx].offset;
copyParams.numBytes = copyRanges[copyRangeIdx].numBytes;
copyParams.src = src;
copyParams.dst = dst;
copyParams.debugLabel = "ReadbackBufferCopy";
ptr->contextInterface->addPassCopyBuffer(context, ©Params);
}
if (copyRangeCount == 0u)
{
NvFlowPassCopyBufferParams copyParams = {};
copyParams.srcOffset = 0llu;
copyParams.dstOffset = 0llu;
copyParams.numBytes = 0llu;
copyParams.src = src;
copyParams.dst = dst;
copyParams.debugLabel = "ReadbackBufferCopy";
ptr->contextInterface->addPassCopyBuffer(context, ©Params);
}
// push on active queue
ptr->activeBuffers.pushBack(bufferIdx);
}
NV_FLOW_INLINE void NvFlowReadbackBuffer_copy(NvFlowContext* context, NvFlowReadbackBuffer* ptr, NvFlowUint64 numBytes, NvFlowBufferTransient* src, NvFlowUint64* pOutVersion)
{
NvFlowReadbackBufferCopyRange copyRange = { 0llu, numBytes };
NvFlowReadbackBuffer_copyN(context, ptr, numBytes, src, ©Range, 1u, pOutVersion);
}
NV_FLOW_INLINE void NvFlowReadbackBuffer_flush(NvFlowContext* context, NvFlowReadbackBuffer* ptr)
{
// flush queue
NvFlowUint completedCount = 0u;
NvFlowUint64 lastFenceCompleted = ptr->contextInterface->getLastFrameCompleted(context);
for (NvFlowUint activeBufferIdx = 0u; activeBufferIdx < ptr->activeBuffers.size; activeBufferIdx++)
{
if (ptr->buffers[ptr->activeBuffers[activeBufferIdx]].completedFrame > lastFenceCompleted)
{
break;
}
completedCount++;
}
NvFlowUint popCount = completedCount >= 2u ? completedCount - 1u : 0u;
if (popCount > 0u)
{
for (NvFlowUint activeBufferIdx = 0u; activeBufferIdx < popCount; activeBufferIdx++)
{
ptr->buffers[ptr->activeBuffers[activeBufferIdx]].isActive = NV_FLOW_FALSE;
}
// compact
for (NvFlowUint activeBufferIdx = popCount; activeBufferIdx < ptr->activeBuffers.size; activeBufferIdx++)
{
ptr->activeBuffers[activeBufferIdx - popCount] = ptr->activeBuffers[activeBufferIdx];
}
ptr->activeBuffers.size = ptr->activeBuffers.size - popCount;
}
}
NV_FLOW_INLINE NvFlowUint NvFlowReadbackBuffer_getActiveCount(NvFlowContext* context, NvFlowReadbackBuffer* ptr)
{
return (NvFlowUint)ptr->activeBuffers.size;
}
NV_FLOW_INLINE NvFlowUint64 NvFlowReadbackBuffer_getCompletedGlobalFrame(NvFlowContext* context, NvFlowReadbackBuffer* ptr, NvFlowUint activeIdx)
{
if (activeIdx < ptr->activeBuffers.size)
{
return ptr->buffers[ptr->activeBuffers[activeIdx]].completedGlobalFrame;
}
return ~0llu;
}
NV_FLOW_INLINE void* NvFlowReadbackBuffer_map(NvFlowContext* context, NvFlowReadbackBuffer* ptr, NvFlowUint activeIdx, NvFlowUint64* pOutVersion, NvFlowUint64* pNumBytes)
{
if (activeIdx > ptr->activeBuffers.size)
{
if (pOutVersion)
{
*pOutVersion = 0llu;
}
if (pNumBytes)
{
*pNumBytes = 0llu;
}
return nullptr;
}
NvFlowReadbackBufferInstance* inst = &ptr->buffers[ptr->activeBuffers[activeIdx]];
if (pOutVersion)
{
*pOutVersion = inst->version;
}
if (pNumBytes)
{
*pNumBytes = inst->validNumBytes;
}
return ptr->contextInterface->mapBuffer(context, inst->buffer);
}
NV_FLOW_INLINE void* NvFlowReadbackBuffer_mapLatest(NvFlowContext* context, NvFlowReadbackBuffer* ptr, NvFlowUint64* pOutVersion, NvFlowUint64* pNumBytes)
{
NvFlowReadbackBuffer_flush(context, ptr);
NvFlowUint64 lastFenceCompleted = ptr->contextInterface->getLastFrameCompleted(context);
bool shouldMap = true;
if (ptr->activeBuffers.size > 0u)
{
if (ptr->buffers[ptr->activeBuffers[0u]].completedFrame > lastFenceCompleted)
{
shouldMap = false;
}
}
else if (ptr->buffers[ptr->activeBuffers[0u]].completedFrame > lastFenceCompleted)
{
shouldMap = false;
}
if (!shouldMap)
{
if (pOutVersion)
{
*pOutVersion = 0llu;
}
if (pNumBytes)
{
*pNumBytes = 0llu;
}
return nullptr;
}
return NvFlowReadbackBuffer_map(context, ptr, 0u, pOutVersion, pNumBytes);
}
NV_FLOW_INLINE void NvFlowReadbackBuffer_unmap(NvFlowContext* context, NvFlowReadbackBuffer* ptr, NvFlowUint activeIdx)
{
if (activeIdx < ptr->activeBuffers.size)
{
NvFlowReadbackBufferInstance* inst = &ptr->buffers[ptr->activeBuffers[activeIdx]];
ptr->contextInterface->unmapBuffer(context, inst->buffer);
}
}
NV_FLOW_INLINE void NvFlowReadbackBuffer_unmapLatest(NvFlowContext* context, NvFlowReadbackBuffer* ptr)
{
NvFlowReadbackBuffer_unmap(context, ptr, 0u);
} |
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowDeepCopy.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowReflect.h"
#include "NvFlowArray.h"
#include <string.h>
struct NvFlowReflectDeepCopyInfo
{
const char* debugname;
NvFlowUint64 size;
};
struct NvFlowReflectDeepCopyCached;
struct NvFlowReflectDeepCopy
{
NvFlowArray<NvFlowArray<NvFlowUint8>, 16u> heaps;
NvFlowArray<NvFlowReflectDeepCopyInfo> infos;
NvFlowArray<const char*> pathStack;
NvFlowArrayPointer<NvFlowReflectDeepCopyCached*> cached;
};
struct NvFlowReflectDeepCopyCached
{
NvFlowUint64 luid = 0llu;
NvFlowArray<const char*> pathStack;
NvFlowUint64 version = 0llu;
NvFlowReflectDeepCopy* deepCopy = nullptr;
NvFlowUint8* deepCopyData;
NvFlowUint64 lastUse = 0llu;
};
NV_FLOW_INLINE NvFlowReflectDeepCopy* NvFlowReflectDeepCopy_create()
{
auto ptr = new NvFlowReflectDeepCopy();
return ptr;
}
NV_FLOW_INLINE void NvFlowReflectDeepCopyCached_destroy(NvFlowReflectDeepCopyCached* ptr);
NV_FLOW_INLINE void NvFlowReflectDeepCopy_destroy(NvFlowReflectDeepCopy* ptr)
{
for (NvFlowUint64 cachedIdx = 0u; cachedIdx < ptr->cached.size; cachedIdx++)
{
NvFlowReflectDeepCopyCached_destroy(ptr->cached[cachedIdx]);
ptr->cached[cachedIdx] = nullptr;
}
ptr->cached.size = 0u;
delete ptr;
}
NV_FLOW_INLINE NvFlowReflectDeepCopyCached* NvFlowReflectDeepCopyCached_create(NvFlowUint64 luid, const char** pathStacks, NvFlowUint64 pathStackCount)
{
auto ptr = new NvFlowReflectDeepCopyCached();
ptr->luid = luid;
ptr->pathStack.size = 0u;
for (NvFlowUint64 pathStackIdx = 0u; pathStackIdx < pathStackCount; pathStackIdx++)
{
ptr->pathStack.pushBack(pathStacks[pathStackIdx]);
}
ptr->version = 0llu;
ptr->deepCopy = NvFlowReflectDeepCopy_create();
return ptr;
}
NV_FLOW_INLINE void NvFlowReflectDeepCopyCached_destroy(NvFlowReflectDeepCopyCached* ptr)
{
NvFlowReflectDeepCopy_destroy(ptr->deepCopy);
ptr->deepCopy = nullptr;
delete ptr;
}
NV_FLOW_INLINE void NvFlowReflectDeepCopy_newHeap(NvFlowReflectDeepCopy* ptr, NvFlowUint64 allocSize)
{
auto& currentHeap = ptr->heaps[ptr->heaps.allocateBack()];
NvFlowUint64 heapSize = 4096u; // default heap size
while (heapSize < allocSize)
{
heapSize *= 2u;
}
currentHeap.reserve(heapSize);
}
NV_FLOW_INLINE NvFlowUint64 NvFlowReflectDeepCopy_alignment(NvFlowUint64 size)
{
return 8u * ((size + 7u) / 8u);
}
NV_FLOW_INLINE NvFlowUint8* NvFlowReflectDeepCopy_allocate(NvFlowReflectDeepCopy* ptr, NvFlowUint64 size, const char* debugName)
{
NvFlowUint64 allocSize = NvFlowReflectDeepCopy_alignment(size);
if (ptr->heaps.size > 0u)
{
auto& currentHeap = ptr->heaps[ptr->heaps.size - 1u];
if (currentHeap.size + allocSize <= currentHeap.capacity)
{
NvFlowUint8* ret = currentHeap.data + currentHeap.size;
ret[size - 1] = 0;
currentHeap.size += allocSize;
NvFlowReflectDeepCopyInfo info = { debugName, size };
ptr->infos.pushBack(info);
return ret;
}
}
NvFlowReflectDeepCopy_newHeap(ptr, allocSize);
return NvFlowReflectDeepCopy_allocate(ptr, size, debugName);
}
NV_FLOW_INLINE void NvFlowReflectDeepCopy_reset(NvFlowReflectDeepCopy* ptr)
{
for (NvFlowUint64 heapIdx = 0u; heapIdx < ptr->heaps.size; heapIdx++)
{
ptr->heaps[heapIdx].size = 0u;
}
ptr->heaps.size = 0u;
ptr->infos.size = 0u;
ptr->pathStack.size = 0u;
}
NV_FLOW_INLINE NvFlowUint8* NvFlowReflectDeepCopy_recursive(NvFlowReflectDeepCopy* ptr, NvFlowUint64 luid, const NvFlowUint8* src, const NvFlowReflectDataType* type, NvFlowUint64 elementCount, NvFlowBool32 isPointerArray);
NV_FLOW_INLINE void NvFlowReflectDeepCopy_cleanCache(NvFlowReflectDeepCopy* ptr)
{
static const NvFlowUint64 cacheFreeTreshold = 8u;
NvFlowUint cachedIdx = 0u;
while (cachedIdx < ptr->cached.size)
{
ptr->cached[cachedIdx]->lastUse++;
if (ptr->cached[cachedIdx]->lastUse > cacheFreeTreshold)
{
NvFlowReflectDeepCopyCached_destroy(ptr->cached[cachedIdx]);
ptr->cached[cachedIdx] = nullptr;
ptr->cached.removeSwapPointerAtIndex(cachedIdx);
}
else
{
cachedIdx++;
}
}
}
NV_FLOW_INLINE NvFlowUint8* NvFlowReflectDeepCopy_cached(NvFlowReflectDeepCopy* ptr, NvFlowUint64 luid, const NvFlowUint8* src, const NvFlowReflectDataType* type, NvFlowUint64 elementCount, NvFlowUint64 version, NvFlowBool32 isPointerArray)
{
NvFlowUint64 cachedIdx = 0u;
for (; cachedIdx < ptr->cached.size; cachedIdx++)
{
auto& cached = ptr->cached[cachedIdx];
if (cached->luid == luid && ptr->pathStack.size == cached->pathStack.size)
{
// check path stack
bool pathStackMatches = true;
for (NvFlowUint64 pathStackIdx = 0u; pathStackIdx < ptr->pathStack.size; pathStackIdx++)
{
if (NvFlowReflectStringCompare(ptr->pathStack[pathStackIdx], cached->pathStack[pathStackIdx]) != 0)
{
pathStackMatches = false;
break;
}
}
if (pathStackMatches)
{
break;
}
}
}
if (cachedIdx == ptr->cached.size)
{
cachedIdx = ptr->cached.allocateBack();
ptr->cached[cachedIdx] = NvFlowReflectDeepCopyCached_create(luid, ptr->pathStack.data, ptr->pathStack.size);
}
auto cached = ptr->cached[cachedIdx];
if (ptr->cached[cachedIdx]->version != version)
{
NvFlowReflectDeepCopy_reset(cached->deepCopy);
NvFlowReflectDeepCopy_cleanCache(cached->deepCopy);
cached->deepCopyData = NvFlowReflectDeepCopy_recursive(cached->deepCopy, luid, src, type, elementCount, isPointerArray);
cached->version = version;
}
cached->lastUse = 0u;
return cached->deepCopyData;
}
NV_FLOW_INLINE void NvFlowReflectDeepCopy_structRecursive(NvFlowReflectDeepCopy* ptr, NvFlowUint64 luid, NvFlowUint8* dst, const NvFlowReflectDataType* type, NvFlowUint64 elementCount, NvFlowBool32 isPointerArray)
{
if (type->dataType == eNvFlowType_struct)
{
for (NvFlowUint64 elementIdx = 0u; elementIdx < elementCount; elementIdx++)
{
NvFlowUint8* dstArray = dst + type->elementSize * elementIdx;
// attempt to find luid
for (NvFlowUint childIdx = 0u; childIdx < type->childReflectDataCount; childIdx++)
{
const auto& childReflectData = type->childReflectDatas[childIdx];
if (childReflectData.reflectMode == eNvFlowReflectMode_value &&
childReflectData.dataType->dataType == eNvFlowType_uint64)
{
if (NvFlowReflectStringCompare(childReflectData.name, "luid") == 0)
{
luid = *((NvFlowUint64*)(dst + childReflectData.dataOffset));
break;
}
}
}
// traverse all elements, searching for pointers/arrays
for (NvFlowUint64 childIdx = 0u; childIdx < type->childReflectDataCount; childIdx++)
{
const auto& childReflectData = type->childReflectDatas[childIdx];
ptr->pathStack.pushBack(childReflectData.name);
if (childReflectData.dataType->dataType == eNvFlowType_struct &&
(childReflectData.reflectMode == eNvFlowReflectMode_value ||
childReflectData.reflectMode == eNvFlowReflectMode_valueVersioned))
{
NvFlowReflectDeepCopy_structRecursive(ptr, luid, dstArray + childReflectData.dataOffset, childReflectData.dataType, 1u, NV_FLOW_FALSE);
}
if (childReflectData.reflectMode & eNvFlowReflectMode_pointerArray)
{
// get pointer to pointer
NvFlowUint8** childPtr = (NvFlowUint8**)(dstArray + childReflectData.dataOffset);
NvFlowUint64 childElementCount = 1u;
NvFlowUint64 childVersion = 0u;
if ((*childPtr))
{
if (childReflectData.reflectMode & eNvFlowReflectMode_array)
{
childElementCount = *(NvFlowUint64*)(dstArray + childReflectData.arraySizeOffset);
}
if (childReflectData.reflectMode & eNvFlowReflectMode_valueVersioned)
{
childVersion = *(NvFlowUint64*)(dstArray + childReflectData.versionOffset);
}
NvFlowBool32 isPointerArray = (childReflectData.reflectMode & eNvFlowReflectMode_pointerArray) == eNvFlowReflectMode_pointerArray;
// conditionally attempt cached array
if (luid > 0u && childElementCount > 0u && childVersion > 0u && childReflectData.dataType->dataType != eNvFlowType_struct)
{
*childPtr = NvFlowReflectDeepCopy_cached(ptr, luid, *childPtr, childReflectData.dataType, childElementCount, childVersion, isPointerArray);
}
else
{
// recurse
*childPtr = NvFlowReflectDeepCopy_recursive(ptr, luid, *childPtr, childReflectData.dataType, childElementCount, isPointerArray);
}
}
}
ptr->pathStack.size--;
}
}
}
}
NV_FLOW_INLINE NvFlowUint8* NvFlowReflectDeepCopy_recursive(NvFlowReflectDeepCopy* ptr, NvFlowUint64 luid, const NvFlowUint8* src, const NvFlowReflectDataType* type, NvFlowUint64 elementCount, NvFlowBool32 isPointerArray)
{
const char* debugName = "root";
if (ptr->pathStack.size > 0u)
{
debugName = ptr->pathStack[ptr->pathStack.size - 1u];
}
if (isPointerArray)
{
NvFlowUint8* dstData = NvFlowReflectDeepCopy_allocate(ptr, sizeof(void*) * elementCount, debugName);
memcpy(dstData, src, sizeof(void*) * elementCount);
// for each non-null pointer, recurse
NvFlowUint8** dstArray = (NvFlowUint8**)dstData;
for (NvFlowUint64 elementIdx = 0u; elementIdx < elementCount; elementIdx++)
{
if (dstArray[elementIdx])
{
dstArray[elementIdx] = NvFlowReflectDeepCopy_recursive(ptr, luid, dstArray[elementIdx], type, 1u, NV_FLOW_FALSE);
}
}
return dstData;
}
NvFlowUint8* dstData = NvFlowReflectDeepCopy_allocate(ptr, type->elementSize * elementCount, debugName);
memcpy(dstData, src, type->elementSize * elementCount);
NvFlowReflectDeepCopy_structRecursive(ptr, luid, dstData, type, elementCount, isPointerArray);
return dstData;
}
NV_FLOW_INLINE NvFlowUint8* NvFlowReflectDeepCopy_update(NvFlowReflectDeepCopy* ptr, const void* srcVoid, const NvFlowReflectDataType* type)
{
const NvFlowUint8* src = (const NvFlowUint8*)srcVoid;
NvFlowReflectDeepCopy_reset(ptr);
NvFlowReflectDeepCopy_cleanCache(ptr);
return NvFlowReflectDeepCopy_recursive(ptr, 0llu, src, type, 1u, NV_FLOW_FALSE);
} |
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowUploadBuffer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowContext.h"
#include "NvFlowArray.h"
#define NV_FLOW_DISPATCH_BATCH_SIZE 32768u
//#define NV_FLOW_DISPATCH_BATCH_SIZE 256
struct NvFlowDispatchBatch
{
NvFlowBufferTransient* globalTransient = nullptr;
NvFlowUint blockIdxOffset = 0u;
NvFlowUint blockCount = 0u;
};
typedef NvFlowArray<NvFlowDispatchBatch, 8u> NvFlowDispatchBatches;
NV_FLOW_INLINE void NvFlowDispatchBatches_init_custom(NvFlowDispatchBatches* ptr, NvFlowUint totalBlockCount, NvFlowUint batchSize)
{
ptr->size = 0u;
for (NvFlowUint blockIdxOffset = 0u; blockIdxOffset < totalBlockCount; blockIdxOffset += batchSize)
{
NvFlowDispatchBatch batch = {};
batch.globalTransient = nullptr;
batch.blockIdxOffset = blockIdxOffset;
batch.blockCount = totalBlockCount - blockIdxOffset;
if (batch.blockCount > batchSize)
{
batch.blockCount = batchSize;
}
ptr->pushBack(batch);
}
}
NV_FLOW_INLINE void NvFlowDispatchBatches_init(NvFlowDispatchBatches* ptr, NvFlowUint totalBlockCount)
{
NvFlowDispatchBatches_init_custom(ptr, totalBlockCount, NV_FLOW_DISPATCH_BATCH_SIZE);
}
struct NvFlowBufferVersioning
{
NvFlowUint64 mappedIdx = ~0llu;
NvFlowUint64 frontIdx = ~0llu;
NvFlowArray<NvFlowUint64, 16u> recycleFenceValues;
};
NV_FLOW_INLINE NvFlowUint64 NvFlowBufferVersioning_map(NvFlowBufferVersioning* ptr, NvFlowUint64 lastFenceCompleted)
{
NvFlowUint64 index = ptr->frontIdx + 1u;
for (; index < ptr->recycleFenceValues.size; index++)
{
if (ptr->recycleFenceValues[index] <= lastFenceCompleted)
{
break;
}
}
if (index == ptr->recycleFenceValues.size)
{
for (index = 0; index < ptr->frontIdx; index++)
{
if (ptr->recycleFenceValues[index] <= lastFenceCompleted)
{
break;
}
}
}
if (!(index < ptr->recycleFenceValues.size && ptr->recycleFenceValues[index] <= lastFenceCompleted))
{
index = ptr->recycleFenceValues.allocateBack();
}
ptr->recycleFenceValues[index] = ~0llu;
ptr->mappedIdx = index;
return ptr->mappedIdx;
}
NV_FLOW_INLINE void NvFlowBufferVersioning_unmap(NvFlowBufferVersioning* ptr, NvFlowUint64 nextFenceValue)
{
if (ptr->frontIdx < ptr->recycleFenceValues.size)
{
ptr->recycleFenceValues[ptr->frontIdx] = nextFenceValue;
}
ptr->frontIdx = ptr->mappedIdx;
}
struct NvFlowUploadBuffer
{
NvFlowContextInterface* contextInterface = nullptr;
NvFlowBuffer*(NV_FLOW_ABI* createBuffer)(NvFlowContext* context, NvFlowMemoryType memoryType, const NvFlowBufferDesc* desc, void* userdata) = nullptr;
void(NV_FLOW_ABI* addPassCopyBuffer)(NvFlowContext* context, const NvFlowPassCopyBufferParams* params, void* userdata) = nullptr;
void* userdata = nullptr;
NvFlowBufferUsageFlags flags = 0u;
NvFlowFormat format = eNvFlowFormat_unknown;
NvFlowUint structureStride = 0u;
NvFlowBufferVersioning versioning;
NvFlowArray<NvFlowBuffer*, 8u> buffers;
NvFlowArray<NvFlowUint64, 8u> bufferSizes;
NvFlowBuffer* deviceBuffer = nullptr;
NvFlowUint64 deviceNumBytes = 0llu;
};
NV_FLOW_INLINE void NvFlowUploadBuffer_init_custom(
NvFlowContextInterface* contextInterface,
NvFlowContext* context, NvFlowUploadBuffer* ptr,
NvFlowBufferUsageFlags flags, NvFlowFormat format, NvFlowUint structureStride,
NvFlowBuffer*(NV_FLOW_ABI* createBuffer)(NvFlowContext* context, NvFlowMemoryType memoryType, const NvFlowBufferDesc* desc, void* userdata),
void(NV_FLOW_ABI* addPassCopyBuffer)(NvFlowContext* context, const NvFlowPassCopyBufferParams* params, void* userdata),
void* userdata
)
{
ptr->contextInterface = contextInterface;
ptr->createBuffer = createBuffer;
ptr->addPassCopyBuffer = addPassCopyBuffer;
ptr->userdata = userdata;
ptr->flags = flags;
ptr->format = format;
ptr->structureStride = structureStride;
}
NV_FLOW_INLINE NvFlowBuffer* NvFlowUploadBuffer_createBuffer(NvFlowContext* context, NvFlowMemoryType memoryType, const NvFlowBufferDesc* desc, void* userdata)
{
NvFlowUploadBuffer* ptr = (NvFlowUploadBuffer*)userdata;
return ptr->contextInterface->createBuffer(context, memoryType, desc);
}
NV_FLOW_INLINE void NvFlowUploadBuffer_addPassCopyBuffer(NvFlowContext* context, const NvFlowPassCopyBufferParams* params, void* userdata)
{
NvFlowUploadBuffer* ptr = (NvFlowUploadBuffer*)userdata;
ptr->contextInterface->addPassCopyBuffer(context, params);
}
NV_FLOW_INLINE void NvFlowUploadBuffer_init(NvFlowContextInterface* contextInterface, NvFlowContext* context, NvFlowUploadBuffer* ptr, NvFlowBufferUsageFlags flags, NvFlowFormat format, NvFlowUint structureStride)
{
NvFlowUploadBuffer_init_custom(contextInterface, context, ptr, flags, format, structureStride, NvFlowUploadBuffer_createBuffer, NvFlowUploadBuffer_addPassCopyBuffer, ptr);
}
NV_FLOW_INLINE void NvFlowUploadBuffer_destroy(NvFlowContext* context, NvFlowUploadBuffer* ptr)
{
for (NvFlowUint64 idx = 0u; idx < ptr->buffers.size; idx++)
{
if (ptr->buffers[idx])
{
ptr->contextInterface->destroyBuffer(context, ptr->buffers[idx]);
ptr->buffers[idx] = nullptr;
}
}
ptr->buffers.size = 0u;
ptr->bufferSizes.size = 0u;
if (ptr->deviceBuffer)
{
ptr->contextInterface->destroyBuffer(context, ptr->deviceBuffer);
ptr->deviceBuffer = nullptr;
}
}
NV_FLOW_INLINE NvFlowUint64 NvFlowUploadBuffer_computeBufferSize(NvFlowUint64 requested)
{
NvFlowUint64 bufferSize = 65536u;
while (bufferSize < requested)
{
bufferSize *= 2u;
}
return bufferSize;
}
NV_FLOW_INLINE void* NvFlowUploadBuffer_map(NvFlowContext* context, NvFlowUploadBuffer* ptr, NvFlowUint64 numBytes)
{
NvFlowUint64 instanceIdx = NvFlowBufferVersioning_map(&ptr->versioning, ptr->contextInterface->getLastFrameCompleted(context));
while (instanceIdx >= ptr->buffers.size)
{
ptr->buffers.pushBack(nullptr);
ptr->bufferSizes.pushBack(0llu);
}
if (ptr->buffers[instanceIdx] && ptr->bufferSizes[instanceIdx] < numBytes)
{
ptr->contextInterface->destroyBuffer(context, ptr->buffers[instanceIdx]);
ptr->buffers[instanceIdx] = nullptr;
}
if (!ptr->buffers[instanceIdx])
{
NvFlowBufferDesc bufDesc = {};
bufDesc.format = ptr->format;
bufDesc.usageFlags = ptr->flags;
bufDesc.structureStride = ptr->structureStride;
bufDesc.sizeInBytes = NvFlowUploadBuffer_computeBufferSize(numBytes);
ptr->bufferSizes[instanceIdx] = bufDesc.sizeInBytes;
ptr->buffers[instanceIdx] = ptr->contextInterface->createBuffer(context, eNvFlowMemoryType_upload, &bufDesc);
}
return ptr->contextInterface->mapBuffer(context, ptr->buffers[instanceIdx]);
}
NV_FLOW_INLINE NvFlowBufferTransient* NvFlowUploadBuffer_unmap(NvFlowContext* context, NvFlowUploadBuffer* ptr)
{
ptr->contextInterface->unmapBuffer(context, ptr->buffers[ptr->versioning.mappedIdx]);
NvFlowBufferVersioning_unmap(&ptr->versioning, ptr->contextInterface->getCurrentFrame(context));
return ptr->contextInterface->registerBufferAsTransient(context, ptr->buffers[ptr->versioning.frontIdx]);
}
struct NvFlowUploadBufferCopyRange
{
NvFlowUint64 offset;
NvFlowUint64 numBytes;
};
NV_FLOW_INLINE NvFlowBufferTransient* NvFlowUploadBuffer_getDevice(NvFlowContext* context, NvFlowUploadBuffer* ptr, NvFlowUint64 numBytes)
{
NvFlowUint64 srcNumBytes = NvFlowUploadBuffer_computeBufferSize(numBytes);
if (ptr->deviceBuffer && ptr->deviceNumBytes < srcNumBytes)
{
ptr->contextInterface->destroyBuffer(context, ptr->deviceBuffer);
ptr->deviceBuffer = nullptr;
ptr->deviceNumBytes = 0llu;
}
if (!ptr->deviceBuffer)
{
NvFlowBufferDesc bufDesc = {};
bufDesc.format = ptr->format;
bufDesc.usageFlags = ptr->flags | eNvFlowBufferUsage_bufferCopyDst;
bufDesc.structureStride = ptr->structureStride;
bufDesc.sizeInBytes = srcNumBytes;
ptr->deviceBuffer = ptr->createBuffer(context, eNvFlowMemoryType_device, &bufDesc, ptr->userdata);
ptr->deviceNumBytes = srcNumBytes;
}
return ptr->contextInterface->registerBufferAsTransient(context, ptr->deviceBuffer);
}
NV_FLOW_INLINE NvFlowBufferTransient* NvFlowUploadBuffer_unmapDeviceN(NvFlowContext* context, NvFlowUploadBuffer* ptr, NvFlowUploadBufferCopyRange* copyRanges, NvFlowUint64 copyRangeCount, const char* debugName)
{
NvFlowBufferTransient* src = NvFlowUploadBuffer_unmap(context, ptr);
NvFlowUint64 srcNumBytes = ptr->bufferSizes[ptr->versioning.frontIdx];
NvFlowBufferTransient* dst = NvFlowUploadBuffer_getDevice(context, ptr, srcNumBytes);
NvFlowUint activeCopyCount = 0u;
for (NvFlowUint64 copyRangeIdx = 0u; copyRangeIdx < copyRangeCount; copyRangeIdx++)
{
NvFlowPassCopyBufferParams copyParams = {};
copyParams.srcOffset = copyRanges[copyRangeIdx].offset;
copyParams.dstOffset = copyRanges[copyRangeIdx].offset;
copyParams.numBytes = copyRanges[copyRangeIdx].numBytes;
copyParams.src = src;
copyParams.dst = dst;
copyParams.debugLabel = debugName ? debugName : "UploadBufferUnmapDevice";
if (copyParams.numBytes > 0u)
{
ptr->addPassCopyBuffer(context, ©Params, ptr->userdata);
activeCopyCount++;
}
}
// this ensures proper barriers
if (activeCopyCount == 0u)
{
NvFlowPassCopyBufferParams copyParams = {};
copyParams.srcOffset = 0llu;
copyParams.dstOffset = 0llu;
copyParams.numBytes = 0llu;
copyParams.src = src;
copyParams.dst = dst;
copyParams.debugLabel = debugName ? debugName : "UploadBufferUnmapDevice";
ptr->addPassCopyBuffer(context, ©Params, ptr->userdata);
}
return dst;
}
NV_FLOW_INLINE NvFlowBufferTransient* NvFlowUploadBuffer_unmapDevice(NvFlowContext* context, NvFlowUploadBuffer* ptr, NvFlowUint64 offset, NvFlowUint64 numBytes, const char* debugName)
{
NvFlowUploadBufferCopyRange copyRange = { offset, numBytes };
return NvFlowUploadBuffer_unmapDeviceN(context, ptr, ©Range, 1u, debugName);
} |
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowPreprocessor.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowString.h"
struct NvFlowPreprocessor;
struct NvFlowPreprocessorRange
{
NvFlowUint64 begin;
NvFlowUint64 end;
};
enum NvFlowPreprocessorTokenType
{
eNvFlowPreprocessorTokenType_unknown = 0, // unclassified
eNvFlowPreprocessorTokenType_whitespace, //
eNvFlowPreprocessorTokenType_newline, // \n
eNvFlowPreprocessorTokenType_comment, // // comment
eNvFlowPreprocessorTokenType_name, // alpha_1234
eNvFlowPreprocessorTokenType_number, // 1234
eNvFlowPreprocessorTokenType_string, // "string"
eNvFlowPreprocessorTokenType_char, // 's'
eNvFlowPreprocessorTokenType_pound, // #
eNvFlowPreprocessorTokenType_comma, // ,
eNvFlowPreprocessorTokenType_period, // .
eNvFlowPreprocessorTokenType_semicolon, // ;
eNvFlowPreprocessorTokenType_colon, // :
eNvFlowPreprocessorTokenType_equals, // =
eNvFlowPreprocessorTokenType_asterisk, // *
eNvFlowPreprocessorTokenType_leftParenthesis, // (
eNvFlowPreprocessorTokenType_rightParenthesis, // )
eNvFlowPreprocessorTokenType_leftBracket, // [
eNvFlowPreprocessorTokenType_rightBracket, // ]
eNvFlowPreprocessorTokenType_leftCurlyBrace, // {
eNvFlowPreprocessorTokenType_rightCurlyBrace, // }
eNvFlowPreprocessorTokenType_lessThan, // <
eNvFlowPreprocessorTokenType_greaterThan, // >
eNvFlowPreprocessorTokenType_anyWhitespace, // For delimiter usage, aligns with NvFlowPreprocessorTokenIsWhitespace()
eNvFlowPreprocessorTokenType_count,
eNvFlowPreprocessorTokenType_maxEnum = 0x7FFFFFFF
};
struct NvFlowPreprocessorToken
{
NvFlowPreprocessorTokenType type;
const char* str;
};
NV_FLOW_INLINE NvFlowBool32 NvFlowPreprocessorTokenIsWhitespace(const NvFlowPreprocessorToken token)
{
return token.type == eNvFlowPreprocessorTokenType_whitespace ||
token.type == eNvFlowPreprocessorTokenType_newline ||
token.type == eNvFlowPreprocessorTokenType_comment;
}
NV_FLOW_INLINE void NvFlowPreprocessorSkipWhitespaceTokens(NvFlowUint64* pTokenIdx, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens)
{
while ((*pTokenIdx) < numTokens && NvFlowPreprocessorTokenIsWhitespace(tokens[(*pTokenIdx)]))
{
(*pTokenIdx)++;
}
}
enum NvFlowPreprocessorType
{
eNvFlowPreprocessorType_constant = 0, // name
eNvFlowPreprocessorType_statement = 1, // name arg0 arg1;
eNvFlowPreprocessorType_function = 2, // name(arg0, arg1, arg2)
eNvFlowPreprocessorType_index = 3, // name[arg0] or name[arg0]= arg1 arg2 arg3;
eNvFlowPreprocessorType_attribute = 4, // [name(arg0, arg1, arg2)]
eNvFlowPreprocessorType_line = 5, // #name arg0 \n
eNvFlowPreprocessorType_body = 6, // name <arg0, arg1> arg2 arg3(arg4, arg5) { arg6; arg7; }
eNvFlowPreprocessorType_templateInstance = 7, // name<arg0, arg1>
eNvFlowPreprocessorType_statementComma = 8, // "name arg0," or "name arg0)"
eNvFlowPreprocessorType_maxEnum = 0x7FFFFFFF
};
struct NvFlowPreprocessorConstant
{
const char* name;
const char* value;
};
struct NvFlowPreprocessorFunction
{
const char* name;
NvFlowPreprocessorType type;
void* userdata;
char*(*substitute)(NvFlowPreprocessor* ptr, void* userdata, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens);
NvFlowBool32 allowRecursion;
};
enum NvFlowPreprocessorMode
{
eNvFlowPreprocessorMode_default = 0, // Input string evaluated and substitution evaluated, no recursion
eNvFlowPreprocessorMode_singlePass = 1, // Input string evaluated once, no substitution evaluation
eNvFlowPreprocessorMode_disable_passthrough = 2, // Do not passthrough strings
eNvFlowPreprocessorMode_maxEnum = 0x7FFFFFFF
};
NvFlowPreprocessor* NvFlowPreprocessorCreate(NvFlowStringPool* pool);
void NvFlowPreprocessorDestroy(NvFlowPreprocessor* ptr);
void NvFlowPreprocessorReset(NvFlowPreprocessor* ptr);
void NvFlowPreprocessorSetMode(NvFlowPreprocessor* ptr, NvFlowPreprocessorMode mode);
NvFlowPreprocessorMode NvFlowPreprocessorGetMode(NvFlowPreprocessor* ptr);
NvFlowStringPool* NvFlowPreprocessorStringPool(NvFlowPreprocessor* ptr);
void NvFlowPreprocessorAddConstants(NvFlowPreprocessor* ptr, NvFlowUint64 numConstants, const NvFlowPreprocessorConstant* constants);
void NvFlowPreprocessorAddFunctions(NvFlowPreprocessor* ptr, NvFlowUint64 numFunctions, const NvFlowPreprocessorFunction* functions);
NvFlowPreprocessorRange NvFlowPreprocessorExtractTokensDelimitedN(NvFlowPreprocessor* ptr, NvFlowUint64* pTokenIdx, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens, NvFlowUint64 numDelimiters, const NvFlowPreprocessorTokenType* delimiters);
NvFlowPreprocessorRange NvFlowPreprocessorExtractTokensDelimited(NvFlowPreprocessor* ptr, NvFlowUint64* pTokenIdx, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens, NvFlowPreprocessorTokenType delimiter);
const char* NvFlowPreprocessorExtractDelimited(NvFlowPreprocessor* ptr, NvFlowUint64* pTokenIdx, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens, NvFlowPreprocessorTokenType delimiter);
const char* NvFlowPreprocessorExtractDelimitedN(NvFlowPreprocessor* ptr, NvFlowUint64* pTokenIdx, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens, NvFlowUint64 numDelimiters, const NvFlowPreprocessorTokenType* delimiters);
const char* NvFlowPreprocessorExtractDelimitedPreserve(NvFlowPreprocessor* ptr, NvFlowUint64* pTokenIdx, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens, NvFlowPreprocessorTokenType delimiter);
const char* NvFlowPreprocessorExtractIfType(NvFlowPreprocessor* ptr, NvFlowUint64* pTokenIdx, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens, NvFlowPreprocessorTokenType type);
const char* NvFlowPreprocessorConcatTokens(NvFlowPreprocessor* ptr, const NvFlowPreprocessorToken* tokens, NvFlowUint64 numTokens);
NvFlowBool32 NvFlowPreprocessorFindKeyInSource(NvFlowPreprocessor* ptr, const NvFlowPreprocessorToken* keyTokens, NvFlowUint64 keyTokenCount, const NvFlowPreprocessorToken* sourceTokens, NvFlowUint64 sourceTokenCount, NvFlowUint64* pSourceIndex);
char* NvFlowPreprocessorExecute(NvFlowPreprocessor* ptr, const char* input);
void NvFlowPreprocessorTokenize(NvFlowPreprocessor* ptr, const char* input, NvFlowUint64* pTotalTokens, NvFlowPreprocessorToken** pTokens);
enum NvFlowPreprocessorGlobalType
{
eNvFlowPreprocessorGlobalType_unknown = 0, // Unknown global type
eNvFlowPreprocessorGlobalType_statement = 1, // ConstantBuffer<Params> gParams;
eNvFlowPreprocessorGlobalType_function = 2, // returnType functionName(arg1, arg2, arg3) { [functionbody] }
eNvFlowPreprocessorGlobalType_attribute = 3, // [name(arg0, arg1, arg2)]
eNvFlowPreprocessorGlobalType_line = 4, // #define CONSTANT \n
eNvFlowPreprocessorGlobalType_maxEnum = 0x7FFFFFFF
};
char* NvFlowPreprocessorExecuteGlobal(NvFlowPreprocessor* ptr, const char* input, void* userdata, char*(*substitute)(NvFlowPreprocessor* ptr, void* userdata, NvFlowPreprocessorGlobalType globalType, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens)); |
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowDatabase.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowReflect.h"
#include "NvFlowArray.h"
#include "NvFlowDeepCopy.h"
#include <string.h>
struct NvFlowDatabaseContext;
struct NvFlowDatabasePrim;
struct NvFlowDatabaseAttr;
struct NvFlowDatabaseInterface
{
NvFlowDatabasePrim*(NV_FLOW_ABI *createPrim)(
NvFlowDatabaseContext* context,
NvFlowUint64 version,
NvFlowDatabasePrim* parent,
const char* displayTypename,
const char* path,
const char* name);
void(NV_FLOW_ABI* updatePrim)(
NvFlowDatabaseContext* context,
NvFlowUint64 version,
NvFlowUint64 minActiveVersion,
NvFlowDatabasePrim* prim);
void(NV_FLOW_ABI* markDestroyedPrim)(NvFlowDatabaseContext* context, NvFlowDatabasePrim* prim);
void(NV_FLOW_ABI* destroyPrim)(NvFlowDatabaseContext* context, NvFlowDatabasePrim* prim);
NvFlowDatabaseAttr*(NV_FLOW_ABI* createAttr)(
NvFlowDatabaseContext* context,
NvFlowUint64 version,
NvFlowDatabasePrim* prim,
const NvFlowReflectData* reflectData,
NvFlowUint8* mappedData);
void(NV_FLOW_ABI* updateAttr)(
NvFlowDatabaseContext* context,
NvFlowUint64 version,
NvFlowUint64 minActiveVersion,
NvFlowDatabaseAttr* attr,
const NvFlowReflectData* reflectData,
NvFlowUint8* mappedData);
void(NV_FLOW_ABI* markDestroyedAttr)(NvFlowDatabaseContext* context, NvFlowDatabaseAttr* attr);
void(NV_FLOW_ABI* destroyAttr)(NvFlowDatabaseContext* context, NvFlowDatabaseAttr* attr);
};
struct NvFlowDatabaseString
{
NvFlowArray<char> data;
void append(const char* str)
{
if (data.size > 0u)
{
data.size--;
}
if (str)
{
NvFlowUint64 idx = 0u;
while (str[idx])
{
data.pushBack(str[idx]);
idx++;
}
data.pushBack('\0');
}
}
void set(const char* str)
{
data.size = 0u;
append(str);
}
const char* get()
{
return data.data;
}
};
struct NvFlowDatabaseInstance
{
struct Prim
{
NvFlowDatabasePrim* prim;
NvFlowArrayPointer<Prim*> childPrims;
NvFlowArray<NvFlowDatabaseAttr*> attrs;
NvFlowDatabaseString path;
};
struct Data
{
NvFlowArray<NvFlowUint8> data;
NvFlowUint64 version;
NvFlowReflectDeepCopy* deepCopy = nullptr;
~Data()
{
if (deepCopy)
{
NvFlowReflectDeepCopy_destroy(deepCopy);
deepCopy = nullptr;
}
}
};
const NvFlowReflectDataType* dataType = nullptr;
NvFlowDatabaseString displayTypename;
NvFlowDatabaseString name;
NvFlowUint64 luid = 0llu;
NvFlowUint64 luidByteOffset = ~0llu;
Prim rootPrim;
NvFlowRingBufferPointer<Data*> datas;
NvFlowBool32 markedForDestroy = NV_FLOW_FALSE;
NvFlowArray<NvFlowUint8> defaultData;
struct StackState
{
NvFlowUint64 childIdx;
const NvFlowReflectDataType* reflectDataType;
NvFlowUint8* data;
Prim* prim;
};
NvFlowUint8* mapDataVersionAndType(NvFlowUint64 version, const NvFlowReflectDataType** pReflectDataType)
{
for (NvFlowUint64 idx = datas.activeCount() - 1u; idx < datas.activeCount(); idx--)
{
if (datas[idx]->version == version)
{
if (pReflectDataType)
{
*pReflectDataType = dataType;
}
return datas[idx]->data.data;
}
}
NvFlowDatabaseInstance::Data* data = datas.allocateBackPointer();
data->version = version;
data->data.reserve(dataType->elementSize);
data->data.size = dataType->elementSize;
if (datas.activeCount() >= 2u)
{
NvFlowDatabaseInstance::Data* oldData = datas[datas.activeCount() - 2u];
memcpy(data->data.data, oldData->data.data, data->data.size);
}
else if (dataType->defaultValue)
{
memcpy(data->data.data, dataType->defaultValue, data->data.size);
}
else
{
memset(data->data.data, 0, data->data.size);
}
// enforce luid
if (luidByteOffset < dataType->elementSize)
{
*((NvFlowUint64*)(data->data.data + luidByteOffset)) = luid;
}
if (pReflectDataType)
{
*pReflectDataType = dataType;
}
return data->data.data;
}
NvFlowUint8* mapDataVersion(NvFlowUint64 version)
{
const NvFlowReflectDataType* reflectDataType = nullptr;
return mapDataVersionAndType(version, &reflectDataType);
}
void deepCopyDataVersion(NvFlowUint64 version)
{
Data* data = nullptr;
for (NvFlowUint64 idx = datas.activeCount() - 1u; idx < datas.activeCount(); idx--)
{
if (datas[idx]->version == version)
{
data = datas[idx];
}
}
if (data)
{
if (!data->deepCopy)
{
data->deepCopy = NvFlowReflectDeepCopy_create();
}
NvFlowUint8* copyData = NvFlowReflectDeepCopy_update(data->deepCopy, data->data.data, dataType);
// copy root struct over mapped to get safe pointers
memcpy(data->data.data, copyData, data->data.size);
}
}
NvFlowUint8* mapDataVersionReadOnly(NvFlowUint64 version)
{
// TODO: Simply update version to avoid copy
return mapDataVersion(version);
}
template<const NvFlowDatabaseInterface* iface>
void init(NvFlowDatabaseContext* context, NvFlowUint64 version, NvFlowUint64 luidIn, const NvFlowReflectDataType* dataTypeIn, const char* displayTypenameIn, const char* pathIn, const char* nameIn)
{
dataType = dataTypeIn;
displayTypename.set(displayTypenameIn);
name.set(nameIn);
luid = luidIn;
luidByteOffset = ~0llu;
// try to find luid offset in root
for (NvFlowUint64 childIdx = 0u; childIdx < dataType->childReflectDataCount; childIdx++)
{
if (strcmp(dataType->childReflectDatas[childIdx].name, "luid") == 0)
{
luidByteOffset = dataType->childReflectDatas[childIdx].dataOffset;
break;
}
}
rootPrim.path.set(pathIn);
rootPrim.prim = nullptr;
if (iface->createPrim)
{
rootPrim.prim = iface->createPrim(
context,
version,
nullptr,
displayTypename.get(),
rootPrim.path.get(),
name.get());
}
NvFlowUint8* mappedData = mapDataVersion(version);
StackState state = { 0llu, dataType, mappedData, &rootPrim };
NvFlowArray<StackState, 8u> stateStack;
for (; state.childIdx < state.reflectDataType->childReflectDataCount; state.childIdx++)
{
// push prims
while (state.reflectDataType->childReflectDatas[state.childIdx].dataType->dataType == eNvFlowType_struct)
{
const NvFlowReflectData* childReflectData = state.reflectDataType->childReflectDatas + state.childIdx;
auto childPrim = state.prim->childPrims.allocateBackPointer();
state.prim->attrs.pushBack(nullptr);
// form path
childPrim->path.set(state.prim->path.get());
childPrim->path.append("/");
childPrim->path.append(childReflectData->name);
childPrim->prim = nullptr;
if (iface->createPrim)
{
childPrim->prim = iface->createPrim(
context,
version,
state.prim->prim,
NvFlowReflectTrimPrefix(childReflectData->dataType->structTypename),
childPrim->path.get(),
childReflectData->name);
}
stateStack.pushBack(state);
state.childIdx = 0u;
state.reflectDataType = childReflectData->dataType;
state.data += childReflectData->dataOffset;
state.prim = childPrim;
}
// attributes
if (state.childIdx < state.reflectDataType->childReflectDataCount)
{
const NvFlowReflectData* childReflectData = state.reflectDataType->childReflectDatas + state.childIdx;
NvFlowDatabaseAttr* attr = nullptr;
if (iface->createAttr)
{
attr = iface->createAttr(context, version, state.prim->prim, childReflectData, state.data);
}
state.prim->attrs.pushBack(attr);
state.prim->childPrims.pushBack(nullptr);
}
// pop prims
while (state.childIdx + 1u >= state.reflectDataType->childReflectDataCount && stateStack.size > 0u)
{
state = stateStack.back();
stateStack.popBack();
}
}
}
void process(NvFlowUint64 version, NvFlowReflectProcess_t processReflect, void* userdata)
{
NvFlowUint8* mappedData = mapDataVersion(version);
processReflect(mappedData, dataType, userdata);
}
template<const NvFlowDatabaseInterface* iface>
void update(NvFlowDatabaseContext* context, NvFlowUint64 version, NvFlowUint64 minActiveVersion)
{
if (!markedForDestroy)
{
NvFlowUint8* mappedData = mapDataVersion(version);
if (rootPrim.prim)
{
iface->updatePrim(context, version, minActiveVersion, rootPrim.prim);
}
StackState state = { 0llu, dataType, mappedData, &rootPrim };
NvFlowArray<StackState, 8u> stateStack;
for (; state.childIdx < state.reflectDataType->childReflectDataCount; state.childIdx++)
{
// push prims
while (state.reflectDataType->childReflectDatas[state.childIdx].dataType->dataType == eNvFlowType_struct)
{
const NvFlowReflectData* childReflectData = state.reflectDataType->childReflectDatas + state.childIdx;
auto childPrim = state.prim->childPrims[state.childIdx];
if (childPrim->prim)
{
iface->updatePrim(context, version, minActiveVersion, childPrim->prim);
}
stateStack.pushBack(state);
state.childIdx = 0u;
state.reflectDataType = childReflectData->dataType;
state.data += childReflectData->dataOffset;
state.prim = childPrim;
}
// attributes
if (state.childIdx < state.reflectDataType->childReflectDataCount)
{
const NvFlowReflectData* childReflectData = state.reflectDataType->childReflectDatas + state.childIdx;
auto attr = state.prim->attrs[state.childIdx];
if (attr)
{
iface->updateAttr(context, version, minActiveVersion, attr, childReflectData, state.data);
}
}
// pop prims
while (state.childIdx + 1u >= state.reflectDataType->childReflectDataCount && stateStack.size > 0u)
{
state = stateStack.back();
stateStack.popBack();
}
}
}
NvFlowUint freeTreshold = markedForDestroy ? 0u : 1u;
while (datas.activeCount() > freeTreshold && datas.front()->version < minActiveVersion)
{
datas.popFront();
}
}
template<const NvFlowDatabaseInterface* iface>
void markForDestroy(NvFlowDatabaseContext* context)
{
NvFlowUint8* mappedData = nullptr;
StackState state = { 0llu, dataType, mappedData, &rootPrim };
NvFlowArray<StackState, 8u> stateStack;
for (; state.childIdx < state.reflectDataType->childReflectDataCount; state.childIdx++)
{
// push prims
while (state.reflectDataType->childReflectDatas[state.childIdx].dataType->dataType == eNvFlowType_struct)
{
const NvFlowReflectData* childReflectData = state.reflectDataType->childReflectDatas + state.childIdx;
auto childPrim = state.prim->childPrims[state.childIdx];
stateStack.pushBack(state);
state.childIdx = 0u;
state.reflectDataType = childReflectData->dataType;
state.data += childReflectData->dataOffset;
state.prim = childPrim;
}
// attributes
if (state.childIdx < state.reflectDataType->childReflectDataCount)
{
auto attr = state.prim->attrs[state.childIdx];
if (attr)
{
iface->markDestroyedAttr(context, attr);
}
}
// pop prims
while (state.childIdx + 1u >= state.reflectDataType->childReflectDataCount && stateStack.size > 0u)
{
if (state.prim->prim)
{
iface->markDestroyedPrim(context, state.prim->prim);
}
state = stateStack.back();
stateStack.popBack();
}
}
if (rootPrim.prim)
{
iface->markDestroyedPrim(context, rootPrim.prim);
}
markedForDestroy = NV_FLOW_TRUE;
}
template<const NvFlowDatabaseInterface* iface>
void destroy(NvFlowDatabaseContext* context)
{
NvFlowUint8* mappedData = nullptr;
StackState state = { 0llu, dataType, mappedData, &rootPrim };
NvFlowArray<StackState, 8u> stateStack;
for (; state.childIdx < state.reflectDataType->childReflectDataCount; state.childIdx++)
{
// push prims
while (state.reflectDataType->childReflectDatas[state.childIdx].dataType->dataType == eNvFlowType_struct)
{
const NvFlowReflectData* childReflectData = state.reflectDataType->childReflectDatas + state.childIdx;
auto childPrim = state.prim->childPrims[state.childIdx];
stateStack.pushBack(state);
state.childIdx = 0u;
state.reflectDataType = childReflectData->dataType;
state.data += childReflectData->dataOffset;
state.prim = childPrim;
}
// attributes
if (state.childIdx < state.reflectDataType->childReflectDataCount)
{
auto attr = state.prim->attrs[state.childIdx];
if (attr)
{
iface->destroyAttr(context, attr);
attr = nullptr;
}
}
// pop prims
while (state.childIdx + 1u >= state.reflectDataType->childReflectDataCount && stateStack.size > 0u)
{
if (state.prim->prim)
{
iface->destroyPrim(context, state.prim->prim);
state.prim->prim = nullptr;
}
state = stateStack.back();
stateStack.popBack();
}
}
if (rootPrim.prim)
{
iface->destroyPrim(context, rootPrim.prim);
rootPrim.prim = nullptr;
}
}
};
struct NvFlowDatabaseType
{
const NvFlowReflectDataType* dataType = nullptr;
NvFlowDatabaseString displayTypeName;
NvFlowArrayPointer<NvFlowDatabaseInstance*> instances;
struct TypeSnapshot
{
NvFlowDatabaseTypeSnapshot snapshot;
NvFlowArray<NvFlowUint8*> instanceDatas;
};
NvFlowRingBufferPointer<TypeSnapshot*> snapshots;
void init(const NvFlowReflectDataType* dataTypeIn, const char* displayTypeNameIn)
{
dataType = dataTypeIn;
displayTypeName.set(displayTypeNameIn);
}
template<const NvFlowDatabaseInterface* iface>
void update(NvFlowDatabaseContext* context, NvFlowUint64 version, NvFlowUint64 minActiveVersion)
{
for (NvFlowUint instanceIdx = 0u; instanceIdx < instances.size; instanceIdx++)
{
instances[instanceIdx]->update<iface>(context, version, minActiveVersion);
}
// release instances
{
NvFlowUint64 keepCount = 0llu;
for (NvFlowUint instanceIdx = 0u; instanceIdx < instances.size; instanceIdx++)
{
if (instances[instanceIdx]->markedForDestroy && instances[instanceIdx]->datas.activeCount() == 0u)
{
instances[instanceIdx]->destroy<iface>(context);
instances.deletePointerAtIndex(instanceIdx);
}
else
{
instances.swapPointers(keepCount, instanceIdx);
keepCount++;
}
}
instances.size = keepCount;
}
// release snapshots
while (snapshots.activeCount() > 0u && snapshots.front()->snapshot.version < minActiveVersion)
{
snapshots.popFront();
}
}
template<const NvFlowDatabaseInterface* iface>
void destroy(NvFlowDatabaseContext* context)
{
for (NvFlowUint instanceIdx = 0u; instanceIdx < instances.size; instanceIdx++)
{
instances[instanceIdx]->destroy<iface>(context);
}
instances.deletePointers();
}
void getSnapshot(NvFlowDatabaseTypeSnapshot* snapshot, NvFlowUint64 version)
{
auto ptr = snapshots.allocateBackPointer();
ptr->snapshot.version = version;
ptr->snapshot.dataType = dataType;
ptr->instanceDatas.size = 0u;
for (NvFlowUint instanceIdx = 0u; instanceIdx < instances.size; instanceIdx++)
{
if (!instances[instanceIdx]->markedForDestroy)
{
NvFlowUint8* data = instances[instanceIdx]->mapDataVersionReadOnly(version);
ptr->instanceDatas.pushBack(data);
}
}
ptr->snapshot.instanceDatas = ptr->instanceDatas.data;
ptr->snapshot.instanceCount = ptr->instanceDatas.size;
if (snapshot)
{
*snapshot = ptr->snapshot;
}
}
};
struct NvFlowDatabase
{
NvFlowArrayPointer<NvFlowDatabaseType*> types;
struct Snapshot
{
NvFlowDatabaseSnapshot snapshot;
NvFlowArray<NvFlowDatabaseTypeSnapshot> typeSnapshots;
};
NvFlowRingBufferPointer<Snapshot*> snapshots;
NvFlowUint64 luidCounter = 0llu;
NvFlowDatabaseType* createType(const NvFlowReflectDataType* dataTypeIn, const char* displayTypeName)
{
auto ptr = types.allocateBackPointer();
ptr->init(dataTypeIn, displayTypeName);
return ptr;
}
template<const NvFlowDatabaseInterface* iface>
NvFlowDatabaseInstance* createInstance(NvFlowDatabaseContext* context, NvFlowUint64 version, NvFlowDatabaseType* type, const char* pathIn, const char* name)
{
auto ptr = type->instances.allocateBackPointer();
luidCounter++;
ptr->init<iface>(context, version, luidCounter, type->dataType, type->displayTypeName.get(), pathIn, name);
return ptr;
}
template<const NvFlowDatabaseInterface* iface>
void update(NvFlowDatabaseContext* context, NvFlowUint64 version, NvFlowUint64 minActiveVersion)
{
for (NvFlowUint64 typeIdx = 0u; typeIdx < types.size; typeIdx++)
{
types[typeIdx]->update<iface>(context, version, minActiveVersion);
}
// release snapshots
while (snapshots.activeCount() > 0u && snapshots.front()->snapshot.version < minActiveVersion)
{
snapshots.popFront();
}
}
template<const NvFlowDatabaseInterface* iface>
void markInstanceForDestroy(NvFlowDatabaseContext* context, NvFlowDatabaseInstance* ptr)
{
ptr->markForDestroy<iface>(context);
}
template<const NvFlowDatabaseInterface* iface>
void markAllInstancesForDestroy(NvFlowDatabaseContext* context)
{
for (NvFlowUint64 typeIdx = 0u; typeIdx < types.size; typeIdx++)
{
NvFlowDatabaseType* type = types[typeIdx];
for (NvFlowUint instanceIdx = 0u; instanceIdx < type->instances.size; instanceIdx++)
{
type->instances[instanceIdx]->markForDestroy<iface>(context);
}
}
}
template<const NvFlowDatabaseInterface* iface>
NvFlowBool32 snapshotPending(NvFlowDatabaseContext* context, NvFlowUint64 version, NvFlowUint64 minActiveVersion)
{
update<iface>(context, version, minActiveVersion);
NvFlowBool32 anySnapshotPending = NV_FLOW_FALSE;
for (NvFlowUint64 typeIdx = 0u; typeIdx < types.size; typeIdx++)
{
if (types[typeIdx]->snapshots.activeCount() > 0u)
{
anySnapshotPending = NV_FLOW_TRUE;
}
}
if (snapshots.activeCount() > 0u)
{
anySnapshotPending = NV_FLOW_TRUE;
}
return anySnapshotPending;
}
template<const NvFlowDatabaseInterface* iface>
void destroy(NvFlowDatabaseContext* context)
{
for (NvFlowUint64 typeIdx = 0u; typeIdx < types.size; typeIdx++)
{
types[typeIdx]->destroy<iface>(context);
}
}
void getSnapshot(NvFlowDatabaseSnapshot* snapshot, NvFlowUint64 version)
{
auto ptr = snapshots.allocateBackPointer();
ptr->snapshot.version = version;
ptr->typeSnapshots.size = 0u;
for (NvFlowUint64 typeIdx = 0u; typeIdx < types.size; typeIdx++)
{
NvFlowDatabaseTypeSnapshot typeSnapshot = {};
types[typeIdx]->getSnapshot(&typeSnapshot, version);
ptr->typeSnapshots.pushBack(typeSnapshot);
}
ptr->snapshot.typeSnapshots = ptr->typeSnapshots.data;
ptr->snapshot.typeSnapshotCount = ptr->typeSnapshots.size;
if (snapshot)
{
*snapshot = ptr->snapshot;
}
}
void enumerateActiveInstances(NvFlowDatabaseInstance** pInstances, NvFlowUint64* pInstanceCount)
{
if (!pInstances && pInstanceCount)
{
NvFlowUint64 activeCount = 0llu;
for (NvFlowUint64 typeIdx = 0u; typeIdx < types.size; typeIdx++)
{
NvFlowDatabaseType* type = types[typeIdx];
for (NvFlowUint instanceIdx = 0u; instanceIdx < type->instances.size; instanceIdx++)
{
if (!type->instances[instanceIdx]->markedForDestroy)
{
activeCount++;
}
}
}
*pInstanceCount = activeCount;
}
if (pInstances && pInstanceCount)
{
NvFlowUint64 activeCount = 0llu;
for (NvFlowUint64 typeIdx = 0u; typeIdx < types.size; typeIdx++)
{
NvFlowDatabaseType* type = types[typeIdx];
for (NvFlowUint instanceIdx = 0u; instanceIdx < type->instances.size; instanceIdx++)
{
if (!type->instances[instanceIdx]->markedForDestroy)
{
if (activeCount < (*pInstanceCount))
{
pInstances[activeCount] = type->instances[instanceIdx];
activeCount++;
}
}
}
}
*pInstanceCount = activeCount;
}
}
};
|
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowLocationHashTable.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowTypes.h"
#include "NvFlowArray.h"
struct NvFlowLocationHashTableRange
{
NvFlowUint64 beginIdx;
NvFlowUint64 endIdx;
};
struct NvFlowLocationHashTable
{
NvFlowUint tableDimBits = 0llu;
NvFlowUint tableDimLessOne = 0llu;
NvFlowUint tableDim3 = 1u;
NvFlowArray<NvFlowLocationHashTableRange> ranges;
NvFlowArray<NvFlowUint64> nextIndices;
NvFlowArray<NvFlowInt4> locations;
NvFlowArray<NvFlowUint> masks;
NvFlowInt4 locationMin = { 0, 0, 0, 0 };
NvFlowInt4 locationMax = { 0, 0, 0, 0 };
NvFlowArray<NvFlowInt4> tmpLocations;
NvFlowArray<NvFlowUint> tmpMasks;
void reset()
{
tableDimBits = 0llu;
tableDimLessOne = 0llu;
tableDim3 = 1u;
ranges.size = 0u;
nextIndices.size = 0u;
NvFlowLocationHashTableRange nullRange = { ~0llu, ~0llu };
ranges.pushBack(nullRange);
locations.size = 0u;
masks.size = 0u;
}
NvFlowLocationHashTable()
{
reset();
}
void rebuildTable()
{
ranges.size = 0u;
ranges.reserve(tableDim3);
ranges.size = tableDim3;
nextIndices.size = 0u;
nextIndices.reserve(locations.size);
nextIndices.size = locations.size;
// invalidate ranges
NvFlowLocationHashTableRange nullRange = { ~0llu, ~0llu };
for (NvFlowUint64 rangeIdx = 0u; rangeIdx < ranges.size; rangeIdx++)
{
ranges[rangeIdx] = nullRange;
}
for (NvFlowUint64 locationIdx = 0u; locationIdx < locations.size; locationIdx++)
{
NvFlowInt4 location = locations[locationIdx];
NvFlowUint64 baseRangeIdx = (location.x & tableDimLessOne) |
((location.y & tableDimLessOne) << tableDimBits) |
((location.z & tableDimLessOne) << (tableDimBits + tableDimBits));
// reset next for this location
nextIndices[locationIdx] = ~0llu;
NvFlowUint64 beginIdx = ranges[baseRangeIdx].beginIdx;
NvFlowUint64 endIdx = ranges[baseRangeIdx].endIdx;
if (beginIdx >= endIdx)
{
ranges[baseRangeIdx].beginIdx = locationIdx;
ranges[baseRangeIdx].endIdx = locationIdx + 1u;
}
else if (endIdx == locationIdx)
{
ranges[baseRangeIdx].endIdx = locationIdx + 1u;
nextIndices[endIdx - 1u] = locationIdx;
}
else
{
NvFlowUint64 prevIdx = endIdx - 1u;
NvFlowUint64 currentIdx = nextIndices[prevIdx];
while (currentIdx < nextIndices.size)
{
prevIdx = currentIdx;
currentIdx = nextIndices[currentIdx];
}
nextIndices[prevIdx] = locationIdx;
}
}
}
void compactNonZeroWithLimit(NvFlowUint64 maxLocations)
{
NvFlowUint64 dstIdx = 0u;
for (NvFlowUint64 srcIdx = 0u; srcIdx < locations.size && dstIdx < maxLocations; srcIdx++)
{
if (masks[srcIdx])
{
locations[dstIdx] = locations[srcIdx];
masks[dstIdx] = masks[srcIdx];
dstIdx++;
}
}
locations.size = dstIdx;
masks.size = dstIdx;
// optimize compacted table dim
tableDimBits = 0llu;
tableDimLessOne = 0llu;
tableDim3 = 1u;
while (locations.size > tableDim3)
{
tableDimBits++;
tableDimLessOne = (1u << tableDimBits) - 1u;
tableDim3 = (1 << (tableDimBits + tableDimBits + tableDimBits));
}
rebuildTable();
}
void sort()
{
NvFlowArray_copy(tmpLocations, locations);
NvFlowArray_copy(tmpMasks, masks);
NvFlowUint64 globalOffset = 0u;
for (NvFlowUint64 baseRangeIdx = 0u; baseRangeIdx < ranges.size; baseRangeIdx++)
{
NvFlowUint64 beginIdx = ranges[baseRangeIdx].beginIdx;
NvFlowUint64 endIdx = ranges[baseRangeIdx].endIdx;
for (NvFlowUint64 currentIdx = beginIdx; currentIdx < endIdx; currentIdx++)
{
locations[globalOffset] = tmpLocations[currentIdx];
masks[globalOffset] = tmpMasks[currentIdx];
globalOffset++;
}
if (beginIdx < endIdx)
{
NvFlowUint64 currentIdx = nextIndices[endIdx - 1u];
while (currentIdx < nextIndices.size)
{
locations[globalOffset] = tmpLocations[currentIdx];
masks[globalOffset] = tmpMasks[currentIdx];
globalOffset++;
currentIdx = nextIndices[currentIdx];
}
}
}
rebuildTable();
}
NvFlowUint64 find(NvFlowInt4 location)
{
NvFlowUint64 baseRangeIdx = (location.x & tableDimLessOne) |
((location.y & tableDimLessOne) << tableDimBits) |
((location.z & tableDimLessOne) << (tableDimBits + tableDimBits));
NvFlowUint64 beginIdx = ranges[baseRangeIdx].beginIdx;
NvFlowUint64 endIdx = ranges[baseRangeIdx].endIdx;
for (NvFlowUint64 currentIdx = beginIdx; currentIdx < endIdx; currentIdx++)
{
if (location.x == locations[currentIdx].x &&
location.y == locations[currentIdx].y &&
location.z == locations[currentIdx].z &&
location.w == locations[currentIdx].w)
{
return currentIdx;
}
}
if (beginIdx < endIdx)
{
NvFlowUint64 currentIdx = nextIndices[endIdx - 1u];
while (currentIdx < nextIndices.size)
{
if (location.x == locations[currentIdx].x &&
location.y == locations[currentIdx].y &&
location.z == locations[currentIdx].z &&
location.w == locations[currentIdx].w)
{
return currentIdx;
}
currentIdx = nextIndices[currentIdx];
}
}
return ~0llu;
}
void pushNoResize(NvFlowInt4 location, NvFlowUint mask)
{
NvFlowUint64 baseRangeIdx = (location.x & tableDimLessOne) |
((location.y & tableDimLessOne) << tableDimBits) |
((location.z & tableDimLessOne) << (tableDimBits + tableDimBits));
NvFlowUint64 beginIdx = ranges[baseRangeIdx].beginIdx;
NvFlowUint64 endIdx = ranges[baseRangeIdx].endIdx;
for (NvFlowUint64 currentIdx = beginIdx; currentIdx < endIdx; currentIdx++)
{
if (location.x == locations[currentIdx].x &&
location.y == locations[currentIdx].y &&
location.z == locations[currentIdx].z &&
location.w == locations[currentIdx].w)
{
masks[currentIdx] |= mask;
return;
}
}
if (beginIdx >= endIdx)
{
locations.pushBack(location);
masks.pushBack(mask);
nextIndices.pushBack(~0llu);
ranges[baseRangeIdx].beginIdx = locations.size - 1u;
ranges[baseRangeIdx].endIdx = locations.size;
}
else if (endIdx == locations.size)
{
locations.pushBack(location);
masks.pushBack(mask);
nextIndices.pushBack(~0llu);
ranges[baseRangeIdx].endIdx = locations.size;
nextIndices[endIdx - 1u] = locations.size - 1u;
}
else
{
NvFlowUint64 prevIdx = endIdx - 1u;
NvFlowUint64 currentIdx = nextIndices[prevIdx];
while (currentIdx < nextIndices.size)
{
if (location.x == locations[currentIdx].x &&
location.y == locations[currentIdx].y &&
location.z == locations[currentIdx].z &&
location.w == locations[currentIdx].w)
{
masks[currentIdx] |= mask;
return;
}
prevIdx = currentIdx;
currentIdx = nextIndices[currentIdx];
}
locations.pushBack(location);
masks.pushBack(mask);
nextIndices.pushBack(~0llu);
nextIndices[prevIdx] = locations.size - 1u;
}
}
void conditionalGrowTable()
{
if (locations.size > tableDim3)
{
tableDimBits++;
tableDimLessOne = (1u << tableDimBits) - 1u;
tableDim3 = (1 << (tableDimBits + tableDimBits + tableDimBits));
rebuildTable();
}
}
void push(NvFlowInt4 location, NvFlowUint mask)
{
pushNoResize(location, mask);
conditionalGrowTable();
}
void computeStats()
{
locationMin = NvFlowInt4{ 0, 0, 0, 0 };
locationMax = NvFlowInt4{ 0, 0, 0, 0 };
if (locations.size > 0)
{
locationMin = locations[0];
locationMax.x = locations[0].x + 1;
locationMax.y = locations[0].y + 1;
locationMax.z = locations[0].z + 1;
locationMax.w = locations[0].w + 1;
}
for (NvFlowUint64 locationIdx = 1u; locationIdx < locations.size; locationIdx++)
{
NvFlowInt4 location = locations[locationIdx];
if (location.x < locationMin.x)
{
locationMin.x = location.x;
}
if (location.y < locationMin.y)
{
locationMin.y = location.y;
}
if (location.z < locationMin.z)
{
locationMin.z = location.z;
}
if (location.w < locationMin.w)
{
locationMin.w = location.w;
}
// plus one, since max is exclusive
if (location.x + 1 > locationMax.x)
{
locationMax.x = location.x + 1;
}
if (location.y + 1 > locationMax.y)
{
locationMax.y = location.y + 1;
}
if (location.z + 1 > locationMax.z)
{
locationMax.z = location.z + 1;
}
if (location.w + 1 > locationMax.w)
{
locationMax.w = location.w + 1;
}
}
}
}; |
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowString.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include <stdarg.h>
#include "NvFlowTypes.h"
/// ************************** String Pool *********************************************
struct NvFlowStringPool;
NvFlowStringPool* NvFlowStringPoolCreate();
char* NvFlowStringPoolAllocate(NvFlowStringPool* pool, NvFlowUint64 size);
void NvFlowStringPoolTempAllocate(NvFlowStringPool* ptr, char** p_str_data, NvFlowUint64* p_str_size);
void NvFlowStringPoolTempAllocateCommit(NvFlowStringPool* ptr, char* str_data, NvFlowUint64 str_size);
void NvFlowStringPoolDestroy(NvFlowStringPool* pool);
void NvFlowStringPoolReset(NvFlowStringPool* pool);
char* NvFlowStringPrint(NvFlowStringPool* pool, const char* format, ...);
char* NvFlowStringPrintV(NvFlowStringPool* pool, const char* format, va_list args);
/// ************************** Macro utils *********************************
#define NV_FLOW_CSTR(X) NvFlowStringView{X, sizeof(X) - 1}
#define NvFlowStringToInteger(input) atoi(input)
#define NvFlowStringMakeView(input) NvFlowStringView{ input, (int)strlen(input) }
/// ************************** Char Utils *********************************************
NV_FLOW_INLINE int NvFlowCharIsWhiteSpace(char c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == '\f' || c == '\v';
}
NV_FLOW_INLINE int NvFlowCharIsWhiteSpaceButNotNewline(char c)
{
return c == ' ' || c == '\r' || c == '\t' || c == '\f' || c == '\v';
}
NV_FLOW_INLINE int NvFlowCharIsAlphaUnderscore(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '_');
}
NV_FLOW_INLINE int NvFlowCharIsAlphaNum(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '_');
}
NV_FLOW_INLINE int NvFlowCharIsNum(char c)
{
return (c >= '0' && c <= '9');
}
/// ************************** String Utils *********************************************
NV_FLOW_INLINE NvFlowUint64 NvFlowStringLength(const char* a)
{
if (!a)
{
return 0;
}
int idx = 0;
while (a[idx])
{
idx++;
}
return idx;
}
NV_FLOW_INLINE int NvFlowStringCompare(const char* a, const char* b)
{
a = a ? a : "\0";
b = b ? b : "\0";
int idx = 0;
while (a[idx] || b[idx])
{
if (a[idx] != b[idx])
{
return a[idx] < b[idx] ? -1 : +1;
}
idx++;
}
return 0;
}
NV_FLOW_INLINE char* NvFlowStringFromView(NvFlowStringPool* pool, const char* data, NvFlowUint64 size)
{
char* str = NvFlowStringPoolAllocate(pool, size);
for (NvFlowUint64 i = 0; i < size; i++)
{
str[i] = data[i];
}
return str;
}
NV_FLOW_INLINE void NvFlowStringSplitDelimFirst(NvFlowStringPool* pool, char** pFirst, char** pSecond, const char* input_data, char delim)
{
NvFlowUint64 input_size = NvFlowStringLength(input_data);
NvFlowUint64 slashIdx = 0;
while (slashIdx < input_size)
{
if (input_data[slashIdx] == delim)
{
break;
}
slashIdx++;
}
*pFirst = NvFlowStringFromView(pool, input_data, slashIdx + 1);
*pSecond = NvFlowStringFromView(pool, input_data + slashIdx + 1, input_size - slashIdx - 1);
}
NV_FLOW_INLINE void NvFlowStringSplitDelimLast(NvFlowStringPool* pool, char** pFirst, char** pSecond, const char* input_data, char delim)
{
NvFlowUint64 input_size = NvFlowStringLength(input_data);
NvFlowUint64 slashIdx = input_size - 1;
while (slashIdx < input_size)
{
if (input_data[slashIdx] == delim)
{
break;
}
slashIdx--;
}
*pFirst = NvFlowStringFromView(pool, input_data, slashIdx + 1);
*pSecond = NvFlowStringFromView(pool, input_data + slashIdx + 1, input_size - slashIdx - 1);
}
NV_FLOW_INLINE char* NvFlowStringDup(NvFlowStringPool* pool, const char* name)
{
NvFlowUint64 name_size = NvFlowStringLength(name);
return NvFlowStringFromView(pool, name, name_size);
}
NV_FLOW_INLINE char* NvFlowStringConcat(NvFlowStringPool* pool, const char* dir_data, const char* filename_data)
{
NvFlowUint64 dir_size = NvFlowStringLength(dir_data);
NvFlowUint64 filename_size = NvFlowStringLength(filename_data);
char* s_data = NvFlowStringPoolAllocate(pool, dir_size + filename_size);
for (NvFlowUint64 i = 0; i < dir_size; i++)
{
s_data[i] = dir_data[i];
}
for (NvFlowUint64 i = 0; i < filename_size; i++)
{
s_data[i + dir_size] = filename_data[i];
}
return s_data;
}
NV_FLOW_INLINE char* NvFlowStringConcatN(NvFlowStringPool* pool, const char** views, NvFlowUint64 numViews)
{
NvFlowUint64 totalSize = 0;
for (NvFlowUint64 viewIdx = 0; viewIdx < numViews; viewIdx++)
{
totalSize += NvFlowStringLength(views[viewIdx]);
}
char* s_data = NvFlowStringPoolAllocate(pool, totalSize);
NvFlowUint64 dstOffset = 0;
for (NvFlowUint64 viewIdx = 0; viewIdx < numViews; viewIdx++)
{
const char* view_data = views[viewIdx];
NvFlowUint64 view_size = NvFlowStringLength(view_data);
for (NvFlowUint64 i = 0; i < view_size; i++)
{
s_data[i + dstOffset] = view_data[i];
}
dstOffset += view_size;
}
return s_data;
}
NV_FLOW_INLINE char* NvFlowStringConcat3(NvFlowStringPool* pool, const char* a, const char* b, const char* c)
{
const char* list[3u] = { a, b, c };
return NvFlowStringConcatN(pool, list, 3u);
}
NV_FLOW_INLINE char* NvFlowStringConcat4(NvFlowStringPool* pool, const char* a, const char* b, const char* c, const char* d)
{
const char* list[4u] = { a, b, c, d };
return NvFlowStringConcatN(pool, list, 4u);
}
NV_FLOW_INLINE char* NvFlowStringTrimEnd(NvFlowStringPool* pool, const char* a_data, char trimChar)
{
NvFlowUint64 a_size = NvFlowStringLength(a_data);
while (a_size > 0 && a_data[a_size - 1] == trimChar)
{
a_size--;
}
return NvFlowStringFromView(pool, a_data, a_size);
}
NV_FLOW_INLINE char* NvFlowStringTrimBeginAndEnd(NvFlowStringPool* pool, const char* a_data, char trimChar)
{
NvFlowUint64 a_size = NvFlowStringLength(a_data);
while (a_size > 0 && a_data[0] == trimChar)
{
a_data++;
a_size--;
}
while (a_size > 0 && a_data[a_size - 1] == trimChar)
{
a_size--;
}
return NvFlowStringFromView(pool, a_data, a_size);
}
/// ************************** File Utils *********************************************
const char* NvFlowTextFileLoad(NvFlowStringPool* pool, const char* filename);
void NvFlowTextFileStore(const char* text, const char* filename);
NvFlowBool32 NvFlowTextFileTestOpen(const char* filename);
void NvFlowTextFileRemove(const char* name);
void NvFlowTextFileRename(const char* oldName, const char* newName);
NvFlowBool32 NvFlowTextFileDiffAndWriteIfModified(const char* filenameDst, const char* filenameTmp);
|
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowMath.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#pragma once
#include "NvFlowTypes.h"
#include <math.h>
namespace NvFlowMath
{
static const float pi = 3.141592654f;
NV_FLOW_INLINE NvFlowFloat4 operator+(const NvFlowFloat4& lhs, const NvFlowFloat4& rhs)
{
NvFlowFloat4 ret;
ret.x = lhs.x + rhs.x;
ret.y = lhs.y + rhs.y;
ret.z = lhs.z + rhs.z;
ret.w = lhs.w + rhs.w;
return ret;
}
NV_FLOW_INLINE NvFlowFloat4 operator-(const NvFlowFloat4& lhs, const NvFlowFloat4& rhs)
{
NvFlowFloat4 ret;
ret.x = lhs.x - rhs.x;
ret.y = lhs.y - rhs.y;
ret.z = lhs.z - rhs.z;
ret.w = lhs.w - rhs.w;
return ret;
}
NV_FLOW_INLINE NvFlowFloat4 operator*(const NvFlowFloat4& lhs, const NvFlowFloat4& rhs)
{
NvFlowFloat4 ret;
ret.x = lhs.x * rhs.x;
ret.y = lhs.y * rhs.y;
ret.z = lhs.z * rhs.z;
ret.w = lhs.w * rhs.w;
return ret;
}
NV_FLOW_INLINE NvFlowFloat4 operator/(const NvFlowFloat4& lhs, const NvFlowFloat4& rhs)
{
NvFlowFloat4 ret;
ret.x = lhs.x / rhs.x;
ret.y = lhs.y / rhs.y;
ret.z = lhs.z / rhs.z;
ret.w = lhs.w / rhs.w;
return ret;
}
NV_FLOW_INLINE NvFlowFloat4 operator*(float v, const NvFlowFloat4& rhs)
{
NvFlowFloat4 ret;
ret.x = v * rhs.x;
ret.y = v * rhs.y;
ret.z = v * rhs.z;
ret.w = v * rhs.w;
return ret;
}
NV_FLOW_INLINE NvFlowFloat4 operator*(const NvFlowFloat4& lhs, float v)
{
NvFlowFloat4 ret;
ret.x = lhs.x * v;
ret.y = lhs.y * v;
ret.z = lhs.z * v;
ret.w = lhs.w * v;
return ret;
}
NV_FLOW_INLINE NvFlowFloat4 vectorSplatX(const NvFlowFloat4& a)
{
return NvFlowFloat4{ a.x, a.x, a.x, a.x };
}
NV_FLOW_INLINE NvFlowFloat4 vectorSplatY(const NvFlowFloat4& a)
{
return NvFlowFloat4{ a.y, a.y, a.y, a.y };
}
NV_FLOW_INLINE NvFlowFloat4 vectorSplatZ(const NvFlowFloat4& a)
{
return NvFlowFloat4{ a.z, a.z, a.z, a.z };
}
NV_FLOW_INLINE NvFlowFloat4 vectorSplatW(const NvFlowFloat4& a)
{
return NvFlowFloat4{ a.w, a.w, a.w, a.w };
}
NV_FLOW_INLINE NvFlowFloat4 vector3Normalize(const NvFlowFloat4& v)
{
float magn = sqrtf(v.x * v.x + v.y * v.y + v.z * v.z);
if (magn > 0.f)
{
magn = 1.f / magn;
}
return NvFlowFloat4{ v.x * magn, v.y * magn, v.z * magn, v.w * magn };
}
NV_FLOW_INLINE NvFlowFloat4 vectorPerspectiveDivide(const NvFlowFloat4& v)
{
return v / vectorSplatW(v);
}
NV_FLOW_INLINE NvFlowFloat4 matrixMultiplyRow(const NvFlowFloat4x4& b, const NvFlowFloat4& r)
{
NvFlowFloat4 result;
result.x = b.x.x * r.x + b.y.x * r.y + b.z.x * r.z + b.w.x * r.w;
result.y = b.x.y * r.x + b.y.y * r.y + b.z.y * r.z + b.w.y * r.w;
result.z = b.x.z * r.x + b.y.z * r.y + b.z.z * r.z + b.w.z * r.w;
result.w = b.x.w * r.x + b.y.w * r.y + b.z.w * r.z + b.w.w * r.w;
return result;
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixMultiply(const NvFlowFloat4x4& a, const NvFlowFloat4x4& b)
{
NvFlowFloat4x4 result;
result.x = matrixMultiplyRow(b, a.x);
result.y = matrixMultiplyRow(b, a.y);
result.z = matrixMultiplyRow(b, a.z);
result.w = matrixMultiplyRow(b, a.w);
return result;
}
NV_FLOW_INLINE NvFlowFloat4 matrixTransposeRow(const NvFlowFloat4x4& a, unsigned int offset)
{
NvFlowFloat4 result;
result.x = *((&a.x.x) + offset);
result.y = *((&a.y.x) + offset);
result.z = *((&a.z.x) + offset);
result.w = *((&a.w.x) + offset);
return result;
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixTranspose(const NvFlowFloat4x4& a)
{
NvFlowFloat4x4 result;
result.x = matrixTransposeRow(a, 0u);
result.y = matrixTransposeRow(a, 1u);
result.z = matrixTransposeRow(a, 2u);
result.w = matrixTransposeRow(a, 3u);
return result;
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixInverse(const NvFlowFloat4x4& a)
{
const NvFlowFloat4x4& m = a;
float f = (float(1.0) /
(m.x.x * m.y.y * m.z.z * m.w.w +
m.x.x * m.y.z * m.z.w * m.w.y +
m.x.x * m.y.w * m.z.y * m.w.z +
m.x.y * m.y.x * m.z.w * m.w.z +
m.x.y * m.y.z * m.z.x * m.w.w +
m.x.y * m.y.w * m.z.z * m.w.x +
m.x.z * m.y.x * m.z.y * m.w.w +
m.x.z * m.y.y * m.z.w * m.w.x +
m.x.z * m.y.w * m.z.x * m.w.y +
m.x.w * m.y.x * m.z.z * m.w.y +
m.x.w * m.y.y * m.z.x * m.w.z +
m.x.w * m.y.z * m.z.y * m.w.x +
-m.x.x * m.y.y * m.z.w * m.w.z +
-m.x.x * m.y.z * m.z.y * m.w.w +
-m.x.x * m.y.w * m.z.z * m.w.y +
-m.x.y * m.y.x * m.z.z * m.w.w +
-m.x.y * m.y.z * m.z.w * m.w.x +
-m.x.y * m.y.w * m.z.x * m.w.z +
-m.x.z * m.y.x * m.z.w * m.w.y +
-m.x.z * m.y.y * m.z.x * m.w.w +
-m.x.z * m.y.w * m.z.y * m.w.x +
-m.x.w * m.y.x * m.z.y * m.w.z +
-m.x.w * m.y.y * m.z.z * m.w.x +
-m.x.w * m.y.z * m.z.x * m.w.y));
float a00 = (m.y.y * m.z.z * m.w.w +
m.y.z * m.z.w * m.w.y +
m.y.w * m.z.y * m.w.z +
-m.y.y * m.z.w * m.w.z +
-m.y.z * m.z.y * m.w.w +
-m.y.w * m.z.z * m.w.y);
float a10 = (m.x.y * m.z.w * m.w.z +
m.x.z * m.z.y * m.w.w +
m.x.w * m.z.z * m.w.y +
-m.x.y * m.z.z * m.w.w +
-m.x.z * m.z.w * m.w.y +
-m.x.w * m.z.y * m.w.z);
float a20 = (m.x.y * m.y.z * m.w.w +
m.x.z * m.y.w * m.w.y +
m.x.w * m.y.y * m.w.z +
-m.x.y * m.y.w * m.w.z +
-m.x.z * m.y.y * m.w.w +
-m.x.w * m.y.z * m.w.y);
float a30 = (m.x.y * m.y.w * m.z.z +
m.x.z * m.y.y * m.z.w +
m.x.w * m.y.z * m.z.y +
-m.x.y * m.y.z * m.z.w +
-m.x.z * m.y.w * m.z.y +
-m.x.w * m.y.y * m.z.z);
float a01 = (m.y.x * m.z.w * m.w.z +
m.y.z * m.z.x * m.w.w +
m.y.w * m.z.z * m.w.x +
-m.y.x * m.z.z * m.w.w +
-m.y.z * m.z.w * m.w.x +
-m.y.w * m.z.x * m.w.z);
float a11 = (m.x.x * m.z.z * m.w.w +
m.x.z * m.z.w * m.w.x +
m.x.w * m.z.x * m.w.z +
-m.x.x * m.z.w * m.w.z +
-m.x.z * m.z.x * m.w.w +
-m.x.w * m.z.z * m.w.x);
float a21 = (m.x.x * m.y.w * m.w.z +
m.x.z * m.y.x * m.w.w +
m.x.w * m.y.z * m.w.x +
-m.x.x * m.y.z * m.w.w +
-m.x.z * m.y.w * m.w.x +
-m.x.w * m.y.x * m.w.z);
float a31 = (m.x.x * m.y.z * m.z.w +
m.x.z * m.y.w * m.z.x +
m.x.w * m.y.x * m.z.z +
-m.x.x * m.y.w * m.z.z +
-m.x.z * m.y.x * m.z.w +
-m.x.w * m.y.z * m.z.x);
float a02 = (m.y.x * m.z.y * m.w.w +
m.y.y * m.z.w * m.w.x +
m.y.w * m.z.x * m.w.y +
-m.y.x * m.z.w * m.w.y +
-m.y.y * m.z.x * m.w.w +
-m.y.w * m.z.y * m.w.x);
float a12 = (-m.x.x * m.z.y * m.w.w +
-m.x.y * m.z.w * m.w.x +
-m.x.w * m.z.x * m.w.y +
m.x.x * m.z.w * m.w.y +
m.x.y * m.z.x * m.w.w +
m.x.w * m.z.y * m.w.x);
float a22 = (m.x.x * m.y.y * m.w.w +
m.x.y * m.y.w * m.w.x +
m.x.w * m.y.x * m.w.y +
-m.x.x * m.y.w * m.w.y +
-m.x.y * m.y.x * m.w.w +
-m.x.w * m.y.y * m.w.x);
float a32 = (m.x.x * m.y.w * m.z.y +
m.x.y * m.y.x * m.z.w +
m.x.w * m.y.y * m.z.x +
-m.x.y * m.y.w * m.z.x +
-m.x.w * m.y.x * m.z.y +
-m.x.x * m.y.y * m.z.w);
float a03 = (m.y.x * m.z.z * m.w.y +
m.y.y * m.z.x * m.w.z +
m.y.z * m.z.y * m.w.x +
-m.y.x * m.z.y * m.w.z +
-m.y.y * m.z.z * m.w.x +
-m.y.z * m.z.x * m.w.y);
float a13 = (m.x.x * m.z.y * m.w.z +
m.x.y * m.z.z * m.w.x +
m.x.z * m.z.x * m.w.y +
-m.x.x * m.z.z * m.w.y +
-m.x.y * m.z.x * m.w.z +
-m.x.z * m.z.y * m.w.x);
float a23 = (m.x.x * m.y.z * m.w.y +
m.x.y * m.y.x * m.w.z +
m.x.z * m.y.y * m.w.x +
-m.x.x * m.y.y * m.w.z +
-m.x.y * m.y.z * m.w.x +
-m.x.z * m.y.x * m.w.y);
float a33 = (m.x.x * m.y.y * m.z.z +
m.x.y * m.y.z * m.z.x +
m.x.z * m.y.x * m.z.y +
-m.x.x * m.y.z * m.z.y +
-m.x.y * m.y.x * m.z.z +
-m.x.z * m.y.y * m.z.x);
return NvFlowFloat4x4{
a00*f, a10*f, a20*f, a30*f,
a01*f, a11*f, a21*f, a31*f,
a02*f, a12*f, a22*f, a32*f,
a03*f, a13*f, a23*f, a33*f };
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixIdentity()
{
return NvFlowFloat4x4{
{ 1.f, 0.f, 0.f, 0.f },
{ 0.f, 1.f, 0.f, 0.f },
{ 0.f, 0.f, 1.f, 0.f },
{ 0.f, 0.f, 0.f, 1.f }
};
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixScaling(float x, float y, float z)
{
return NvFlowFloat4x4{
x, 0.f, 0.f, 0.f,
0.f, y, 0.f, 0.f,
0.f, 0.f, z, 0.f,
0.f, 0.f, 0.f, 1.f
};
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixTranslation(float x, float y, float z)
{
return NvFlowFloat4x4{
1.f, 0.f, 0.f, 0.f,
0.f, 1.f, 0.f, 0.f,
0.f, 0.f, 1.f, 0.f,
x, y, z, 1.f
};
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixPerspectiveFovRH(float fovAngleY, float aspectRatio, float nearZ, float farZ)
{
float sinfov = sinf(0.5f * fovAngleY);
float cosfov = cosf(0.5f * fovAngleY);
float height = cosfov / sinfov;
float width = height / aspectRatio;
float frange = farZ / (nearZ - farZ);
if (nearZ == INFINITY)
{
return NvFlowFloat4x4{
{ width, 0.f, 0.f, 0.f },
{ 0.f, height, 0.f, 0.f },
{ 0.f, 0.f, frange, -1.f },
{ 0.f, 0.f, farZ, 0.f }
};
}
return NvFlowFloat4x4{
{ width, 0.f, 0.f, 0.f },
{ 0.f, height, 0.f, 0.f },
{ 0.f, 0.f, frange, -1.f },
{ 0.f, 0.f, frange * nearZ, 0.f }
};
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixPerspectiveFovLH(float fovAngleY, float aspectRatio, float nearZ, float farZ)
{
float sinfov = sinf(0.5f * fovAngleY);
float cosfov = cosf(0.5f * fovAngleY);
float height = cosfov / sinfov;
float width = height / aspectRatio;
float frange = farZ / (farZ - nearZ);
if (nearZ == INFINITY)
{
return NvFlowFloat4x4{
{ width, 0.f, 0.f, 0.f },
{ 0.f, height, 0.f, 0.f },
{ 0.f, 0.f, frange, 1.f },
{ 0.f, 0.f, farZ, 0.f }
};
}
return NvFlowFloat4x4{
{ width, 0.f, 0.f, 0.f },
{ 0.f, height, 0.f, 0.f },
{ 0.f, 0.f, frange, 1.f },
{ 0.f, 0.f, -frange * nearZ, 0.f }
};
}
NV_FLOW_INLINE NvFlowBool32 matrixPerspectiveIsRH(const NvFlowFloat4x4& m)
{
return m.z.w < 0.f ? NV_FLOW_TRUE : NV_FLOW_FALSE;
}
NV_FLOW_INLINE NvFlowBool32 matrixPerspectiveIsReverseZ(const NvFlowFloat4x4& m)
{
float nearZ = -m.w.z / m.z.z;
float farZ = (m.w.w - m.w.z) / (m.z.z - m.z.w);
float singZ = -m.w.w / m.z.w;
return fabsf(farZ - singZ) < fabs(nearZ - singZ) ? NV_FLOW_TRUE : NV_FLOW_FALSE;
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixOrthographicLH(float width, float height, float nearZ, float farZ)
{
float frange = 1.f / (farZ - nearZ);
return NvFlowFloat4x4{
{ 2.f / width, 0.f, 0.f, 0.f },
{ 0.f, 2.f / height, 0.f, 0.f },
{ 0.f, 0.f, frange, 0.f },
{ 0.f, 0.f, -frange * nearZ, 1.f }
};
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixOrthographicRH(float width, float height, float nearZ, float farZ)
{
float frange = 1.f / (nearZ - farZ);
return NvFlowFloat4x4{
{ 2.f / width, 0.f, 0.f, 0.f },
{ 0.f, 2.f / height, 0.f, 0.f },
{ 0.f, 0.f, frange, 0.f },
{ 0.f, 0.f, frange * nearZ, 1.f }
};
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixRotationNormal(NvFlowFloat4 normal, float angle)
{
float sinAngle = sinf(angle);
float cosAngle = cosf(angle);
NvFlowFloat4 a = { sinAngle, cosAngle, 1.f - cosAngle, 0.f };
NvFlowFloat4 c2 = vectorSplatZ(a);
NvFlowFloat4 c1 = vectorSplatY(a);
NvFlowFloat4 c0 = vectorSplatX(a);
NvFlowFloat4 n0 = { normal.y, normal.z, normal.x, normal.w };
NvFlowFloat4 n1 = { normal.z, normal.x, normal.y, normal.w };
NvFlowFloat4 v0 = c2 * n0;
v0 = v0 * n1;
NvFlowFloat4 r0 = c2 * normal;
r0 = (r0 * normal) + c1;
NvFlowFloat4 r1 = (c0 * normal) + v0;
NvFlowFloat4 r2 = v0 - (c0 * normal);
v0 = NvFlowFloat4{ r0.x, r0.y, r0.z, a.w };
NvFlowFloat4 v1 = { r1.z, r2.y, r2.z, r1.x };
NvFlowFloat4 v2 = { r1.y, r2.x, r1.y, r2.x };
return NvFlowFloat4x4{
{ v0.x, v1.x, v1.y, v0.w },
{ v1.z, v0.y, v1.w, v0.w },
{ v2.x, v2.y, v0.z, v0.w },
{ 0.f, 0.f, 0.f, 1.f }
};
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixRotationAxis(NvFlowFloat4 axis, float angle)
{
NvFlowFloat4 normal = vector3Normalize(axis);
return matrixRotationNormal(normal, angle);
}
NV_FLOW_INLINE NvFlowFloat4 quaterionRotationRollPitchYawFromVector(NvFlowFloat4 angles)
{
NvFlowFloat4 sign = { 1.f, -1.f, -1.f, 1.f };
NvFlowFloat4 halfAngles = angles * NvFlowFloat4{ 0.5f, 0.5f, 0.5f, 0.5f };
NvFlowFloat4 sinAngle = NvFlowFloat4{ sinf(halfAngles.x), sinf(halfAngles.y), sinf(halfAngles.z), sinf(halfAngles.w) };
NvFlowFloat4 cosAngle = NvFlowFloat4{ cosf(halfAngles.x), cosf(halfAngles.y), cosf(halfAngles.z), cosf(halfAngles.w) };
NvFlowFloat4 p0 = { sinAngle.x, cosAngle.x, cosAngle.x, cosAngle.x };
NvFlowFloat4 y0 = { cosAngle.y, sinAngle.y, cosAngle.y, cosAngle.y };
NvFlowFloat4 r0 = { cosAngle.z, cosAngle.z, sinAngle.z, cosAngle.z };
NvFlowFloat4 p1 = { cosAngle.x, sinAngle.x, sinAngle.x, sinAngle.x };
NvFlowFloat4 y1 = { sinAngle.y, cosAngle.y, sinAngle.y, sinAngle.y };
NvFlowFloat4 r1 = { sinAngle.z, sinAngle.z, cosAngle.z, sinAngle.z };
NvFlowFloat4 q1 = p1 * sign;
NvFlowFloat4 q0 = p0 * y0;
q1 = q1 * y1;
q0 = q0 * r0;
NvFlowFloat4 q = (q1 * r1) + q0;
return q;
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixRotationQuaternion(NvFlowFloat4 quaternion)
{
NvFlowFloat4 constant1110 = { 1.f, 1.f, 1.f, 0.f };
NvFlowFloat4 q0 = quaternion + quaternion;
NvFlowFloat4 q1 = quaternion * q0;
NvFlowFloat4 v0 = { q1.y, q1.x, q1.x, constant1110.w };
NvFlowFloat4 v1 = { q1.z, q1.z, q1.y, constant1110.w };
NvFlowFloat4 r0 = constant1110 - v0;
r0 = r0 - v1;
v0 = NvFlowFloat4{ quaternion.x, quaternion.x, quaternion.y, quaternion.w };
v1 = NvFlowFloat4{ q0.z, q0.y, q0.z, q0.w };
v0 = v0 * v1;
v1 = vectorSplatW(quaternion);
NvFlowFloat4 v2 = { q0.y, q0.z, q0.x, q0.w };
v1 = v1 * v2;
NvFlowFloat4 r1 = v0 + v1;
NvFlowFloat4 r2 = v0 - v1;
v0 = NvFlowFloat4{ r1.y, r2.x, r2.y, r1.z };
v1 = NvFlowFloat4{ r1.x, r2.z, r1.x, r2.z };
return NvFlowFloat4x4{
{ r0.x, v0.x, v0.y, r0.w },
{ v0.z, r0.y, v0.w, r0.w },
{ v1.x, v1.y, r0.z, r0.w },
{ 0.f, 0.f, 0.f, 1.f }
};
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixRotationRollPitchYaw(float pitch, float yaw, float roll)
{
NvFlowFloat4 angles = { pitch, yaw, roll, 0.f };
NvFlowFloat4 q = quaterionRotationRollPitchYawFromVector(angles);
return matrixRotationQuaternion(q);
}
NV_FLOW_INLINE NvFlowFloat4 vectorLerp(NvFlowFloat4 a, NvFlowFloat4 b, float t)
{
return NvFlowFloat4{
(1.f - t) * a.x + t * b.x,
(1.f - t) * a.y + t * b.y,
(1.f - t) * a.z + t * b.z,
(1.f - t) * a.w + t * b.w
};
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixInterpolateTranslation(const NvFlowFloat4x4& a, const NvFlowFloat4x4& b, float t)
{
NvFlowFloat4x4 ret;
if (t < 0.5f)
{
ret = a;
}
else
{
ret = b;
}
ret.w.x = (1.f - t) * a.w.x + t * b.w.x;
ret.w.y = (1.f - t) * a.w.y + t * b.w.y;
ret.w.z = (1.f - t) * a.w.z + t * b.w.z;
return ret;
}
NV_FLOW_INLINE NvFlowFloat4 vector4Normalize(const NvFlowFloat4& v)
{
float magn = sqrtf(v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w);
if (magn > 0.f)
{
magn = 1.f / magn;
}
return NvFlowFloat4{v.x * magn, v.y * magn, v.z * magn, v.w * magn};
}
NV_FLOW_INLINE NvFlowFloat4x4 matrixNormalize(const NvFlowFloat4x4& a)
{
NvFlowFloat4x4 temp = a;
temp.x.w = 0.f;
temp.y.w = 0.f;
temp.z.w = 0.f;
temp.w.w = 1.f;
temp.w.x = 0.f;
temp.w.y = 0.f;
temp.w.z = 0.f;
NvFlowFloat4x4 ret = temp;
ret.x = vector4Normalize(ret.x);
ret.y = vector4Normalize(ret.y);
ret.z = vector4Normalize(ret.z);
return ret;
}
NV_FLOW_INLINE NvFlowFloat4 vector4Transform(const NvFlowFloat4& x, const NvFlowFloat4x4& A)
{
return NvFlowFloat4{
A.x.x * x.x + A.y.x * x.y + A.z.x * x.z + A.w.x * x.w,
A.x.y * x.x + A.y.y * x.y + A.z.y * x.z + A.w.y * x.w,
A.x.z * x.x + A.y.z * x.y + A.z.z * x.z + A.w.z * x.w,
A.x.w * x.x + A.y.w * x.y + A.z.w * x.z + A.w.w * x.w
};
}
NV_FLOW_INLINE NvFlowFloat4 vectorMin(const NvFlowFloat4& a, const NvFlowFloat4& b)
{
return NvFlowFloat4{
a.x < b.x ? a.x : b.x,
a.y < b.y ? a.y : b.y,
a.z < b.z ? a.z : b.z,
a.w < b.w ? a.w : b.w
};
}
NV_FLOW_INLINE NvFlowFloat4 vectorMax(const NvFlowFloat4& a, const NvFlowFloat4& b)
{
return NvFlowFloat4{
a.x > b.x ? a.x : b.x,
a.y > b.y ? a.y : b.y,
a.z > b.z ? a.z : b.z,
a.w > b.w ? a.w : b.w
};
}
NV_FLOW_INLINE NvFlowFloat4 vectorMultiply(const NvFlowFloat4& a, const NvFlowFloat4& b)
{
return NvFlowFloat4{a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w};
}
NV_FLOW_INLINE NvFlowFloat4 vectorFloor(const NvFlowFloat4& a)
{
return NvFlowFloat4{ floorf(a.x), floorf(a.y), floorf(a.z), floorf(a.w) };
}
NV_FLOW_INLINE NvFlowFloat4 vectorCeiling(const NvFlowFloat4& a)
{
return NvFlowFloat4{ceilf(a.x), ceilf(a.y), ceilf(a.z), ceilf(a.w)};
}
NV_FLOW_INLINE NvFlowFloat4 vector3Dot(const NvFlowFloat4& a, const NvFlowFloat4& b)
{
float magn = a.x * b.x + a.y * b.y + a.z * b.z;
return NvFlowFloat4{ magn, magn, magn, magn };
}
NV_FLOW_INLINE NvFlowFloat4 vector4Dot(const NvFlowFloat4& a, const NvFlowFloat4& b)
{
float magn = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
return NvFlowFloat4{ magn, magn, magn, magn };
}
NV_FLOW_INLINE NvFlowFloat4 vector3Cross(const NvFlowFloat4& a, const NvFlowFloat4& b)
{
return NvFlowFloat4{
a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x,
0.f
};
}
NV_FLOW_INLINE NvFlowFloat4 vector3Length(const NvFlowFloat4& a)
{
float magn = sqrtf(a.x * a.x + a.y * a.y + a.z * a.z);
return NvFlowFloat4{ magn, magn, magn, magn };
}
NV_FLOW_INLINE NvFlowFloat4 make_float4(NvFlowFloat3 a, float b)
{
return NvFlowFloat4{ a.x, a.y, a.z, b };
}
NV_FLOW_INLINE NvFlowFloat3 float4_to_float3(NvFlowFloat4 a)
{
return NvFlowFloat3{ a.x, a.y, a.z };
}
NV_FLOW_INLINE NvFlowUint log2ui(NvFlowUint val)
{
NvFlowUint ret = 0;
for (NvFlowUint i = 0; i < 32; i++)
{
if ((1u << i) >= val)
{
ret = i;
break;
}
}
return ret;
}
NV_FLOW_INLINE NvFlowFloat4 computeRayOrigin(const NvFlowFloat4x4& viewInv, const NvFlowFloat4x4& projectionInv, NvFlowFloat2 ndc, float nearZ)
{
NvFlowFloat4 viewPos = vector4Transform(NvFlowFloat4{ ndc.x, ndc.y, nearZ, 1.f }, projectionInv);
return vectorPerspectiveDivide(vector4Transform(viewPos, viewInv));
}
NV_FLOW_INLINE NvFlowFloat4 computeRayDir(const NvFlowFloat4x4& viewInv, const NvFlowFloat4x4& projectionInv, NvFlowFloat2 ndc, float nearZ)
{
NvFlowFloat4x4 projectionInvT = matrixTranspose(projectionInv);
NvFlowFloat4 ndc_ext = NvFlowFloat4{ ndc.x, ndc.y, 0.f, 1.f };
NvFlowFloat4 dir = {
-projectionInvT.w.z * vector4Dot(projectionInvT.x, ndc_ext).x,
-projectionInvT.w.z * vector4Dot(projectionInvT.y, ndc_ext).x,
-projectionInvT.w.z * vector4Dot(projectionInvT.z, ndc_ext).x +
projectionInvT.z.z * vector4Dot(projectionInvT.w, ndc_ext).x,
0.f
};
if (nearZ > 0.5f)
{
dir = NvFlowFloat4{ 0.f, 0.f, 0.f, 0.f } - dir;
}
return vector4Transform(dir, viewInv);
}
struct FrustumRays
{
NvFlowFloat4 rayOrigin00;
NvFlowFloat4 rayOrigin10;
NvFlowFloat4 rayOrigin01;
NvFlowFloat4 rayOrigin11;
NvFlowFloat4 rayDir00;
NvFlowFloat4 rayDir10;
NvFlowFloat4 rayDir01;
NvFlowFloat4 rayDir11;
float nearZ;
NvFlowBool32 isReverseZ;
};
NV_FLOW_INLINE void computeFrustumRays(FrustumRays* ptr, const NvFlowFloat4x4& viewInv, const NvFlowFloat4x4& projectionInv)
{
NvFlowFloat4 nearPoint = vector4Transform(NvFlowFloat4{ 0.f, 0.f, 0.f, 1.f }, projectionInv);
NvFlowFloat4 farPoint = vector4Transform(NvFlowFloat4{ 0.f, 0.f, 1.f, 1.f }, projectionInv);
nearPoint = nearPoint / vectorSplatW(nearPoint);
farPoint = farPoint / vectorSplatW(farPoint);
float nearZ = fabsf(nearPoint.z) < fabsf(farPoint.z) ? 0.f : 1.f;
ptr->rayOrigin00 = computeRayOrigin(viewInv, projectionInv, NvFlowFloat2{ -1.f, +1.f }, nearZ);
ptr->rayOrigin10 = computeRayOrigin(viewInv, projectionInv, NvFlowFloat2{ +1.f, +1.f }, nearZ);
ptr->rayOrigin01 = computeRayOrigin(viewInv, projectionInv, NvFlowFloat2{ -1.f, -1.f }, nearZ);
ptr->rayOrigin11 = computeRayOrigin(viewInv, projectionInv, NvFlowFloat2{ +1.f, -1.f }, nearZ);
ptr->rayDir00 = computeRayDir(viewInv, projectionInv, NvFlowFloat2{ -1.f, +1.f }, nearZ);
ptr->rayDir10 = computeRayDir(viewInv, projectionInv, NvFlowFloat2{ +1.f, +1.f }, nearZ);
ptr->rayDir01 = computeRayDir(viewInv, projectionInv, NvFlowFloat2{ -1.f, -1.f }, nearZ);
ptr->rayDir11 = computeRayDir(viewInv, projectionInv, NvFlowFloat2{ +1.f, -1.f }, nearZ);
ptr->nearZ = nearZ;
ptr->isReverseZ = fabsf(nearPoint.z) >= fabsf(farPoint.z);
}
} |
NVIDIA-Omniverse/PhysX/flow/shared/NvFlowPreprocessor.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2014-2022 NVIDIA Corporation. All rights reserved.
#include "NvFlowPreprocessor.h"
#include "NvFlowArray.h"
#include <stdlib.h>
#include <stdio.h>
struct NvFlowPreprocessorItem
{
NvFlowPreprocessorFunction function;
NvFlowPreprocessorToken* tokens_data;
NvFlowUint64 tokens_size;
NvFlowBool32 isEnabled;
};
struct NvFlowPreprocessor
{
NvFlowStringPool* stringPool = nullptr;
int currentLevel = 0;
NvFlowPreprocessorMode mode = eNvFlowPreprocessorMode_default;
NvFlowArray<NvFlowPreprocessorItem, 16u> items;
NvFlowArray<const char*> stringStack;
NvFlowArray<const char*, 8u> tempStrViews;
NvFlowArray<NvFlowPreprocessorToken> tempTokens;
};
NvFlowPreprocessor* NvFlowPreprocessorCreate(NvFlowStringPool* pool)
{
auto ptr = new NvFlowPreprocessor();
ptr->stringPool = pool;
ptr->currentLevel = 0;
return ptr;
}
void NvFlowPreprocessorDestroy(NvFlowPreprocessor* ptr)
{
delete ptr;
}
void NvFlowPreprocessorReset(NvFlowPreprocessor* ptr)
{
ptr->currentLevel = 0;
ptr->mode = eNvFlowPreprocessorMode_default;
ptr->items.size = 0u;
ptr->stringStack.size = 0u;
ptr->tempStrViews.size = 0u;
ptr->tempTokens.size = 0u;
}
void NvFlowPreprocessorSetMode(NvFlowPreprocessor* ptr, NvFlowPreprocessorMode mode)
{
ptr->mode = mode;
}
NvFlowPreprocessorMode NvFlowPreprocessorGetMode(NvFlowPreprocessor* ptr)
{
return ptr->mode;
}
NvFlowStringPool* NvFlowPreprocessorStringPool(NvFlowPreprocessor* ptr)
{
return ptr->stringPool;
}
void NvFlowPreprocessor_addItem(NvFlowPreprocessor* ptr, const NvFlowPreprocessorFunction* pFunction)
{
NvFlowPreprocessorItem item = {};
item.function = *pFunction;
item.isEnabled = NV_FLOW_TRUE;
const char* tokenStr = item.function.name;
if (item.function.type == eNvFlowPreprocessorType_function)
{
tokenStr = NvFlowStringConcat(ptr->stringPool, tokenStr, "(");
}
else if (item.function.type == eNvFlowPreprocessorType_index)
{
tokenStr = NvFlowStringConcat(ptr->stringPool, tokenStr, "[");
}
else if (item.function.type == eNvFlowPreprocessorType_attribute)
{
tokenStr = NvFlowStringConcat(ptr->stringPool, "[", tokenStr);
}
else if (item.function.type == eNvFlowPreprocessorType_line)
{
tokenStr = NvFlowStringConcat(ptr->stringPool, "#", tokenStr);
}
else if (item.function.type == eNvFlowPreprocessorType_templateInstance)
{
tokenStr = NvFlowStringConcat(ptr->stringPool, tokenStr, "<");
}
else
{
tokenStr = NvFlowStringDup(ptr->stringPool, tokenStr);
}
NvFlowPreprocessorTokenize(ptr, tokenStr, &item.tokens_size, &item.tokens_data);
ptr->items.pushBack(item);
}
char* NvFlowPreprocessor_substituteConstant(NvFlowPreprocessor* ptr, void* userdata, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens)
{
const char* value = (const char*)userdata;
return NvFlowStringDup(ptr->stringPool, value);
}
void NvFlowPreprocessorAddConstants(NvFlowPreprocessor* ptr, NvFlowUint64 numConstants, const NvFlowPreprocessorConstant* constants)
{
for (NvFlowUint64 idx = 0u; idx < numConstants; idx++)
{
char* valueStr = NvFlowStringDup(ptr->stringPool, constants[idx].value);
NvFlowPreprocessorFunction function = {};
function.name = constants[idx].name;
function.type = eNvFlowPreprocessorType_constant;
function.userdata = valueStr;
function.substitute = NvFlowPreprocessor_substituteConstant;
NvFlowPreprocessor_addItem(ptr, &function);
}
}
void NvFlowPreprocessorAddFunctions(NvFlowPreprocessor* ptr, NvFlowUint64 numFunctions, const NvFlowPreprocessorFunction* functions)
{
for (NvFlowUint64 idx = 0u; idx < numFunctions; idx++)
{
NvFlowPreprocessor_addItem(ptr, &functions[idx]);
}
}
char NvFlowPreprocessor_peekChar(const char* input, NvFlowUint64 inputIdx, NvFlowUint64 input_size)
{
char ret = '\0';
if (inputIdx < input_size)
{
ret = input[inputIdx];
}
return ret;
}
NvFlowBool32 NvFlowPreprocessor_whitespaceButNotNewline(const char** pOutput, NvFlowUint64* pOutput_size, const char* input, NvFlowUint64 input_size, NvFlowUint64 inputIdx)
{
char c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
if (NvFlowCharIsWhiteSpaceButNotNewline(c0))
{
NvFlowUint64 beginIdx = inputIdx;
inputIdx++;
for (; inputIdx < input_size; inputIdx++)
{
c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
if (!NvFlowCharIsWhiteSpaceButNotNewline(c0))
{
break;
}
}
*pOutput_size = inputIdx - beginIdx;
*pOutput = input + beginIdx;
return NV_FLOW_TRUE;
}
return NV_FLOW_FALSE;
}
NvFlowBool32 NvFlowPreprocessor_continuation(const char** pOutput, NvFlowUint64* pOutput_size, const char* input, NvFlowUint64 input_size, NvFlowUint64 inputIdx)
{
char c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
char c1 = NvFlowPreprocessor_peekChar(input, inputIdx + 1, input_size);
if (c0 == '\\' && c1 == '\n')
{
*pOutput_size = 2;
*pOutput = input + inputIdx;
return NV_FLOW_TRUE;
}
return NV_FLOW_FALSE;
}
NvFlowBool32 NvFlowPreprocessor_whitespace(const char** pOutput, NvFlowUint64* pOutput_size, const char* input, NvFlowUint64 input_size, NvFlowUint64 inputIdx)
{
if (NvFlowPreprocessor_whitespaceButNotNewline(pOutput, pOutput_size, input, input_size, inputIdx))
{
return NV_FLOW_TRUE;
}
return NvFlowPreprocessor_continuation(pOutput, pOutput_size, input, input_size, inputIdx);
}
NvFlowBool32 NvFlowPreprocessor_newline(const char** pOutput, NvFlowUint64* pOutput_size, const char* input, NvFlowUint64 input_size, NvFlowUint64 inputIdx)
{
char c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
if (c0 == '\n')
{
*pOutput_size = 1;
*pOutput = input + inputIdx;
return NV_FLOW_TRUE;
}
return NV_FLOW_FALSE;
}
NvFlowBool32 NvFlowPreprocessor_commentLine(const char** pOutput, NvFlowUint64* pOutput_size, const char* input, NvFlowUint64 input_size, NvFlowUint64 inputIdx)
{
char c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
char c1 = NvFlowPreprocessor_peekChar(input, inputIdx + 1, input_size);
if (c0 == '/' && c1 == '/')
{
NvFlowUint64 beginIdx = inputIdx;
inputIdx++;
for (; inputIdx < input_size; inputIdx++)
{
c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
c1 = NvFlowPreprocessor_peekChar(input, inputIdx + 1, input_size);
if (c0 == '\n')
{
break;
}
}
*pOutput_size = inputIdx - beginIdx;
*pOutput = input + beginIdx;
return NV_FLOW_TRUE;
}
return NV_FLOW_FALSE;
}
NvFlowBool32 NvFlowPreprocessor_commentMultiLine(const char** pOutput, NvFlowUint64* pOutput_size, const char* input, NvFlowUint64 input_size, NvFlowUint64 inputIdx)
{
char c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
char c1 = NvFlowPreprocessor_peekChar(input, inputIdx + 1, input_size);
if (c0 == '/' && c1 == '*')
{
NvFlowUint64 beginIdx = inputIdx;
inputIdx++;
for (; inputIdx < input_size; inputIdx++)
{
c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
c1 = NvFlowPreprocessor_peekChar(input, inputIdx + 1, input_size);
if (c0 == '*' && c1 == '/')
{
inputIdx += 2;
break;
}
}
*pOutput_size = inputIdx - beginIdx;
*pOutput = input + beginIdx;
return NV_FLOW_TRUE;
}
return NV_FLOW_FALSE;
}
NvFlowBool32 NvFlowPreprocessor_comment(const char** pOutput, NvFlowUint64* pOutput_size, const char* input, NvFlowUint64 input_size, NvFlowUint64 inputIdx)
{
if (NvFlowPreprocessor_commentLine(pOutput, pOutput_size, input, input_size, inputIdx))
{
return NV_FLOW_TRUE;
}
return NvFlowPreprocessor_commentMultiLine(pOutput, pOutput_size, input, input_size, inputIdx);
}
NvFlowBool32 NvFlowPreprocessor_name(const char** pOutput, NvFlowUint64* pOutput_size, const char* input, NvFlowUint64 input_size, NvFlowUint64 inputIdx)
{
char c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
if (NvFlowCharIsAlphaUnderscore(c0))
{
NvFlowUint64 beginIdx = inputIdx;
inputIdx++;
for (; inputIdx < input_size; inputIdx++)
{
c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
if (!NvFlowCharIsAlphaNum(c0))
{
break;
}
}
*pOutput_size = inputIdx - beginIdx;
*pOutput = input + beginIdx;
return NV_FLOW_TRUE;
}
return NV_FLOW_FALSE;
}
NvFlowBool32 NvFlowPreprocessor_number(const char** pOutput, NvFlowUint64* pOutput_size, const char* input, NvFlowUint64 input_size, NvFlowUint64 inputIdx)
{
char c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
if (NvFlowCharIsNum(c0))
{
NvFlowUint64 beginIdx = inputIdx;
inputIdx++;
for (; inputIdx < input_size; inputIdx++)
{
c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
if (!(NvFlowCharIsAlphaNum(c0) || (c0 == '.')))
{
break;
}
}
*pOutput_size = inputIdx - beginIdx;
*pOutput = input + beginIdx;
return NV_FLOW_TRUE;
}
return NV_FLOW_FALSE;
}
NvFlowBool32 NvFlowPreprocessor_string(const char** pOutput, NvFlowUint64* pOutput_size, const char* input, NvFlowUint64 input_size, NvFlowUint64 inputIdx)
{
char c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
char c1 = NvFlowPreprocessor_peekChar(input, inputIdx + 1, input_size);
if (c0 == '\"')
{
NvFlowUint64 beginIdx = inputIdx;
inputIdx++;
for (; inputIdx < input_size; inputIdx++)
{
c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
c1 = NvFlowPreprocessor_peekChar(input, inputIdx + 1, input_size);
if (c0 == '\"')
{
inputIdx++;
break;
}
else if (c0 == '\\' && c1 == '\"')
{
inputIdx++;
}
}
*pOutput_size = inputIdx - beginIdx;
*pOutput = input + beginIdx;
return NV_FLOW_TRUE;
}
return NV_FLOW_FALSE;
}
NvFlowBool32 NvFlowPreprocessor_char(const char** pOutput, NvFlowUint64* pOutput_size, const char* input, NvFlowUint64 input_size, NvFlowUint64 inputIdx)
{
char c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
char c1 = NvFlowPreprocessor_peekChar(input, inputIdx + 1, input_size);
if (c0 == '\'')
{
NvFlowUint64 beginIdx = inputIdx;
inputIdx++;
for (; inputIdx < input_size; inputIdx++)
{
c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
c1 = NvFlowPreprocessor_peekChar(input, inputIdx + 1, input_size);
if (c0 == '\'')
{
inputIdx++;
break;
}
else if (c0 == '\\' && c1 == '\'')
{
inputIdx++;
}
}
*pOutput_size = inputIdx - beginIdx;
*pOutput = input + beginIdx;
return NV_FLOW_TRUE;
}
return NV_FLOW_FALSE;
}
NvFlowBool32 NvFlowPreprocessor_specialChar(const char** pOutput, NvFlowUint64* pOutput_size, const char* input, NvFlowUint64 input_size, NvFlowUint64 inputIdx, char specialChar)
{
char c0 = NvFlowPreprocessor_peekChar(input, inputIdx + 0, input_size);
if (c0 == specialChar)
{
*pOutput_size = 1;
*pOutput = input + inputIdx;
return NV_FLOW_TRUE;
}
return NV_FLOW_FALSE;
}
void NvFlowPreprocessorTokenize(NvFlowPreprocessor* ptr, const char* input, NvFlowUint64* pTotalTokens, NvFlowPreprocessorToken** pTokens)
{
NvFlowStringPool* pool = ptr->stringPool;
ptr->tempTokens.size = 0u;
NvFlowUint64 input_size = NvFlowStringLength(input);
NvFlowUint64 inputIdx = 0u;
while (inputIdx < input_size)
{
char c0 = input[inputIdx];
char c1 = '\0';
if (inputIdx + 1 < input_size)
{
c1 = input[inputIdx + 1u];
}
// default to single char token
NvFlowPreprocessorToken token = { eNvFlowPreprocessorTokenType_unknown, "InvalidToken" };
NvFlowUint64 output_size = 1;
const char* output = input + inputIdx;
if (NvFlowPreprocessor_whitespace(&output, &output_size, input, input_size, inputIdx))
{
token.type = eNvFlowPreprocessorTokenType_whitespace;
}
else if (NvFlowPreprocessor_newline(&output, &output_size, input, input_size, inputIdx))
{
token.type = eNvFlowPreprocessorTokenType_newline;
}
else if (NvFlowPreprocessor_comment(&output, &output_size, input, input_size, inputIdx))
{
token.type = eNvFlowPreprocessorTokenType_comment;
}
else if (NvFlowPreprocessor_name(&output, &output_size, input, input_size, inputIdx))
{
token.type = eNvFlowPreprocessorTokenType_name;
}
else if (NvFlowPreprocessor_number(&output, &output_size, input, input_size, inputIdx))
{
token.type = eNvFlowPreprocessorTokenType_number;
}
else if (NvFlowPreprocessor_string(&output, &output_size, input, input_size, inputIdx))
{
token.type = eNvFlowPreprocessorTokenType_string;
}
else if (NvFlowPreprocessor_char(&output, &output_size, input, input_size, inputIdx))
{
token.type = eNvFlowPreprocessorTokenType_char;
}
else if (NvFlowPreprocessor_specialChar(&output, &output_size, input, input_size, inputIdx, '#'))
{
token.type = eNvFlowPreprocessorTokenType_pound;
}
else if (NvFlowPreprocessor_specialChar(&output, &output_size, input, input_size, inputIdx, ','))
{
token.type = eNvFlowPreprocessorTokenType_comma;
}
else if (NvFlowPreprocessor_specialChar(&output, &output_size, input, input_size, inputIdx, '.'))
{
token.type = eNvFlowPreprocessorTokenType_period;
}
else if (NvFlowPreprocessor_specialChar(&output, &output_size, input, input_size, inputIdx, ';'))
{
token.type = eNvFlowPreprocessorTokenType_semicolon;
}
else if (NvFlowPreprocessor_specialChar(&output, &output_size, input, input_size, inputIdx, ':'))
{
token.type = eNvFlowPreprocessorTokenType_colon;
}
else if (NvFlowPreprocessor_specialChar(&output, &output_size, input, input_size, inputIdx, '='))
{
token.type = eNvFlowPreprocessorTokenType_equals;
}
else if (NvFlowPreprocessor_specialChar(&output, &output_size, input, input_size, inputIdx, '*'))
{
token.type = eNvFlowPreprocessorTokenType_asterisk;
}
else if (NvFlowPreprocessor_specialChar(&output, &output_size, input, input_size, inputIdx, '('))
{
token.type = eNvFlowPreprocessorTokenType_leftParenthesis;
}
else if (NvFlowPreprocessor_specialChar(&output, &output_size, input, input_size, inputIdx, ')'))
{
token.type = eNvFlowPreprocessorTokenType_rightParenthesis;
}
else if (NvFlowPreprocessor_specialChar(&output, &output_size, input, input_size, inputIdx, '['))
{
token.type = eNvFlowPreprocessorTokenType_leftBracket;
}
else if (NvFlowPreprocessor_specialChar(&output, &output_size, input, input_size, inputIdx, ']'))
{
token.type = eNvFlowPreprocessorTokenType_rightBracket;
}
else if (NvFlowPreprocessor_specialChar(&output, &output_size, input, input_size, inputIdx, '{'))
{
token.type = eNvFlowPreprocessorTokenType_leftCurlyBrace;
}
else if (NvFlowPreprocessor_specialChar(&output, &output_size, input, input_size, inputIdx, '}'))
{
token.type = eNvFlowPreprocessorTokenType_rightCurlyBrace;
}
else if (NvFlowPreprocessor_specialChar(&output, &output_size, input, input_size, inputIdx, '<'))
{
token.type = eNvFlowPreprocessorTokenType_lessThan;
}
else if (NvFlowPreprocessor_specialChar(&output, &output_size, input, input_size, inputIdx, '>'))
{
token.type = eNvFlowPreprocessorTokenType_greaterThan;
}
// duplicate output to null terminated string
token.str = NvFlowStringFromView(pool, output, output_size);
ptr->tempTokens.pushBack(token);
// advance past token
inputIdx += output_size;
}
auto tokenData = (NvFlowPreprocessorToken*)NvFlowStringPoolAllocate(pool, ptr->tempTokens.size * sizeof(NvFlowPreprocessorToken));
for (NvFlowUint64 idx = 0u; idx < ptr->tempTokens.size; idx++)
{
tokenData[idx] = ptr->tempTokens[idx];
}
*pTokens = tokenData;
*pTotalTokens = ptr->tempTokens.size;
ptr->tempTokens.size = 0u;
}
NvFlowBool32 NvFlowPreprocessorFindKeyInSource(NvFlowPreprocessor* ptr, const NvFlowPreprocessorToken* keyTokens, NvFlowUint64 keyTokenCount, const NvFlowPreprocessorToken* sourceTokens, NvFlowUint64 sourceTokenCount, NvFlowUint64* pSourceIndex)
{
NvFlowUint64 keyTokenIdx = 0u;
NvFlowUint64 sourceTokenIdx = 0u;
NvFlowUint64 matches = 0u;
NvFlowUint64 keyTestCount = 0u;
while (keyTokenIdx < keyTokenCount && sourceTokenIdx < sourceTokenCount)
{
NvFlowPreprocessorSkipWhitespaceTokens(&keyTokenIdx, keyTokenCount, keyTokens);
NvFlowPreprocessorSkipWhitespaceTokens(&sourceTokenIdx, sourceTokenCount, sourceTokens);
if (keyTokenIdx < keyTokenCount)
{
keyTestCount++;
}
if (keyTokenIdx < keyTokenCount && sourceTokenIdx < sourceTokenCount)
{
if (keyTokens[keyTokenIdx].type == sourceTokens[sourceTokenIdx].type)
{
if (keyTokens[keyTokenIdx].type == eNvFlowPreprocessorTokenType_name)
{
if (NvFlowStringCompare(keyTokens[keyTokenIdx].str, sourceTokens[sourceTokenIdx].str) == 0)
{
matches++;
}
}
else
{
matches++;
}
}
}
keyTokenIdx++;
sourceTokenIdx++;
}
if (pSourceIndex)
{
*pSourceIndex += sourceTokenIdx;
}
return (matches > 0 && matches == keyTestCount) ? NV_FLOW_TRUE : NV_FLOW_FALSE;
}
NvFlowPreprocessorRange NvFlowPreprocessorExtractTokensDelimitedN(NvFlowPreprocessor* ptr, NvFlowUint64* pTokenIdx, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens, NvFlowUint64 numDelimiters, const NvFlowPreprocessorTokenType* delimiters)
{
NvFlowUint64 beginTokenIdx = (*pTokenIdx);
NvFlowPreprocessorRange range = { beginTokenIdx, beginTokenIdx };
if (numDelimiters > 0u)
{
NvFlowUint64 localTokenIdx = beginTokenIdx;
range = NvFlowPreprocessorExtractTokensDelimited(ptr, &localTokenIdx, numTokens, tokens, delimiters[0u]);
(*pTokenIdx) = localTokenIdx;
}
for (NvFlowUint64 delimiterIdx = 1u; delimiterIdx < numDelimiters; delimiterIdx++)
{
NvFlowUint64 localTokenIdx = beginTokenIdx;
NvFlowPreprocessorRange localRange = NvFlowPreprocessorExtractTokensDelimited(ptr, &localTokenIdx, numTokens, tokens, delimiters[delimiterIdx]);
if (localRange.end < range.end)
{
range = localRange;
(*pTokenIdx) = localTokenIdx;
}
}
return range;
}
NvFlowPreprocessorRange NvFlowPreprocessorExtractTokensDelimited(NvFlowPreprocessor* ptr, NvFlowUint64* pTokenIdx, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens, NvFlowPreprocessorTokenType delimiter)
{
NvFlowPreprocessorRange range = { (*pTokenIdx), (*pTokenIdx) };
NvFlowPreprocessorTokenType rightType = eNvFlowPreprocessorTokenType_rightParenthesis;
NvFlowPreprocessorTokenType leftType = eNvFlowPreprocessorTokenType_leftParenthesis;
if (delimiter == eNvFlowPreprocessorTokenType_greaterThan)
{
rightType = eNvFlowPreprocessorTokenType_greaterThan;
leftType = eNvFlowPreprocessorTokenType_lessThan;
}
bool delimiterIsScopeEnd = (
delimiter == eNvFlowPreprocessorTokenType_rightParenthesis ||
delimiter == eNvFlowPreprocessorTokenType_rightBracket ||
delimiter == eNvFlowPreprocessorTokenType_rightCurlyBrace ||
delimiter == eNvFlowPreprocessorTokenType_greaterThan
);
int scopeIdx = delimiterIsScopeEnd ? 1 : 0;
for (; (*pTokenIdx) < numTokens; (*pTokenIdx)++)
{
// scope end is 'before' the end symbol
if (tokens[(*pTokenIdx)].type == eNvFlowPreprocessorTokenType_rightParenthesis ||
tokens[(*pTokenIdx)].type == eNvFlowPreprocessorTokenType_rightBracket ||
tokens[(*pTokenIdx)].type == eNvFlowPreprocessorTokenType_rightCurlyBrace ||
tokens[(*pTokenIdx)].type == rightType)
{
scopeIdx--;
}
if (scopeIdx == 0 && tokens[(*pTokenIdx)].type == delimiter)
{
(*pTokenIdx)++;
break;
}
else if (scopeIdx == 0 && delimiter == eNvFlowPreprocessorTokenType_anyWhitespace && NvFlowPreprocessorTokenIsWhitespace(tokens[(*pTokenIdx)]))
{
(*pTokenIdx)++;
break;
}
else
{
range.end++;
}
// scope begin is 'after' the start symbol
if (tokens[(*pTokenIdx)].type == eNvFlowPreprocessorTokenType_leftParenthesis ||
tokens[(*pTokenIdx)].type == eNvFlowPreprocessorTokenType_leftBracket ||
tokens[(*pTokenIdx)].type == eNvFlowPreprocessorTokenType_leftCurlyBrace ||
tokens[(*pTokenIdx)].type == leftType)
{
scopeIdx++;
}
}
return range;
}
const char* NvFlowPreprocessorExtractDelimitedN(NvFlowPreprocessor* ptr, NvFlowUint64* pTokenIdx, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens, NvFlowUint64 numDelimiters, const NvFlowPreprocessorTokenType* delimiters)
{
ptr->tempStrViews.size = 0u;
NvFlowPreprocessorSkipWhitespaceTokens(pTokenIdx, numTokens, tokens);
NvFlowPreprocessorRange range = NvFlowPreprocessorExtractTokensDelimitedN(ptr, pTokenIdx, numTokens, tokens, numDelimiters, delimiters);
NvFlowPreprocessorToken prevPushedToken = {};
for (NvFlowUint64 idx = range.begin; idx < range.end; idx++)
{
if (NvFlowPreprocessorTokenIsWhitespace(tokens[idx]))
{
continue;
}
else
{
if (tokens[idx].type == eNvFlowPreprocessorTokenType_name ||
tokens[idx].type == eNvFlowPreprocessorTokenType_number)
{
if (prevPushedToken.type == eNvFlowPreprocessorTokenType_name ||
prevPushedToken.type == eNvFlowPreprocessorTokenType_number)
{
ptr->tempStrViews.pushBack(" ");
}
}
ptr->tempStrViews.pushBack(tokens[idx].str);
prevPushedToken = tokens[idx];
}
}
char* output = NvFlowStringConcatN(ptr->stringPool, ptr->tempStrViews.data, ptr->tempStrViews.size);
ptr->tempStrViews.size = 0u;
return output;
}
const char* NvFlowPreprocessorExtractDelimited(NvFlowPreprocessor* ptr, NvFlowUint64* pTokenIdx, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens, NvFlowPreprocessorTokenType delimiter)
{
return NvFlowPreprocessorExtractDelimitedN(ptr, pTokenIdx, numTokens, tokens, 1u, &delimiter);
}
const char* NvFlowPreprocessorExtractDelimitedPreserve(NvFlowPreprocessor* ptr, NvFlowUint64* pTokenIdx, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens, NvFlowPreprocessorTokenType delimiter)
{
NvFlowPreprocessorRange range = NvFlowPreprocessorExtractTokensDelimited(ptr, pTokenIdx, numTokens, tokens, delimiter);
return NvFlowPreprocessorConcatTokens(ptr, tokens + range.begin, range.end - range.begin);
}
const char* NvFlowPreprocessorExtractIfType(NvFlowPreprocessor* ptr, NvFlowUint64* pTokenIdx, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens, NvFlowPreprocessorTokenType type)
{
const char* ret = nullptr;
NvFlowPreprocessorSkipWhitespaceTokens(pTokenIdx, numTokens, tokens);
if ((*pTokenIdx) < numTokens && tokens[(*pTokenIdx)].type == type)
{
ret = tokens[(*pTokenIdx)].str;
(*pTokenIdx)++;
}
return ret;
}
const char* NvFlowPreprocessorConcatTokens(NvFlowPreprocessor* ptr, const NvFlowPreprocessorToken* tokens, NvFlowUint64 numTokens)
{
ptr->tempStrViews.size = 0u;
for (NvFlowUint64 idx = 0u; idx < numTokens; idx++)
{
ptr->tempStrViews.pushBack(tokens[idx].str);
}
char* output = NvFlowStringConcatN(ptr->stringPool, ptr->tempStrViews.data, ptr->tempStrViews.size);
ptr->tempStrViews.size = 0u;
return output;
}
char* NvFlowPreprocessorExecute(NvFlowPreprocessor* ptr, const char* input)
{
// increment level
ptr->currentLevel++;
NvFlowUint64 stringStackBegin = ptr->stringStack.size;
// tokenize
NvFlowPreprocessorToken* tokenStack_data = nullptr;
NvFlowUint64 tokenStack_size = 0u;
NvFlowPreprocessorTokenize(ptr, input, &tokenStack_size, &tokenStack_data);
// process tokens
for (NvFlowUint64 tokenIdx = 0u; tokenIdx < tokenStack_size; tokenIdx++)
{
NvFlowPreprocessorToken firstToken = tokenStack_data[tokenIdx];
if (NvFlowPreprocessorTokenIsWhitespace(firstToken))
{
if (ptr->mode == eNvFlowPreprocessorMode_disable_passthrough)
{
// NOP
}
else
{
ptr->stringStack.pushBack(firstToken.str);
}
}
else
{
NvFlowUint64 itemIdx = 0u;
for (; itemIdx < ptr->items.size; itemIdx++)
{
const NvFlowPreprocessorItem item = ptr->items[itemIdx];
NvFlowUint64 compareSourceIdx = tokenIdx;
if (item.isEnabled && NvFlowPreprocessorFindKeyInSource(ptr,
item.tokens_data, item.tokens_size,
tokenStack_data + tokenIdx, tokenStack_size - tokenIdx,
&compareSourceIdx))
{
NvFlowUint64 childTokenBegin = tokenIdx;
NvFlowUint64 childTokenEnd = tokenIdx;
if (item.function.type == eNvFlowPreprocessorType_constant)
{
childTokenEnd = compareSourceIdx;
}
else if (item.function.type == eNvFlowPreprocessorType_statement)
{
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_semicolon);
}
else if (item.function.type == eNvFlowPreprocessorType_statementComma)
{
NvFlowPreprocessorTokenType delimiters[2u] = { eNvFlowPreprocessorTokenType_comma, eNvFlowPreprocessorTokenType_rightParenthesis };
NvFlowPreprocessorExtractTokensDelimitedN(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, 2u, delimiters);
}
else if (item.function.type == eNvFlowPreprocessorType_function)
{
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_leftParenthesis);
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_rightParenthesis);
}
else if (item.function.type == eNvFlowPreprocessorType_attribute)
{
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_leftBracket);
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_rightBracket);
}
else if (item.function.type == eNvFlowPreprocessorType_body)
{
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_leftCurlyBrace);
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_rightCurlyBrace);
}
else if (item.function.type == eNvFlowPreprocessorType_templateInstance)
{
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_lessThan);
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_greaterThan);
}
else if (item.function.type == eNvFlowPreprocessorType_index)
{
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_leftBracket);
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_rightBracket);
NvFlowUint64 childTokenEndWithEquals = childTokenEnd;
NvFlowPreprocessorSkipWhitespaceTokens(&childTokenEndWithEquals, tokenStack_size, tokenStack_data);
// check for =
if (childTokenEndWithEquals < tokenStack_size)
{
const NvFlowPreprocessorToken token = tokenStack_data[childTokenEndWithEquals];
if (token.type == eNvFlowPreprocessorTokenType_equals)
{
childTokenEndWithEquals++;
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEndWithEquals, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_semicolon);
// commit
childTokenEnd = childTokenEndWithEquals;
}
}
}
else if (item.function.type == eNvFlowPreprocessorType_line)
{
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_newline);
}
if (!ptr->items[itemIdx].function.allowRecursion)
{
ptr->items[itemIdx].isEnabled = NV_FLOW_FALSE; // disable recursion
}
if (item.function.substitute)
{
char* substituteStr = item.function.substitute(
ptr,
item.function.userdata,
childTokenEnd - childTokenBegin,
tokenStack_data + childTokenBegin
);
char* substituteOutput = nullptr;
if (ptr->mode == eNvFlowPreprocessorMode_singlePass)
{
substituteOutput = substituteStr;
}
else // eNvFlowPreprocessorModeDefault or eNvFlowPreprocessorMode_disable_passthrough
{
substituteOutput = NvFlowPreprocessorExecute(ptr, substituteStr);
}
ptr->stringStack.pushBack(substituteOutput);
}
if (!ptr->items[itemIdx].function.allowRecursion)
{
ptr->items[itemIdx].isEnabled = NV_FLOW_TRUE;
}
// advance tokenIdx
if (childTokenEnd > childTokenBegin)
{
tokenIdx += childTokenEnd - childTokenBegin - 1u;
}
break;
}
}
// If no match found, pass through token
if (itemIdx == ptr->items.size)
{
if (ptr->mode == eNvFlowPreprocessorMode_disable_passthrough)
{
// NOP
}
else
{
ptr->stringStack.pushBack(firstToken.str);
}
}
}
}
// pop string stack
NvFlowUint64 stringStackEnd = ptr->stringStack.size;
char* ret = NvFlowStringConcatN(ptr->stringPool, ptr->stringStack.data + stringStackBegin, stringStackEnd - stringStackBegin);
ptr->stringStack.size = stringStackBegin;
// decrement level
ptr->currentLevel--;
return ret;
}
char* NvFlowPreprocessorExecuteGlobal(NvFlowPreprocessor* ptr, const char* input, void* userdata, char*(*substitute)(NvFlowPreprocessor* ptr, void* userdata, NvFlowPreprocessorGlobalType globalType, NvFlowUint64 numTokens, const NvFlowPreprocessorToken* tokens))
{
// increment level
ptr->currentLevel++;
NvFlowUint64 stringStackBegin = ptr->stringStack.size;
// tokenize
NvFlowPreprocessorToken* tokenStack_data = nullptr;
NvFlowUint64 tokenStack_size = 0u;
NvFlowPreprocessorTokenize(ptr, input, &tokenStack_size, &tokenStack_data);
// process tokens
NvFlowUint64 tokenIdx = 0u;
while (tokenIdx < tokenStack_size)
{
NvFlowPreprocessorToken firstToken = tokenStack_data[tokenIdx];
// skip whitespace, but include in output stream
if (NvFlowPreprocessorTokenIsWhitespace(firstToken))
{
ptr->stringStack.pushBack(firstToken.str);
tokenIdx++;
continue;
}
NvFlowUint64 childTokenBegin = tokenIdx;
NvFlowUint64 childTokenEnd = tokenIdx;
NvFlowPreprocessorGlobalType globalType = eNvFlowPreprocessorGlobalType_unknown;
// check for # condition
if (firstToken.type == eNvFlowPreprocessorTokenType_pound)
{
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_newline);
globalType = eNvFlowPreprocessorGlobalType_line;
}
// check for [ condition
if (firstToken.type == eNvFlowPreprocessorTokenType_leftBracket)
{
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_leftBracket);
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_rightBracket);
globalType = eNvFlowPreprocessorGlobalType_attribute;
}
// attempt to detect a function declaration, unless line was detected
if (childTokenBegin == childTokenEnd)
{
// names and whitespace are acceptable up to initial (
while (childTokenEnd < tokenStack_size)
{
const NvFlowPreprocessorToken token = tokenStack_data[childTokenEnd];
if (!(token.type == eNvFlowPreprocessorTokenType_name || NvFlowPreprocessorTokenIsWhitespace(token)))
{
break;
}
childTokenEnd++;
}
if (childTokenBegin != childTokenEnd && tokenStack_data[childTokenEnd].type == eNvFlowPreprocessorTokenType_leftParenthesis)
{
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_leftParenthesis);
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_rightParenthesis);
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_leftCurlyBrace);
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_rightCurlyBrace);
globalType = eNvFlowPreprocessorGlobalType_function;
}
else
{
// invalidate
childTokenEnd = childTokenBegin;
}
}
// attempt to extract a simple statement
if (childTokenBegin == childTokenEnd)
{
NvFlowPreprocessorExtractTokensDelimited(ptr, &childTokenEnd, tokenStack_size, tokenStack_data, eNvFlowPreprocessorTokenType_semicolon);
globalType = eNvFlowPreprocessorGlobalType_statement;
}
if (childTokenBegin == childTokenEnd)
{
// not indentified, force advance
childTokenEnd++;
}
if (globalType != eNvFlowPreprocessorGlobalType_unknown)
{
char* substituteOutput = nullptr;
if (substitute)
{
substituteOutput = substitute(ptr, userdata, globalType, childTokenEnd - childTokenBegin, tokenStack_data + childTokenBegin);
}
if (substituteOutput)
{
ptr->stringStack.pushBack(substituteOutput);
}
}
else
{
for (NvFlowUint64 localTokenIdx = childTokenBegin; localTokenIdx < childTokenEnd; localTokenIdx++)
{
ptr->stringStack.pushBack(tokenStack_data[localTokenIdx].str);
}
}
// advance tokenIdx
tokenIdx = childTokenEnd;
}
// pop string stack
NvFlowUint64 stringStackEnd = ptr->stringStack.size;
char* ret = NvFlowStringConcatN(ptr->stringPool, ptr->stringStack.data + stringStackBegin, stringStackEnd - stringStackBegin);
ptr->stringStack.size = stringStackBegin;
// decrement level
ptr->currentLevel--;
return ret;
}
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/pyproject.toml | [tool.poetry]
name = "openusd-code-samples"
version = "1.1.0"
description = "Universal Scene Description (OpenUSD) code samples in Python, C++, and USDA for common development features and tasks."
license = "Apache-2.0"
authors = []
readme = "README.md"
packages = [{include = "source"}]
[tool.poetry.dependencies]
python = ">=3.8, <3.11"
numpy = "1.24.1"
usd-core = "23.5"
types-usd = "~23.5.4"
[tool.poetry.group.docs.dependencies]
myst-parser = "0.18.0"
rstcloth = "0.5.4"
Sphinx = "4.5.0"
sphinx-design = "0.2.0"
sphinx-rtd-theme = "1.0.0"
toml = "0.10.2"
# Pinned for security patches
certifi = "2023.7.22"
markdown-it-py = "2.2.0"
pygments = "2.16.1"
requests = "2.31.0"
urllib3 = "1.26.18"
jinja2 = "3.1.3"
[tool.poetry.dev-dependencies]
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/CODE-SAMPLE-GUIDELINES.md | # Code Sample Guidelines
## Samples Format
This image shows the file structure that contains two Code Samples for cameras.

Our Code Samples are stored in the source directory, organized by categories. Each sample has their files, including the actual sample code, in their own directory.
In this example, we have two camera Code Samples. The paths to these two Code Samples folders are the following:
`source/cameras/create-orthographic-camera`
`source/cameras/create-perspective-camera`
**Within each Code Sample folder are the following files:**
| File(s) | Purpose |
| -----|----- |
| config.toml | Contains the title, metadata: description and SEO keywords |
| header.md | The overview for this code sample |
| Code Sample "flavor" file(s) | See below |
| Markdown file for each "flavor" | See below |
The header file is an overview for all of the flavors. It can contain markdown formatting including URL's and markdown directives.
**Each Code Sample should have at least one "flavor":**
| Flavor Source File Name | Language and USD type |
| -----|----- |
| py_usd.py | Python using Pixar USD API |
| py_omni_usd.py | Python using omni.usd extension |
| py_kit_cmds.py | Python using Kit commands |
| cpp_usd.cpp | C++ using Pixar USD API |
| cpp_omni_usd.cpp | C++ using omni.usd extension |
| cpp_kit_cmds.cpp | C++ using Kit commands |
| usda.usda | USDA (text) file |
Each flavor can have more than one sample (variations). In this case we append _var< X >, where X starts with 1 and increments for as many sample variations needed.
Example: `py_usd.py`, `py_usd_var1.py`, `py_usd_var2.py `, etc...
**Markdown files:**
Every flavor that has a sample needs exactly one markdown file, no matter how many variations are included. They will have the same name as the flavor, but with the .md extension.
Example, if you have some `py_usd.py` samples you'll need a `py_usd.md` file. In the markdown file you'll need to use the `literalinclude` directive.
Example:
```
**Convert to Numpy Array**
To convert a VtArray to a Numpy Array, simply pass the VtArray object to `numpy.array` constructor.
``` {literalinclude} py_usd.py
:language: py
```
**Convert from Numpy Array**
To convert a Numpy Array to a VtArray, you can use `FromNumpy()` from the VtArray class you want to convert to.
``` {literalinclude} py_usd_var1.py
:language: py
```
```
This example includes two samples, with a description for each one.
| Language code | File type |
| -----|----- |
| py | Python |
| c++ | C++/cpp |
| usd | USDA |
## Building the Samples
When all of your files are in place you should build and verify your samples are correctly setup by running the build script:
```
>poetry run python build_docs.py
```
If there are no errors, you can then view it by loading the ``index.html`` file, in the ``sphinx/_build folder``, in a browser.

There are two ways to do this. The first way:
1) Select the ``index.html`` file
2) Right click and select ``Copy Path``
3) Paste the path into address bar of your web browser

The second way:
1) select the ``index.html`` file so it's showing in a VS Code window
2) Press ``Alt-B`` and it will be launched in your default web browser.
## Markdown Cheatsheet
### Links
Create links using typical markdown syntax.
Here's an external link:
[USD Data Types documentation](https://docs.omniverse.nvidia.com/dev-guide/latest/dev_usd/quick-start/usd-types.html)
You can also link to other code samples using relative paths. Here's a link to a code sample in the same category:
[Add a Payload](add-payload)
Use the folder name for the code sample. The folder name will be the final markdown/HTML file name.
Here's a link to a code sample in different category:
[Add a Payload](../prims/check-prim-exists)
### Admonitions
https://myst-parser.readthedocs.io/en/latest/syntax/admonitions.html
```{tip}
https://myst-parser.readthedocs.io/en/latest/syntax/admonitions.html
```
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/CONTRIBUTING.md |
## OpenUSD Code Samples OSS Contribution Rules
#### Issue Tracking
* All enhancement, bugfix, or change requests must begin with the creation of a [OpenUSD Code Samples Issue Request](https://github.com/NVIDIA-Omniverse/OpenUSD-Code-Samples/issues).
* The issue request must be reviewed by OpenUSD Code Samples engineers and approved prior to code review.
#### Coding Guidelines
- All source code contributions must strictly adhere to the [OpenUSD Code Samples Guidelines](CODE-SAMPLE-GUIDELINES.md).
- In addition, please follow the existing conventions in the relevant file, submodule, module, and project when you add new code or when you extend/fix existing functionality.
- Avoid introducing unnecessary complexity into existing code so that maintainability and readability are preserved.
- All development should happen against the "main" branch of the repository. Please make sure the base branch of your pull request is set to the "main" branch when filing your pull request.
- Try to keep pull requests (PRs) as concise as possible:
- Avoid committing commented-out code.
- Wherever possible, each PR should address a single concern. If there are several otherwise-unrelated things that should be fixed to reach a desired endpoint, our recommendation is to open several PRs and indicate the dependencies in the description. The more complex the changes are in a single PR, the more time it will take to review those changes.
- Write commit titles using imperative mood and [these rules](https://chris.beams.io/posts/git-commit/), and reference the Issue number corresponding to the PR. Following is the recommended format for commit texts:
```
Issue #<Issue Number> - <Commit Title>
<Commit Body>
```
- Ensure that the Sphinx build log is clean, meaning no warnings or errors should be present.
- Ensure that all code blocks execute correctly prior to submitting your code.
- All OSS components must contain accompanying documentation (READMEs) describing the functionality, dependencies, and known issues.
- See `README.md` for existing samples and plugins for reference.
- All OSS components must have an accompanying test.
- If introducing a new component, such as a plugin, provide a test sample to verify the functionality.
- Make sure that you can contribute your work to open source (no license and/or patent conflict is introduced by your code). You will need to [`sign`](#signing-your-work) your commit.
- Thanks in advance for your patience as we review your contributions; we do appreciate them!
#### Pull Requests
Developer workflow for code contributions is as follows:
1. Developers must first [fork](https://help.github.com/en/articles/fork-a-repo) the [upstream](https://github.com/NVIDIA-Omniverse/OpenUSD-Code-Samples) OpenUSD Code Samples repository.
2. Git clone the forked repository.
```bash
git clone https://github.com/YOUR_USERNAME/YOUR_FORK.git OpenUSD-Code-Samples
```
3. Create a branch off of the "main" branch and commit changes. See [Coding Guidelines](#coding-guidelines) for commit formatting rules.
```bash
# Create a branch off of the "main" branch
git checkout -b <local-branch> <remote-branch>
git add <path-to-files>
# -s flag will "sign-off" on your commit, we require all contributors to sign-off on their commits. See below for more
git commit -s -m "Issue #<Issue Number> - <Commit Title>"
```
4. Push Changes to the personal fork.
```bash
# Push the commits to a branch on the fork (remote).
git push -u origin <local-branch>:<remote-branch>
```
5. Please make sure that your pull requests are clean. Use the rebase and squash git facilities as needed to ensure that the pull request is as clean as possible.
6. Once the code changes are staged on the fork and ready for review, a [Pull Request](https://help.github.com/en/articles/about-pull-requests) (PR) can be [requested](https://help.github.com/en/articles/creating-a-pull-request) to merge the changes from your branch to the upstream "main" branch.
* Exercise caution when selecting the source and target branches for the PR.
* Creation of a PR creation kicks off the code review process.
* At least one OpenUSD Code Samples engineer will be assigned for the review.
* While under review, mark your PRs as work-in-progress by prefixing the PR title with [WIP].
7. Since there is no CI/CD process in place yet, the PR will be accepted and the corresponding issue closed only after adequate testing has been completed, manually, by the developer and/or OpenUSD Code Samples engineer reviewing the code.
#### Signing Your Work
* We require that all contributors "sign-off" on their commits. This certifies that the contribution is your original work, or you have rights to submit it under the same license, or a compatible license.
* Any contribution which contains commits that are not Signed-Off will not be accepted.
* To sign off on a commit you simply use the `--signoff` (or `-s`) option when committing your changes:
```bash
$ git commit -s -m "Add cool feature."
```
This will append the following to your commit message:
```
Signed-off-by: Your Name <[email protected]>
```
* Full text of the DCO:
```
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
``` |
NVIDIA-Omniverse/OpenUSD-Code-Samples/build_docs.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import argparse
import logging
import os
from pathlib import Path
import shutil
from rstcloth import RstCloth
import sphinx.cmd.build
import toml
REPO_ROOT = Path(__file__).parent
SOURCE_DIR = REPO_ROOT / "source"
SPHINX_DIR = REPO_ROOT / "sphinx"
SPHINX_CODE_SAMPLES_DIR = SPHINX_DIR / "usd"
# 0 = normal toctree, 1 = :doc: tags
TOCTREE_STYLE = 0
REPLACE_USDA_EXT = True
STRIP_COPYRIGHTS = True
IMAGE_TYPES = {".jpg" , ".gif"}
logger = logging.getLogger(__name__)
def main():
# flush build dir
if os.path.exists(SPHINX_CODE_SAMPLES_DIR):
shutil.rmtree(SPHINX_CODE_SAMPLES_DIR)
SPHINX_CODE_SAMPLES_DIR.mkdir(exist_ok=False)
samples = {}
# each config.toml should be a sample
for config_file in SOURCE_DIR.rglob("config.toml"):
category_name = config_file.parent.parent.name
sample_name = config_file.parent.name
if category_name not in samples:
samples[category_name] = []
logger.info(f"processing: {sample_name}")
sample_source_dir = config_file.parent
sample_output_dir = SPHINX_CODE_SAMPLES_DIR / sample_source_dir.parent.relative_to(SOURCE_DIR) / f"{sample_name}"
# make sure category dir exists
category_output_dir = SPHINX_CODE_SAMPLES_DIR / sample_source_dir.parent.relative_to(SOURCE_DIR)
if not os.path.exists(category_output_dir):
category_output_dir.mkdir(exist_ok=False)
sample_rst_out = category_output_dir / f"{sample_name}.rst"
with open(config_file) as f:
content = f.read()
config = toml.loads(content)
title = config["core"]["title"]
samples[category_name].append([sample_name, title])
sample_output_dir.mkdir(exist_ok=True)
with open(sample_rst_out, "w") as f:
doc = RstCloth(f)
if TOCTREE_STYLE == 1:
doc._add(":orphan:")
doc.newline()
doc.directive("meta",
fields=[
('description', config["metadata"]["description"]),
('keywords', ", ".join(config["metadata"]["keywords"]))
])
doc.newline()
doc.title(config["core"]["title"], overline=False)
doc.newline()
md_file_path = sample_source_dir / "header.md"
new_md_name = sample_name + "_header.md"
out_md = category_output_dir / new_md_name
prepend_include_path(md_file_path, out_md, sample_name)
fields = [("parser" , "myst_parser.sphinx_")]
doc.directive( "include", new_md_name, fields)
doc.newline()
doc.newline()
doc.directive("tab-set")
doc.newline()
code_flavors = {"USD Python" : "py_usd.md",
"Python omni.usd" : "py_omni_usd.md",
"Python Kit Commands" : "py_kit_cmds.md",
"USD C++" : "cpp_usd.md",
"C++ omni.usd" : "cpp_omni_usd.md",
"C++ Kit Commands" : "cpp_kit_cmds.md",
"usdview": "py_usdview.md",
"USDA" : "usda.md",
}
for tab_name in code_flavors:
md_file_name = code_flavors[tab_name]
md_file_path = sample_source_dir / code_flavors[tab_name]
if md_file_path.exists():
doc.directive("tab-item", tab_name, None, None, 3)
doc.newline()
# make sure all md flavor names are unique
new_md_name = sample_name + "_" + md_file_name
category_output_dir
out_md = category_output_dir / new_md_name
prepend_include_path(md_file_path, out_md, sample_name)
fields = [("parser" , "myst_parser.sphinx_")]
doc.directive( "include", new_md_name, fields, None, 6)
doc.newline()
# copy all samples
ignore=shutil.ignore_patterns('*.md', 'config.toml')
if REPLACE_USDA_EXT:
ignore=shutil.ignore_patterns('*.md', 'config.toml', '*.usda')
shutil.copytree(sample_source_dir, sample_output_dir, ignore=ignore, dirs_exist_ok=True )
# copy any usda's to .py
if REPLACE_USDA_EXT:
for filename in os.listdir(sample_source_dir):
base_file, ext = os.path.splitext(filename)
if ext == ".usda":
orig = str(sample_source_dir) + "/" + filename
newname = str(sample_output_dir) + "/" + str(base_file) + ".py"
shutil.copy(orig, newname)
# strip out copyright comments in output files
if STRIP_COPYRIGHTS:
for filename in os.listdir(sample_output_dir):
full_path = os.path.join(sample_output_dir, filename)
strip_copyrights(full_path)
doc.newline()
generate_sphinx_index(samples)
sphinx.cmd.build.main([str(SPHINX_DIR), str(SPHINX_DIR / "_build"), "-b", "html"])
def strip_copyrights(filename):
base_file, ext = os.path.splitext(filename)
if ext in IMAGE_TYPES:
print(f"strip_copyrights, skip image :: {filename}")
return
with open(filename) as sample_file:
sample_lines = sample_file.readlines()
# strip copyrights
# .py
while sample_lines[0].startswith("# SPDX-"):
sample_lines.pop(0)
# .cpp
while sample_lines[0].startswith("// SPDX-"):
sample_lines.pop(0)
# get rid of empty spacer line
if len(sample_lines[0].strip()) < 1:
sample_lines.pop(0)
with open(filename, "w") as sample_file:
for line in sample_lines:
sample_file.write(line)
def prepend_include_path(in_file_path: str, out_file_path: str, dir_path: str):
with open(in_file_path) as mdf:
md_data = mdf.read()
md_lines = md_data.split("\n")
lc = 0
for line in md_lines:
inc_str ="``` {literalinclude}"
sp = line.split(inc_str)
if len(sp) > 1:
filename = sp[1].strip()
if REPLACE_USDA_EXT:
sfn = filename.split(".")
if len(sfn) > 1 and sfn[1] == "usda":
filename = sfn[0] + ".py"
newl = inc_str + " " + dir_path + "/" + filename
md_lines[lc] = newl
lc += 1
with open(out_file_path,"w") as nmdf:
for line in md_lines:
nmdf.writelines(line + "\n")
def generate_sphinx_index(samples):
cat_names_path = SOURCE_DIR / "category-display-names.toml"
cat_names = toml.load(cat_names_path)["name_mappings"]
print(f"CAT_NAMES: {cat_names}")
ref_links = {"variant-sets" : "variant_sets_ref"}
index_rst = SPHINX_DIR / "usd.rst"
with open(index_rst, "w") as f:
doc = RstCloth(f)
doc.directive("include", "usd_header.rst")
doc.newline()
#doc.title("OpenUSD Code Samples")
for category, cat_samples in samples.items():
if category in ref_links:
doc.ref_target(ref_links[category])
doc.newline()
human_readable = readable_from_category_dir_name(category)
if category in cat_names.keys():
human_readable = cat_names[category]
doc.h2(human_readable)
fields = [
#("caption", human_readable),
("titlesonly", ""),
]
doc.newline()
if TOCTREE_STYLE == 0:
sample_paths = [f"usd/{category}/{sample[0]}" for sample in cat_samples]
doc.directive("toctree", None, fields, sample_paths)
doc.newline()
elif TOCTREE_STYLE == 1:
#doc.h2(human_readable)
doc.newline()
for sample, title in cat_samples:
doc._add("- :doc:`" + title + f" <usd/{category}/" + sample + ">`")
doc.newline()
doc.directive("include", "usd_footer.rst")
doc.newline()
def readable_from_category_dir_name(category):
sub_strs = category.split("-")
readable = ""
for sub in sub_strs:
readable += sub.capitalize() + " "
return readable.strip()
if __name__ == "__main__":
# Create an argument parser
parser = argparse.ArgumentParser(description='Build rST documentation from code sample source.')
# Parse the arguments
args = parser.parse_args()
logging.basicConfig(level=logging.INFO)
main() |
NVIDIA-Omniverse/OpenUSD-Code-Samples/README.md | # OpenUSD Code Samples
[](https://opensource.org/licenses/Apache-2.0) [](https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref/usd.html)
This repository contains useful Universal Scene Description (OpenUSD) code samples in Python, C++, and USDA. If you want to browse the code samples to use them, you can see them fully rendered in the [OpenUSD Code Samples documentation](https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref/usd.html) page.
## Configuration
This repository uses [Poetry](https://python-poetry.org/docs/) for dependency management. If you're new to Poetry, you don't need to know much more than the commands we use in the [build instructions](#How-to-Build). To make it easier when authoring code samples and contributing, we recommend installing:
1. Install any version of Python between versions 3.8-3.10 .
1. [Install Poetry](https://python-poetry.org/docs/#installation)
## How to Build
1. `poetry install`
1. `poetry run python build_docs.py`
1. In a web browser, open `sphinx/_build/index.html`
## Have an Idea for a New Code Sample?
Ideas for new code samples that could help other developers are always welcome. Please [create a new issue](https://github.com/NVIDIA-Omniverse/OpenUSD-Code-Samples/issues) requesting a new code sample and add the _new request_ label. Someone from the NVIDIA team or OpenUSD community will pick it up. If you can contribute it yourself, even better!
## Find a Typo or an Error?
Please let us know if you find any mistakes or non-working code samples. [File an issue](https://github.com/NVIDIA-Omniverse/OpenUSD-Code-Samples/issues) with a _bug_ label to let us know and so we can address it.
## Contributing
Contributions are welcome! If you would like to contribute, please read our [Contributing Guidelines](./CONTRIBUTING.md) to understand how to contribute. Also, check out the [Code Sample Guidelines](CODE-SAMPLE-GUIDELINES.md) to understand how code samples file and folders are structured in this repository and how to adhere to follow our code samples style.
## Disclosures
The goal of this repository is to help developers learn OpenUSD and be more productive. To that end, NVIDIA reserves the right to use the source code and documentation in this repository for the purpose of training and/or benchmarking of an AI code assistant for OpenUSD developers.
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/py_kit_cmds.md | Here you can add any info specific to the code sample flavor and introduce the code sample.
You should include your code sample as a separate source code file like this:
``` {literalinclude} py_kit_cmds.py
:language: py
```
You should use these includes instead of putting code in markdown code blocks. The first source code file should be named the same as the markdown file. If you want to show any variations of the code sample of expand it, you should then include source code files with the suffix `_var#`.
Variations are not required and you generally won't need them, but it's available if you find you code sample could benefit from showing variations. |
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/py_usd.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# Add all the imports that you need for you snippets
from pxr import Usd, Sdf, UsdGeom
def descriptive_code_sample_name(stage: Usd.Stage, prim_path: str="/World/MyPerspCam") -> UsdGeom.Camera:
"""Docstring is optional. Use Google style docstrings if you choose to add them.
The code sample should be defined as a function. As a descriptive name for the function.
Use function arguments to:
- Pass in any objects that your code sample expects to exist (e.g. a Stage)
- Pass in Paths rather than hard-coding them.
Use type-hinting to help learners understand what type every variable is. Don't assume they'll know.
Args:
stage (Usd.Stage): _description_
prim_path (str, optional): _description_. Defaults to "/World/MyPerspCam".
Returns:
UsdGeom.Camera: _description_
"""
camera_path = Sdf.Path(prim_path)
usd_camera: UsdGeom.Camera = UsdGeom.Camera.Define(stage, camera_path)
usd_camera.CreateProjectionAttr().Set(UsdGeom.Tokens.perspective)
return usd_camera
#############
# Full Usage
#############
# Here you will show your code sample in context. Add any additional imports
# that you may need for your "Full Usage" code
# You can create an in-memory stage and do any stage setup before calling
# you code sample.
stage: Usd.Stage = Usd.Stage.CreateInMemory()
default_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World"))
stage.SetDefaultPrim(default_prim.GetPrim())
cam_path = default_prim.GetPath().AppendPath("MyPerspCam")
# Call your code sample function
camera = descriptive_code_sample_name(stage, cam_path)
# print out the result
usda = stage.GetRootLayer().ExportToString()
print(usda)
# Do some basic asserts to show learners how to interact with the results.
prim = camera.GetPrim()
assert prim.IsValid()
assert camera.GetPath() == Sdf.Path(cam_path)
assert prim.GetTypeName() == "Camera"
projection = camera.GetProjectionAttr().Get()
assert projection == UsdGeom.Tokens.perspective
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/usda.usda | #usda 1.0
(
defaultPrim = "World"
)
def Xform "World"
{
} |
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/py_omni_usd.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Source code for code block in the py_omni_usd flavor. See the py_usd.py for a
full example of writing a code sample.
You should use omni.usd.get_stage() instead of creating an in-memory stage
for the Full Usage part since this is meant to run in Omniverse.
""" |
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/py_usd.md | Here you can add any info specific to the code sample flavor and introduce the code sample.
You should include your code sample as a separate source code file like this:
``` {literalinclude} py_usd.py
:language: py
```
You should use these includes instead of putting code in markdown code blocks. The first source code file should be named the same as the markdown file. If you want to show any variations of the code sample of expand it, you should then include source code files with the suffix `_var#`.
``` {literalinclude} py_usd_var1.py
:language: py
```
Variations are not required and you generally won't need them, but it's available if you find you code sample could benefit from showing variations. |
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/py_kit_cmds.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Source code for code block in the py_kit_cmds flavor. See the py_usd.py for a
full example of writing a code sample.
You should use omni.usd.get_stage() instead of creating an in-memory stage
for the Full Usage part since this is meant to run in Omniverse.
""" |
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/usda.md | Here you can say something before showing the USDA example. You can use the usda string generated by the py_usd flavor.
``` {literalinclude} usda.usda
:language: c++
``` |
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/config.toml | [core]
# The title for this code sample. Used to name the page.
title = "My Code Example Code Sample"
[metadata]
#A concise description of the code sample for SEO.
description = "Universal Scene Description (OpenUSD) code samples to show how to contribute."
# Put in SEO keywords relevant to this code sample.
keywords = ["OpenUSD", "USD", "code sample", "snippet", "Python", "C++", "example"] |
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/py_omni_usd.md | Here you can add any info specific to the code sample flavor and introduce the code sample.
You should include your code sample as a separate source code file like this:
``` {literalinclude} py_omni_usd.py
:language: py
```
You should use these includes instead of putting code in markdown code blocks. The first source code file should be named the same as the markdown file. If you want to show any variations of the code sample of expand it, you should then include source code files with the suffix `_var#`.
Variations are not required and you generally won't need them, but it's available if you find you code sample could benefit from showing variations. |
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/py_usd_var1.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Source code for another code block in the py_usd flavor. See the py_usd.py for a
full example of writing a code sample.
""" |
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/header.md | This is a general introduction to the code sample. This show talk generally about USD concepts and not be too specific to any one code sample flavor. You don't need to add the code sample title above this header. That will be autogenerated from the `config.toml`. The code sample flavors will be rendered below this.
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/category-display-names.toml | [name_mappings]
hierarchy-traversal = "Hierarchy & Traversal"
references-payloads = "References & Payloads"
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-orthographic-camera/py_kit_cmds.md | The `CreatePrimWithDefaultXform` command in Kit can create a Camera prim and you can optionally set camera attributes values during creation. You must use the attribute token names as the keys for the `attributes` dictionary. In Omniverse applications, you can explore the names by hovering over a property label in the Property Window and reading it from the tooltip.
``` {literalinclude} py_kit_cmds.py
:language: py
``` |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-orthographic-camera/py_usd.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from pxr import Sdf, Usd, UsdGeom
def create_orthographic_camera(stage: Usd.Stage, prim_path: str="/World/MyOrthoCam") -> UsdGeom.Camera:
"""Create an orthographic camera
Args:
stage (Usd.Stage): A USD Stage to create the camera on.
prim_path (str, optional): The prim path for where to create the camera. Defaults to "/World/MyOrthoCam".
"""
camera_path = Sdf.Path(prim_path)
usd_camera = UsdGeom.Camera.Define(stage, camera_path)
usd_camera.CreateProjectionAttr().Set(UsdGeom.Tokens.orthographic)
return usd_camera
#############
# Full Usage
#############
cam_path = "/World/MyOrthoCam"
stage: Usd.Stage = Usd.Stage.CreateInMemory()
root_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World"))
stage.SetDefaultPrim(root_prim.GetPrim())
camera = create_orthographic_camera(stage, cam_path)
usda = stage.GetRootLayer().ExportToString()
print(usda)
# Check that the camera was created
prim = camera.GetPrim()
assert prim.IsValid()
assert camera.GetPath() == Sdf.Path(cam_path)
assert prim.GetTypeName() == "Camera"
projection = camera.GetProjectionAttr().Get()
assert projection == UsdGeom.Tokens.orthographic
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-orthographic-camera/usda.usda | #usda 1.0
(
defaultPrim = "World"
)
def Xform "World"
{
def Camera "MyOrthoCam"
{
token projection = "orthographic"
}
}
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-orthographic-camera/py_usd.md | ``` {literalinclude} py_usd.py
:language: py
```
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-orthographic-camera/py_kit_cmds.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import omni.kit.commands
from pxr import UsdGeom
def create_orthographic_camera(prim_path: str="/World/MyOrthoCam"):
"""Create an orthographic camera
Args:
prim_path (str, optional): The prim path where the camera should be created. Defaults to "/World/MyOrthoCam".
"""
omni.kit.commands.execute("CreatePrimWithDefaultXform",
prim_type="Camera",
prim_path="/World/MyOrthoCam",
attributes={"projection": UsdGeom.Tokens.orthographic}
)
#############
# Full Usage
#############
import omni.usd
# Create an orthographic camera at /World/MyOrthoCam
path = "/World/MyOrthoCam"
create_orthographic_camera(path)
# Check that the camera was created
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath(path)
assert prim.IsValid() == True
assert prim.GetTypeName() == "Camera"
projection = prim.GetAttribute("projection").Get()
assert projection == UsdGeom.Tokens.orthographic |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-orthographic-camera/usda.md | This is an example USDA result from creating a Camera and setting the `projection` to `orthographic`. All other Properties are using the default values from the `UsdGeomCamera` schema definition.
``` {literalinclude} usda.usda
:language: usd
``` |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-orthographic-camera/config.toml | [core]
title = "Create an Orthographic Camera"
[metadata]
description = "Universal Scene Description (OpenUSD) code samples for creating an orthographic camera prim."
keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "camera", "UsdGeom", "Orthographic"] |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-orthographic-camera/header.md | You can define a new camera on a stage using `UsdGeom.Camera`. The Camera prim has a `projection` attribute that can be set to `orthographic`.
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-perspective-camera/py_kit_cmds.md | The `CreatePrimWithDefaultXform` command in Kit can create a Camera prim and you can optionally set camera attributes values during creation. You must use the attribute token names as the keys for the `attributes` dictionary. In Omniverse applications, you can explore the names by hovering over a property label in the Property Window and reading it from the tooltip.
``` {literalinclude} py_kit_cmds.py
:language: py
``` |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-perspective-camera/py_usd.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from pxr import Usd, Sdf, UsdGeom
def create_perspective_camera(stage: Usd.Stage, prim_path: str="/World/MyPerspCam") -> UsdGeom.Camera:
camera_path = Sdf.Path(prim_path)
usd_camera: UsdGeom.Camera = UsdGeom.Camera.Define(stage, camera_path)
usd_camera.CreateProjectionAttr().Set(UsdGeom.Tokens.perspective)
return usd_camera
#############
# Full Usage
#############
# Create an in-memory Stage with /World Xform prim as the default prim
stage: Usd.Stage = Usd.Stage.CreateInMemory()
default_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World"))
stage.SetDefaultPrim(default_prim.GetPrim())
# Create the perspective camera at /World/MyPerspCam
cam_path = default_prim.GetPath().AppendPath("MyPerspCam")
camera = create_perspective_camera(stage, cam_path)
# Export the complete Stage as a string and print it.
usda = stage.GetRootLayer().ExportToString()
print(usda)
# Check that the camera was created
prim = camera.GetPrim()
assert prim.IsValid()
assert camera.GetPath() == Sdf.Path(cam_path)
assert prim.GetTypeName() == "Camera"
projection = camera.GetProjectionAttr().Get()
assert projection == UsdGeom.Tokens.perspective
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-perspective-camera/usda.usda | #usda 1.0
(
defaultPrim = "World"
)
def Xform "World"
{
def Camera "MyPerspCam"
{
token projection = "perspective"
}
}
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-perspective-camera/py_usd.md | With the USD API, you can use `UsdGeom.Camera.CreateProjectionAttr()` to create the `projection` attribute and then set the value with `Usd.Attribute.Set()`.
``` {literalinclude} py_usd.py
:language: py
```
Here is how to you can set some other common attributes on the camera:
``` {literalinclude} py_usd_var1.py
:language: py
``` |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-perspective-camera/py_kit_cmds.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import omni.kit.commands
from pxr import UsdGeom
def create_perspective_camera(prim_path: str="/World/MyPerspCam"):
"""Create a perspective camera
Args:
prim_path (str, optional): The prim path where the camera should be created. Defaults to "/World/MyPerspCam".
"""
omni.kit.commands.execute("CreatePrimWithDefaultXform",
prim_type="Camera",
prim_path=prim_path,
attributes={
"projection": UsdGeom.Tokens.perspective,
"focalLength": 35,
"horizontalAperture": 20.955,
"verticalAperture": 15.2908,
"clippingRange": (0.1, 100000)
}
)
#############
# Full Usage
#############
import omni.usd
# Create a perspective camera at /World/MyPerspCam
path = "/World/MyPerspCam"
create_perspective_camera(path)
# Check that the camera was created
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath(path)
assert prim.IsValid() == True
assert prim.GetTypeName() == "Camera"
projection = prim.GetAttribute("projection").Get()
assert projection == UsdGeom.Tokens.perspective |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-perspective-camera/usda.md | This is an example USDA result from creating a Camera and setting the `projection` to `perspective`. All other Properties are using the default values from the `UsdGeomCamera` schema definition.
``` {literalinclude} usda.usda
:language: usd
``` |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-perspective-camera/config.toml | [core]
title = "Create a Perspective Camera"
[metadata]
description = "Universal Scene Description (OpenUSD) code sample to create a perspective camera."
keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "camera", "perspective"] |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-perspective-camera/py_usd_var1.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from pxr import Usd, Sdf, UsdGeom
def create_perspective_35mm_camera(stage: Usd.Stage, prim_path: str="/World/MyPerspCam") -> UsdGeom.Camera:
camera_path = Sdf.Path(prim_path)
usd_camera: UsdGeom.Camera = UsdGeom.Camera.Define(stage, camera_path)
usd_camera.CreateProjectionAttr().Set(UsdGeom.Tokens.perspective)
usd_camera.CreateFocalLengthAttr().Set(35)
# Set a few other common attributes too.
usd_camera.CreateHorizontalApertureAttr().Set(20.955)
usd_camera.CreateVerticalApertureAttr().Set(15.2908)
usd_camera.CreateClippingRangeAttr().Set((0.1,100000))
return usd_camera
#############
# Full Usage
#############
# Create an in-memory Stage with /World Xform prim as the default prim
stage: Usd.Stage = Usd.Stage.CreateInMemory()
default_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World"))
stage.SetDefaultPrim(default_prim.GetPrim())
# Create the perspective camera at path /World/MyPerspCam with 35mm
# set for the focal length.
cam_path = default_prim.GetPath().AppendPath("MyPerspCam")
camera = create_perspective_35mm_camera(stage, cam_path)
# Export the complete Stage as a string and print it.
usda = stage.GetRootLayer().ExportToString()
print(usda)
# Check the camera attributes
focal_len = camera.GetFocalLengthAttr().Get()
assert focal_len == 35.0
clip_range = camera.GetClippingRangeAttr().Get()
assert clip_range == (0.1,100000)
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-perspective-camera/header.md | You can define a new camera on a stage using `UsdGeom.Camera`. The Camera prim has a `projection` attribute that can be set to `perspective`.
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/visibility/show-hide-prim/py_kit_cmds.md | You can use the `ChangeProperty` command from the `omni.kit.commands` extension to change the attribute of any prim. In Omniverse applications, you can discover the attribute name by hovering over the label in the Property Window and inspecting the tooltip.
You can find more information about the Kit command API at the [omni.kit.commands extension documentation](https://docs.omniverse.nvidia.com/kit/docs/omni.kit.commands/latest/API.html).
``` {literalinclude} py_kit_cmds.py
:language: py
``` |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/visibility/show-hide-prim/py_usd.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from typing import Union
from pxr import Sdf, Usd, UsdGeom
def get_visibility_attribute(
stage: Usd.Stage, prim_path: str
) -> Union[Usd.Attribute, None]:
"""Return the visibility attribute of a prim"""
path = Sdf.Path(prim_path)
prim = stage.GetPrimAtPath(path)
if not prim.IsValid():
return None
visibility_attribute = prim.GetAttribute("visibility")
return visibility_attribute
def hide_prim(stage: Usd.Stage, prim_path: str):
"""Hide a prim
Args:
stage (Usd.Stage, required): The USD Stage
prim_path (str, required): The prim path of the prim to hide
"""
visibility_attribute = get_visibility_attribute(stage, prim_path)
if visibility_attribute is None:
return
visibility_attribute.Set("invisible")
def show_prim(stage: Usd.Stage, prim_path: str):
"""Show a prim
Args:
stage (Usd.Stage, required): The USD Stage
prim_path (str, required): The prim path of the prim to show
"""
visibility_attribute = get_visibility_attribute(stage, prim_path)
if visibility_attribute is None:
return
visibility_attribute.Set("inherited")
#############
# Full Usage
#############
# Here you will show your code sample in context. Add any additional imports
# that you may need for your "Full Usage" code
# Create a simple in-memory stage with a Cube
stage: Usd.Stage = Usd.Stage.CreateInMemory()
default_prim_path = Sdf.Path("/World")
default_prim = UsdGeom.Xform.Define(stage, default_prim_path)
stage.SetDefaultPrim(default_prim.GetPrim())
cube_path = default_prim_path.AppendPath("Cube")
cube = UsdGeom.Cube.Define(stage, cube_path)
# The prim is initially visible. Assert so and then demonstrate how to toggle
# it off and on
assert get_visibility_attribute(stage, cube_path).Get() == "inherited"
hide_prim(stage, cube_path)
assert get_visibility_attribute(stage, cube_path).Get() == "invisible"
show_prim(stage, cube_path)
assert get_visibility_attribute(stage, cube_path).Get() == "inherited"
# Print the USDA out
usda = stage.GetRootLayer().ExportToString()
print(usda)
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/visibility/show-hide-prim/usda.usda | #usda 1.0
(
defaultPrim = "World"
)
def Xform "World"
{
def Cube "Cube"
{
token visibility = "inherited"
}
}
|
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/visibility/show-hide-prim/py_usd.md | You can use the USD API [Usd.Prim.GetAttribute()](https://openusd.org/release/api/class_usd_prim.html#a31225ac7165f58726f000ab1d67e9e61) to get an attribute of a prim and then use [Usd.Attribute.Set()](https://openusd.org/release/api/class_usd_attribute.html#a151e6fde58bbd911da8322911a3c0079) to change the value. The attribute name for visibility is `visibility` and you can set it to the value of `inherited` or `invisible`.
``` {literalinclude} py_usd.py
:language: py
``` |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/visibility/show-hide-prim/py_kit_cmds.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import omni.kit.commands
import omni.usd
from pxr import Sdf
def hide_prim(prim_path: str):
"""Hide a prim
Args:
prim_path (str, required): The prim path of the prim to hide
"""
set_prim_visibility_attribute(prim_path, "invisible")
def show_prim(prim_path: str):
"""Show a prim
Args:
prim_path (str, required): The prim path of the prim to show
"""
set_prim_visibility_attribute(prim_path, "inherited")
def set_prim_visibility_attribute(prim_path: str, value: str):
"""Set the prim visibility attribute at prim_path to value
Args:
prim_path (str, required): The path of the prim to modify
value (str, required): The value of the visibility attribute
"""
# You can reference attributes using the path syntax by appending the
# attribute name with a leading `.`
prop_path = f"{prim_path}.visibility"
omni.kit.commands.execute(
"ChangeProperty", prop_path=Sdf.Path(prop_path), value=value, prev=None
)
"""
Full Usage
"""
# Path to a prim in the open stage
prim_path = "/World/Cube"
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath(prim_path)
assert prim.IsValid()
# Manually confirm that the prim is not visible in the viewport after calling
# hide_prim. You should comment out the below show_prim call and assert.
hide_prim(prim_path)
assert prim.GetAttribute("visibility").Get() == "invisible"
# Manually confirm that the prim is visible in the viewport after calling
# show_prim
show_prim(prim_path)
assert prim.GetAttribute("visibility").Get() == "inherited"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.